ddi-fw 0.0.247__py3-none-any.whl → 0.0.249__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.
@@ -3,7 +3,7 @@ import pandas as pd
3
3
  from uuid import uuid4
4
4
  from langchain_community.vectorstores.faiss import FAISS
5
5
  from langchain_community.docstore.in_memory import InMemoryDocstore
6
- from typing import Callable, Optional, Dict, Any
6
+ from typing import Callable, Optional, Dict, Any, Type
7
7
  from langchain_core.documents import Document
8
8
  import numpy as np # optional, if you're using NumPy vectors
9
9
  from langchain_core.embeddings import Embeddings
@@ -11,6 +11,8 @@ from langchain_core.embeddings import Embeddings
11
11
  from pydantic import BaseModel, Field
12
12
  from langchain_core.embeddings import Embeddings
13
13
  from langchain_core.vectorstores import VectorStore
14
+ from ddi_fw.utils import get_import
15
+ from langchain.document_loaders import DataFrameLoader
14
16
 
15
17
  class BaseVectorStoreManager(BaseModel):
16
18
  embeddings: Optional[Embeddings] = None
@@ -54,7 +56,9 @@ class FaissVectorStoreManager(BaseVectorStoreManager):
54
56
  # uuids = [str(uuid4()) for _ in range(len(docs))]
55
57
  # self.vector_store.add_documents(documents=docs, ids=uuids)
56
58
 
57
- def initialize_embedding_dict(self):
59
+ def initialize_embedding_dict(self, **kwargs):
60
+ vector_db_persist_directory = kwargs.get("vector_db_persist_directory")
61
+ self.load(vector_db_persist_directory)
58
62
  df = self.as_dataframe(formatter_fn=custom_formatter )
59
63
  type_dict = (
60
64
  df.groupby('type')
@@ -240,3 +244,106 @@ def custom_formatter(document: Document, vector: np.ndarray) -> Dict[str, Any]:
240
244
  "type": document.metadata.get("type", None),
241
245
  "embedding": vector
242
246
  }
247
+
248
+ def load_configuration(config_file):
249
+ """
250
+ Load the configuration from a JSON file.
251
+ """
252
+ import json
253
+ with open(config_file, 'r') as f:
254
+ config = json.load(f)
255
+ return config
256
+
257
+
258
+ def generate_embeddings(
259
+ df,
260
+ vector_store_manager_type:Type[BaseVectorStoreManager],
261
+ config_file,
262
+ new_model_names,
263
+ collections,
264
+ persist_directory="embeddings",
265
+ ):
266
+ """
267
+ Generate embeddings for collections based on a configuration file.
268
+
269
+ collections: List of collections that contain metadata for embedding generation.
270
+ config_file: Path to the configuration file containing model settings.
271
+ new_model_names: List of model names to generate embeddings for.
272
+ vector_store_manager_type: Class type of the vector store manager (e.g., FaissVectorStoreManager or ChromaVectorStoreManager)
273
+ """
274
+ if not collections and not config_file:
275
+ raise ValueError("Either 'collections' or 'config_file' must be provided.")
276
+ if collections and config_file:
277
+ raise ValueError("Only one of 'collections' or 'config_file' should be provided.")
278
+
279
+ if not collections:
280
+ collections = load_configuration(config_file)
281
+
282
+ for collection_config in collections:
283
+ id = collection_config['id']
284
+ name = collection_config['name']
285
+
286
+ if name not in new_model_names:
287
+ continue
288
+
289
+ embedding_model_type = collection_config.get('embedding_model_type')
290
+ text_splitters_types = collection_config.get('text_splitters_types')
291
+ batch_size = collection_config.get('batch_size')
292
+ partial_df_size = collection_config.get('partial_dataframe_size')
293
+ columns = collection_config.get('columns')
294
+ page_content_columns = collection_config.get('page_content_columns')
295
+ persist_dir = f'{persist_directory}/{id}'
296
+
297
+ # Load embedding model
298
+ try:
299
+ model_kwargs = collection_config.get('model_kwargs')
300
+ model = get_import(embedding_model_type)(
301
+ model_name=name, **model_kwargs)
302
+ except Exception as e:
303
+ raise Exception(f"Unknown embedding model: {embedding_model_type}") from e
304
+
305
+ # Load text splitters
306
+ text_splitters = []
307
+ text_splitters_suffixes = []
308
+ for text_splitter_type in text_splitters_types:
309
+ try:
310
+ type_of_text_splitter = get_import(
311
+ text_splitter_type.get("type"))
312
+ kwargs = text_splitter_type.get("params")
313
+ suffix = text_splitter_type.get("suffix")
314
+ if kwargs:
315
+ text_splitter = type_of_text_splitter(**kwargs)
316
+ else:
317
+ text_splitter = type_of_text_splitter()
318
+ text_splitters.append(text_splitter)
319
+ text_splitters_suffixes.append(suffix)
320
+ except Exception as e:
321
+ raise Exception(f"Unknown text splitter: {text_splitter_type}") from e
322
+
323
+ for text_splitter, suffix in zip(text_splitters, text_splitters_suffixes):
324
+ print(f"{id}_{suffix}")
325
+
326
+ # Prepare manager parameters
327
+ manager_params = {
328
+ "collection_name": f"{id}_{suffix}",
329
+ "persist_directory": persist_dir,
330
+ "embeddings": model,
331
+ "text_splitter": text_splitter,
332
+ "batch_size": batch_size
333
+ }
334
+
335
+ # Instantiate the manager class
336
+ vector_store_manager = vector_store_manager_type(**manager_params)
337
+
338
+ # Prepare documents
339
+ # You may need to use a DataFrameLoader or similar to convert df to LangChain Documents
340
+ loader = DataFrameLoader(
341
+ data_frame=df, page_content_column=page_content_columns[0]
342
+ )
343
+ docs = loader.load()
344
+
345
+ # Generate vector store
346
+ vector_store_manager.generate_vector_store(docs)
347
+
348
+ # Optionally persist/save
349
+ vector_store_manager.save(persist_dir)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ddi_fw
3
- Version: 0.0.247
3
+ Version: 0.0.249
4
4
  Summary: Do not use :)
