beekeeper-ai 0.6.6__py3-none-any.whl → 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. beekeeper/_bundle/__init__.py +0 -0
  2. beekeeper_ai-1.0.0.dist-info/METADATA +41 -0
  3. beekeeper_ai-1.0.0.dist-info/RECORD +5 -0
  4. {beekeeper_ai-0.6.6.dist-info → beekeeper_ai-1.0.0.dist-info}/WHEEL +1 -1
  5. beekeeper_ai-1.0.0.dist-info/licenses/LICENSE +176 -0
  6. beekeeper/__init__.py +0 -1
  7. beekeeper/core/document/__init__.py +0 -6
  8. beekeeper/core/document/schema.py +0 -97
  9. beekeeper/core/document_loaders/__init__.py +0 -5
  10. beekeeper/core/document_loaders/base.py +0 -24
  11. beekeeper/core/embeddings/__init__.py +0 -6
  12. beekeeper/core/embeddings/base.py +0 -44
  13. beekeeper/core/text_splitters/utils.py +0 -142
  14. beekeeper/core/utils/pairwise.py +0 -20
  15. beekeeper/document_loaders/__init__.py +0 -17
  16. beekeeper/document_loaders/directory.py +0 -65
  17. beekeeper/document_loaders/docx.py +0 -31
  18. beekeeper/document_loaders/html.py +0 -77
  19. beekeeper/document_loaders/json.py +0 -53
  20. beekeeper/document_loaders/pdf.py +0 -38
  21. beekeeper/document_loaders/s3.py +0 -72
  22. beekeeper/document_loaders/watson_discovery.py +0 -121
  23. beekeeper/embeddings/__init__.py +0 -7
  24. beekeeper/embeddings/huggingface.py +0 -66
  25. beekeeper/embeddings/watsonx.py +0 -100
  26. beekeeper/evaluation/__init__.py +0 -5
  27. beekeeper/evaluation/knowledge_base_coverage.py +0 -62
  28. beekeeper/monitor/__init__.py +0 -11
  29. beekeeper/monitor/watsonx.py +0 -843
  30. beekeeper/retrievers/__init__.py +0 -5
  31. beekeeper/retrievers/watson_discovery.py +0 -121
  32. beekeeper/text_splitters/__init__.py +0 -9
  33. beekeeper/text_splitters/semantic.py +0 -139
  34. beekeeper/text_splitters/sentence.py +0 -107
  35. beekeeper/text_splitters/token.py +0 -101
  36. beekeeper/vector_stores/__init__.py +0 -7
  37. beekeeper/vector_stores/chroma.py +0 -115
  38. beekeeper/vector_stores/elasticsearch.py +0 -183
  39. beekeeper_ai-0.6.6.dist-info/LICENSE +0 -7
  40. beekeeper_ai-0.6.6.dist-info/METADATA +0 -49
  41. beekeeper_ai-0.6.6.dist-info/RECORD +0 -37