5
5
  Author-email: Kıvanç Bayraktar <bayraktarkivanc@gmail.com>
6
6
  Maintainer-email: Kıvanç Bayraktar <bayraktarkivanc@gmail.com>
@@ -6,7 +6,7 @@ ddi_fw/datasets/setup_._py,sha256=khYVJuW5PlOY_i_A16F3UbSZ6s6o_ljw33Byw3C-A8E,10
6
6
  ddi_fw/langchain/__init__.py,sha256=xGNaTEZCUxyc_aT1zvzVWGRfsj-9VXqMvPKtV_G7ChA,399
7
7
  ddi_fw/langchain/chroma_storage.py,sha256=7LSUhdiPdQHZvKC_NapOeVbHtS71iE5ABZVTrI0YQ-A,15520
8
8
  ddi_fw/langchain/embeddings.py,sha256=eEWy4okcjdhUJHi4N48Wd8XauPXyeaQVLUdNWEvtEcY,6754
9
- ddi_fw/langchain/faiss_storage.py,sha256=b-PStwJHeRl9ZYGC7ql5p5ak1Xk2-A6TTEL1UqmhxVI,9220
9
+ ddi_fw/langchain/faiss_storage.py,sha256=26ZrbTUtGux-Yg0eCjQ1Z7PNE6tagyOh2mcWZPUO-0I,13552
10
10
  ddi_fw/langchain/sentence_splitter.py,sha256=h_bYElx4Ud1mwDNJfL7mUwvgadwKX3GKlSzu5L2PXzg,280
11
11
  ddi_fw/langchain/storage.py,sha256=OizKyWm74Js7T6Q9kez-ulUoBGzIMFo4R46h4kjUyIM,11200
12
12
  ddi_fw/ml/__init__.py,sha256=FteYEawCkVQOaK-cTv2VrHZ2ZnfeFr31BD6VucO7_DQ,268
@@ -38,7 +38,7 @@ ddi_fw/utils/zip_helper.py,sha256=YRZA4tKZVBJwGQM0_WK6L-y5MoqkKoC-nXuuHK6CU9I,55
38
38
  ddi_fw/vectorization/__init__.py,sha256=LcJOpLVoLvHPDw9phGFlUQGeNcST_zKV-Oi1Pm5h_nE,110
39
39
  ddi_fw/vectorization/feature_vector_generation.py,sha256=QQQGhCti653BdU343Ag1bH_g1fzi2hlic7dgNy7otjE,7694
40
40
  ddi_fw/vectorization/idf_helper.py,sha256=_Gd1dtDSLaw8o-o0JugzSKMt9FpeXewTh4wGEaUd4VQ,2571
41
- ddi_fw-0.0.247.dist-info/METADATA,sha256=GXPSYB036ezCw_7o3HxjXgxw5sdpD3gjjJ0Mr_hJ2Fk,2623
42
- ddi_fw-0.0.247.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
43
- ddi_fw-0.0.247.dist-info/top_level.txt,sha256=PMwHICFZTZtcpzQNPV4UQnfNXYIeLR_Ste-Wfc1h810,7
44
- ddi_fw-0.0.247.dist-info/RECORD,,
41
+ ddi_fw-0.0.249.dist-info/METADATA,sha256=2Q4PILzRCK4EOfTvjIVuv57oM4nhb-NJ7pgZJz9Uyhc,2623
42
+ ddi_fw-0.0.249.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
43
+ ddi_fw-0.0.249.dist-info/top_level.txt,sha256=PMwHICFZTZtcpzQNPV4UQnfNXYIeLR_Ste-Wfc1h810,7
44
+ ddi_fw-0.0.249.dist-info/RECORD,,