File without changes
@@ -0,0 +1,41 @@
1
+ Metadata-Version: 2.4
2
+ Name: beekeeper-ai
3
+ Version: 1.0.0
4
+ Summary: Load any data in one line of code and connect with AI applications
5
+ Project-URL: Repository, https://github.com/leonardofurnielis/beekeeper
6
+ Author-email: Leonardo Furnielis <leonardofurnielis@outlook.com>
7
+ License: Apache-2.0
8
+ License-File: LICENSE
9
+ Keywords: AI,LLM,QA,RAG,data,observability,retrieval,semantic-search
10
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
11
+ Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
12
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
13
+ Requires-Python: <4.0,>=3.10
14
+ Requires-Dist: beekeeper-core<2.0.0,>=1.0.0
15
+ Requires-Dist: beekeeper-embeddings-huggingface<2.0.0,>=1.0.0
16
+ Requires-Dist: beekeeper-llms-litellm<2.0.0,>=1.0.0
17
+ Requires-Dist: beekeeper-readers-file<2.0.0,>=1.0.0
18
+ Provides-Extra: dev
19
+ Requires-Dist: ruff>=0.11.13; extra == 'dev'
20
+ Provides-Extra: docs
21
+ Requires-Dist: furo>=2024.8.6; extra == 'docs'
22
+ Requires-Dist: sphinx-copybutton>=0.5.2; extra == 'docs'
23
+ Requires-Dist: sphinx-favicon>=1.0.1; extra == 'docs'
24
+ Requires-Dist: sphinx>=8.1.3; extra == 'docs'
25
+ Description-Content-Type: text/markdown
26
+
27
+ ![PyPI - Version](https://img.shields.io/pypi/v/beekeeper-ai)
28
+ [![Hatch project](https://img.shields.io/badge/%F0%9F%A5%9A-Hatch-4051b5.svg)](https://github.com/pypa/hatch)
29
+ ![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)
30
+ ![Pepy Total Downloads](https://img.shields.io/pepy/dt/beekeeper-ai)
31
+ ![PyPI - License](https://img.shields.io/pypi/l/beekeeper-ai)
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ pip install beekeeper-ai
37
+ ```
38
+
39
+ ## 📄 Documentation
40
+
41
+ Please check it out for overview of the interfaces, components, integrations and other resources!
@@ -0,0 +1,5 @@
1
+ beekeeper/_bundle/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ beekeeper_ai-1.0.0.dist-info/METADATA,sha256=8rF-ReDUGG-5wJrVqWjU9CwEoVcd4ERPvlcqfyTOAtU,1776
3
+ beekeeper_ai-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
4
+ beekeeper_ai-1.0.0.dist-info/licenses/LICENSE,sha256=bR2Wj7Il7KNny38LiDGrASo12StUfpReF--OewXD5cw,10349
5
+ beekeeper_ai-1.0.0.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 1.9.1
2
+ Generator: hatchling 1.27.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
beekeeper/__init__.py DELETED
@@ -1 +0,0 @@
1
- __version__ = "0.6.6"
@@ -1,6 +0,0 @@
1
- from beekeeper.core.document.schema import Document, DocumentWithScore
2
-
3
- __all__ = [
4
- "Document",
5
- "DocumentWithScore"
6
- ]
@@ -1,97 +0,0 @@
1
- import uuid
2
- from abc import ABC, abstractmethod
3
- from dataclasses import dataclass
4
- from typing import TYPE_CHECKING, Any, Dict, Optional
5
-
6
- from pydantic.v1 import BaseModel, Field, validator
7
-
8
- if TYPE_CHECKING:
9
- from langchain_core.documents import Document as LangChainDocument
10
-
11
-
12
- class BaseDocument(ABC, BaseModel):
13
- """Generic abstract interface for retrievable documents."""
14
-
15
- doc_id: str = Field(
16
- default_factory=lambda: str(uuid.uuid4()),
17
- description="Unique ID of the document.")
18
- metadata: Dict[str, Any] = Field(
19
- default_factory=dict,
20
- description="A flat dictionary of metadata fields.")
21
-
22
- @validator("metadata", pre=True)
23
- def _validate_metadata(cls, v) -> Dict:
24
- if v is None:
25
- return {}
26
- return v
27
-
28
- @abstractmethod
29
- def get_content(self) -> str:
30
- """Get document content."""
31
-
32
- @abstractmethod
33
- def get_metadata(self) -> str:
34
- """Get metadata."""
35
-
36
-
37
- class Document(BaseDocument):
38
- """Generic interface for data document."""
39
-
40
- text: str = Field(default="", description="Text content of the document.")
41
-
42
- @classmethod
43
- def class_name(cls) -> str:
44
- return "Document"
45
-
46
- def get_content(self) -> str:
47
- """Get the text content."""
48
- return self.text
49
-
50
- def get_metadata(self) -> dict:
51
- """Get metadata."""
52
- return self.metadata
53
-
54
- @classmethod
55
- def from_langchain_format(cls, doc: "LangChainDocument") -> "Document":
56
- """
57
- Convert a document from LangChain format.
58
-
59
- Args:
60
- doc (LangChainDocument): Document in LangChain format.
61
- """
62
- return cls(text=doc.page_content, metadata=doc.metadata)
63
-
64
-
65
- @dataclass
66
- class DocumentWithScore:
67
- document: BaseDocument
68
- score: Optional[float] = None
69
-
70
- @classmethod
71
- def class_name(cls) -> str:
72
- return "DocumentWithScore"
73
-
74
- def get_score(self) -> float:
75
- """Get score."""
76
- if self.score is None:
77
- return 0.0
78
- else:
79
- return self.score
80
-
81
- # #### pass through methods to BaseDocument ####
82
- @property
83
- def doc_id(self) -> str:
84
- return self.document.doc_id
85
-
86
- @property
87
- def text(self) -> str:
88
- if isinstance(self.document, Document):
89
- return self.document.text
90
- else:
91
- raise ValueError("Must be a Document to get text")
92
-
93
- def get_content(self) -> str:
94
- return self.document.get_content()
95
-
96
- def get_metadata(self) -> str:
97
- return self.document.get_metadata()
@@ -1,5 +0,0 @@
1
- from beekeeper.core.document_loaders.base import BaseLoader
2
-
3
- __all__ = [
4
- "BaseLoader",
5
- ]
@@ -1,24 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- from typing import List, Optional
3
-
4
- from pydantic.v1 import BaseModel
5
-
6
- from beekeeper.core.document import Document
7
-
8
-
9
- class BaseLoader(ABC, BaseModel):
10
- """An interface for document loader."""
11
-
12
- @classmethod
13
- def class_name(cls) -> str:
14
- return "BaseLoader"
15
-
16
- @abstractmethod
17
- def load_data(self, extra_info: Optional[dict] = None) -> List[Document]:
18
- """Loads data."""
19
-
20
- def load(self) -> List[Document]:
21
- return self.load_data()
22
-
23
- def lazy_load(self) -> List[Document]:
24
- return self.load_data()
@@ -1,6 +0,0 @@
1
- from beekeeper.core.embeddings.base import BaseEmbedding, Embedding
2
-
3
- __all__ = [
4
- "BaseEmbedding",
5
- "Embedding",
6
- ]
@@ -1,44 +0,0 @@
1
- from abc import ABC, abstractmethod
2
- from typing import List, Literal
3
-
4
- import numpy as np
5
-
6
- from beekeeper.core.utils.pairwise import cosine_similarity
7
-
8
- Embedding = List[float]
9
-
10
-
11
- class BaseEmbedding(ABC):
12
- """An interface for embedding models."""
13
-
14
- @classmethod
15
- def class_name(cls) -> str:
16
- return "BaseEmbedding"
17
-
18
- @abstractmethod
19
- def get_query_embedding(self, query: str) -> Embedding:
20
- """Get query embedding."""
21
-
22
- @abstractmethod
23
- def get_texts_embedding(self, texts: List[str]) -> List[Embedding]:
24
- """Get text embeddings."""
25
-
26
- @abstractmethod
27
- def get_documents_embedding(self, documents: List[str]) -> List[Embedding]:
28
- """Get documents embeddings."""
29
-
30
- def embed_documents(self, texts: List[str]) -> List[Embedding]:
31
- return self.get_texts_embedding(texts=texts)
32
-
33
- @staticmethod
34
- def similarity(embedding1: Embedding, embedding2: Embedding,
35
- mode: Literal["cosine", "dot_product", "euclidean"] = "cosine"):
36
- """Get embedding similarity."""
37
- if mode == "euclidean":
38
- return -float(np.linalg.norm(np.array(embedding1) - np.array(embedding2)))
39
-
40
- elif mode == "dot_product":
41
- return np.dot(embedding1, embedding2)
42
-
43
- else:
44
- return cosine_similarity(embedding1, embedding2)
@@ -1,142 +0,0 @@
1
- from typing import Callable, List, Tuple
2
-
3
-
4
- def tokenizer(text: str) -> List:
5
- try:
6
- import tiktoken
7
- except ImportError:
8
- raise ImportError("tiktoken package not found, please install it with `pip install tiktoken`")
9
-
10
- enc = tiktoken.get_encoding("cl100k_base")
11
- return enc.encode(text)
12
-
13
-
14
- def split_by_sep(sep) -> Callable[[str], List[str]]:
15
- """Split text by separator."""
16
- return lambda text: text.split(sep)
17
-
18
-
19
- def split_by_regex(regex: str) -> Callable[[str], List[str]]:
20
- """Split text by regex."""
21
- import re
22
-
23
- return lambda text: re.findall(regex, text)
24
-
25
-
26
- def split_by_char() -> Callable[[str], List[str]]:
27
- """Split text by character."""
28
- return lambda text: list(text)
29
-
30
-
31
- def split_by_sentence_tokenizer() -> Callable[[str], List[str]]:
32
- try:
33
- import nltk
34
- except ImportError:
35
- raise ImportError("nltk package not found, please install it with `pip install nltk`")
36
-
37
- sentence_tokenizer = nltk.tokenize.PunktSentenceTokenizer()
38
- return lambda text: _split_by_sentence_tokenizer(text, sentence_tokenizer)
39
-
40
-
41
- def _split_by_sentence_tokenizer(text: str, sentence_tokenizer) -> List[str]:
42
- """Get the spans and then return the sentences.
43
-
44
- Using the start index of each span
45
- Instead of using end, use the start of the next span
46
- """
47
- spans = list(sentence_tokenizer.span_tokenize(text))
48
- sentences = []
49
- for i, span in enumerate(spans):
50
- start = span[0]
51
- if i < len(spans) - 1:
52
- end = spans[i + 1][0]
53
- else:
54
- end = len(text)
55
- sentences.append(text[start:end])
56
- return sentences
57
-
58
-
59
- def split_by_fns(text: str,
60
- split_fns: List[Callable],
61
- sub_split_fns: List[Callable] = None) -> Tuple[List[str], bool]:
62
- """Split text by defined list of split functions."""
63
- if not split_fns:
64
- raise ValueError("Must provide a `split_fns` parameter")
65
-
66
- for split_fn in split_fns:
67
- splits = split_fn(text)
68
- if len(splits) > 1:
69
- return splits, True
70
-
71
- if sub_split_fns: # noqa: RET503
72
- for split_fn in sub_split_fns: # noqa: RET503
73
- splits = split_fn(text)
74
- if len(splits) > 1:
75
- return splits, False
76
-
77
-
78
- def merge_splits(splits: List[dict],
79
- chunk_size: int,
80
- chunk_overlap: int) -> List[str]:
81
- """Merge splits into chunks."""
82
- chunks: List[str] = []
83
- cur_chunk: List[Tuple[str, int]] = []
84
- cur_chunk_len = 0
85
- last_chunk: List[Tuple[str, int]] = []
86
- new_chunk = True
87
-
88
- def close_chunk() -> None:
89
- nonlocal chunks, cur_chunk, last_chunk, cur_chunk_len, new_chunk
90
-
91
- chunks.append("".join([text for text, length in cur_chunk]))
92
- last_chunk = cur_chunk
93
- cur_chunk = []
94
- cur_chunk_len = 0
95
- new_chunk = True
96
-
97
- # add overlap to the next chunk using previous chunk
98
- if len(last_chunk) > 0:
99
- last_index = len(last_chunk) - 1
100
- while (
101
- last_index >= 0
102
- and cur_chunk_len + last_chunk[last_index][1] <= chunk_overlap):
103
- text, length = last_chunk[last_index]
104
- cur_chunk_len += length
105
- cur_chunk.insert(0, (text, length))
106
- last_index -= 1
107
-
108
- def postprocess_chunks(_chunks: List[str]) -> List[str]:
109
- """Post-process chunks."""
110
- post_chunks = []
111
- for _chunk in _chunks:
112
- stripped_chunk = _chunk.strip()
113
- if stripped_chunk == "":
114
- continue
115
- post_chunks.append(stripped_chunk)
116
- return post_chunks
117
-
118
- while len(splits) > 0:
119
- cur_split = splits[0]
120
-
121
- if cur_split["token_size"] > chunk_size:
122
- raise ValueError("Got a split size that exceeded chunk size")
123
-
124
- if cur_chunk_len + cur_split["token_size"] > chunk_size and not new_chunk:
125
- close_chunk()
126
- else:
127
- if (cur_split["is_sentence"]
128
- or cur_chunk_len + cur_split["token_size"] <= chunk_size
129
- or new_chunk): # If `new_chunk`, always add at least one split
130
-
131
- cur_chunk_len += cur_split["token_size"]
132
- cur_chunk.append((cur_split["text"], cur_split["token_size"]))
133
- splits.pop(0)
134
- new_chunk = False
135
- else:
136
- close_chunk()
137
-
138
- if not new_chunk:
139
- chunk = "".join([text for text, length in cur_chunk])
140
- chunks.append(chunk)
141
-
142
- return postprocess_chunks(chunks)
@@ -1,20 +0,0 @@
1
- from typing import List
2
-
3
- import numpy as np
4
-
5
- Matrix = List[float]
6
-
7
- def cosine_similarity(X: Matrix, Y: Matrix) -> np.ndarray:
8
- """Row-wise cosine similarity between two equal-width matrices."""
9
- X = np.array(X)
10
- Y = np.array(Y)
11
-
12
- if X.shape[0] != Y.shape[0]:
13
- raise ValueError(
14
- f"Number of rows in X and Y must be the same. X has shape {X.shape} "
15
- f"and Y has shape {Y.shape}."
16
- )
17
- product = np.dot(X, Y)
18
- norm = np.linalg.norm(X) * np.linalg.norm(Y)
19
-
20
- return product / norm
@@ -1,17 +0,0 @@
1
- from beekeeper.document_loaders.directory import DirectoryLoader
2
- from beekeeper.document_loaders.docx import DocxLoader
3
- from beekeeper.document_loaders.html import HTMLLoader
4
- from beekeeper.document_loaders.json import JSONLoader
5
- from beekeeper.document_loaders.pdf import PDFLoader
6
- from beekeeper.document_loaders.s3 import S3Loader
7
- from beekeeper.document_loaders.watson_discovery import WatsonDiscoveryLoader
8
-
9
- __all__ = [
10
- "DirectoryLoader",
11
- "DocxLoader",
12
- "HTMLLoader",
13
- "JSONLoader",
14
- "PDFLoader",
15
- "S3Loader",
16
- "WatsonDiscoveryLoader",
17
- ]
@@ -1,65 +0,0 @@
1
- import glob
2
- import os
3
- from pathlib import Path
4
- from typing import List, Optional, Type
5
-
6
- from beekeeper.core.document import Document
7
- from beekeeper.core.document_loaders import BaseLoader
8
-
9
-
10
- def _loading_default_supported_loaders():
11
- from beekeeper.document_loaders import DocxLoader, HTMLLoader, PDFLoader
12
-
13
- return {
14
- ".docx": DocxLoader,
15
- ".html": HTMLLoader,
16
- ".pdf": PDFLoader,
17
- }
18
-
19
-
20
- class DirectoryLoader(BaseLoader):
21
- """Simple directory loader.
22
-
23
- Args:
24
- required_exts: (List[str], optional): List of file extensions to only load files with those extensions.
25
- recursive (str, optional): Whether to recursively search for files. Defaults to ``False``.
26
- """
27
-
28
- required_exts: List[str] = [".pdf", ".docx", ".html"]
29
- recursive: Optional[bool] = False
30
- file_loader: Optional[dict[str, Type[BaseLoader]]] = None
31
-
32
- def load_data(self, input_dir: str, extra_info: Optional[dict] = None) -> List[Document]:
33
- """Loads data from the specified directory.
34
-
35
- Args:
36
- input_dir (str): Directory path from which to load the documents.
37
- """
38
- if not os.path.isdir(input_dir):
39
- raise ValueError(f"`{input_dir}` is not a valid directory.")
40
-
41
- if self.file_loader is None:
42
- self.file_loader = _loading_default_supported_loaders()
43
-
44
- input_dir = Path(input_dir)
45
- documents = []
46
-
47
- pattern_prefix = "**/*" if self.recursive else ""
48
-
49
- for extension in self.required_exts:
50
- files = glob.glob(os.path.join(input_dir, pattern_prefix + extension), recursive=self.recursive)
51
-
52
- for file_dir in files:
53
- loader_cls = self.file_loader.get(extension)
54
- if loader_cls:
55
- try:
56
- #TO-DO add `file_loader_kwargs`
57
- doc = loader_cls().load_data(file_dir)
58
- documents.extend(doc)
59
- except Exception as e:
60
- raise f"Error reading {file_dir}: {e}"
61
- else:
62
- #TO-DO add `unstructured file` support
63
- raise f"Unsupported file type: {extension}"
64
-
65
- return documents