embedding-flow 0.1.0__tar.gz

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.
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
@@ -0,0 +1,7 @@
1
+ include README.md
2
+ include LICENSE
3
+ include requirements.txt
4
+ recursive-include contracts *.py
5
+ recursive-include transform *.py
6
+ recursive-include load *.py
7
+
@@ -0,0 +1,22 @@
1
+ Metadata-Version: 2.4
2
+ Name: embedding-flow
3
+ Version: 0.1.0
4
+ Summary: Pipeline to transform text chunks into embeddings and load to Qdrant
5
+ Author: facuvega
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.10
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.10
13
+ License-File: LICENSE
14
+ Requires-Dist: pandas>=2.0.0
15
+ Requires-Dist: pyarrow>=12.0.0
16
+ Requires-Dist: sentence-transformers>=2.2.0
17
+ Requires-Dist: torch>=2.0.0
18
+ Requires-Dist: qdrant-client>=1.7.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
21
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
22
+ Dynamic: license-file
@@ -0,0 +1,40 @@
1
+ # embedding-flow
2
+
3
+ Pipeline for transforming text chunks into 768-dimensional embeddings and loading to Qdrant.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install embedding-flow
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```python
14
+ from transform.transform import transform_embedding
15
+ from load.load import load_embedding
16
+
17
+ # Transform
18
+ transformer = transform_embedding()
19
+ output_path = transformer.transform_data("chunks.parquet")
20
+
21
+ # Load to Qdrant
22
+ loader = load_embedding()
23
+ loader.load_data(output_path)
24
+ ```
25
+
26
+ ## Environment Variables
27
+
28
+ ```bash
29
+ QDRANT_URL=http://localhost:6333
30
+ QDRANT_COLLECTION=embeddings_collection
31
+ VECTOR_SIZE=768
32
+ ```
33
+
34
+ ## Development
35
+
36
+ ```bash
37
+ pip install -e ".[dev]"
38
+ pytest tests/
39
+ ```
40
+
File without changes
@@ -0,0 +1,14 @@
1
+ from abc import ABC, abstractmethod
2
+ from typing import Optional
3
+
4
+ class transform_data(ABC):
5
+ @abstractmethod
6
+ def transform_data(self, url: str) -> Optional[str]:
7
+ """Transforma datos y retorna la ruta del archivo procesado, o None si falla"""
8
+ pass
9
+
10
+ class load_data(ABC):
11
+ @abstractmethod
12
+ def load_data(self, url: str) -> bool:
13
+ """Carga datos y retorna True si fue exitoso, False si falló"""
14
+ pass
@@ -0,0 +1,22 @@
1
+ Metadata-Version: 2.4
2
+ Name: embedding-flow
3
+ Version: 0.1.0
4
+ Summary: Pipeline to transform text chunks into embeddings and load to Qdrant
5
+ Author: facuvega
6
+ Classifier: Programming Language :: Python :: 3
7
+ Classifier: Programming Language :: Python :: 3.10
8
+ Classifier: Programming Language :: Python :: 3.11
9
+ Classifier: Programming Language :: Python :: 3.12
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.10
13
+ License-File: LICENSE
14
+ Requires-Dist: pandas>=2.0.0
15
+ Requires-Dist: pyarrow>=12.0.0
16
+ Requires-Dist: sentence-transformers>=2.2.0
17
+ Requires-Dist: torch>=2.0.0
18
+ Requires-Dist: qdrant-client>=1.7.0
19
+ Provides-Extra: dev
20
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
21
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
22
+ Dynamic: license-file
@@ -0,0 +1,19 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ requirements.txt
6
+ setup.py
7
+ contracts/__init__.py
8
+ contracts/contracts.py
9
+ embedding_flow.egg-info/PKG-INFO
10
+ embedding_flow.egg-info/SOURCES.txt
11
+ embedding_flow.egg-info/dependency_links.txt
12
+ embedding_flow.egg-info/requires.txt
13
+ embedding_flow.egg-info/top_level.txt
14
+ load/__init__.py
15
+ load/load.py
16
+ tests/test_load.py
17
+ tests/test_transform.py
18
+ transform/__init__.py
19
+ transform/transform.py
@@ -0,0 +1,9 @@
1
+ pandas>=2.0.0
2
+ pyarrow>=12.0.0
3
+ sentence-transformers>=2.2.0
4
+ torch>=2.0.0
5
+ qdrant-client>=1.7.0
6
+
7
+ [dev]
8
+ pytest>=7.0.0
9
+ pytest-cov>=4.0.0
@@ -0,0 +1,3 @@
1
+ contracts
2
+ load
3
+ transform
File without changes
@@ -0,0 +1,101 @@
1
+ from contracts.contracts import load_data
2
+ from qdrant_client import QdrantClient
3
+ from qdrant_client.models import Distance, VectorParams, PointStruct
4
+ import pandas as pd
5
+ import logging
6
+ import os
7
+ from typing import List
8
+ import uuid
9
+
10
+ # Configurar logging
11
+ logging.basicConfig(
12
+ level=logging.INFO,
13
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
14
+ )
15
+ logger = logging.getLogger(__name__)
16
+
17
+ class load_embedding(load_data):
18
+ def __init__(self):
19
+ """Inicializa el cliente de Qdrant"""
20
+ self.qdrant_url = os.getenv("QDRANT_URL", "http://localhost:6333")
21
+ self.qdrant_api_key = os.getenv("QDRANT_API_KEY", None)
22
+ self.collection_name = os.getenv("QDRANT_COLLECTION", "embeddings_collection")
23
+ self.vector_size = int(os.getenv("VECTOR_SIZE", "768"))
24
+
25
+ # Inicializar cliente
26
+ self.client = QdrantClient(
27
+ url=self.qdrant_url,
28
+ api_key=self.qdrant_api_key
29
+ )
30
+
31
+ # Crear colección si no existe
32
+ self._ensure_collection_exists()
33
+
34
+ def _ensure_collection_exists(self):
35
+ """Crea la colección en Qdrant si no existe"""
36
+ try:
37
+ collections = self.client.get_collections().collections
38
+ collection_exists = any(col.name == self.collection_name for col in collections)
39
+
40
+ if not collection_exists:
41
+ self.client.create_collection(
42
+ collection_name=self.collection_name,
43
+ vectors_config=VectorParams(
44
+ size=self.vector_size,
45
+ distance=Distance.COSINE
46
+ )
47
+ )
48
+ logger.info(f"✅ Colección '{self.collection_name}' creada en Qdrant")
49
+ else:
50
+ logger.info(f"ℹ️ Colección '{self.collection_name}' ya existe")
51
+ except Exception as e:
52
+ logger.error(f"❌ Error al verificar/crear colección: {e}", exc_info=True)
53
+ raise
54
+
55
+ def load_data(self, parquet_path: str) -> bool:
56
+ """
57
+ Carga los embeddings desde un parquet a Qdrant
58
+
59
+ Args:
60
+ parquet_path: Ruta al archivo parquet con embeddings
61
+
62
+ Returns:
63
+ True si la carga fue exitosa, False si falló
64
+ """
65
+ try:
66
+ # Leer parquet
67
+ df = pd.read_parquet(parquet_path)
68
+
69
+ if "embedding" not in df.columns:
70
+ raise ValueError(f"El parquet {parquet_path} no contiene columna 'embedding'")
71
+
72
+ # Preparar puntos para Qdrant
73
+ points: List[PointStruct] = []
74
+
75
+ for idx, row in df.iterrows():
76
+ # Generar ID único
77
+ point_id = str(uuid.uuid4())
78
+
79
+ # Preparar payload (todos los campos excepto embedding)
80
+ payload = {col: row[col] for col in df.columns if col != "embedding"}
81
+
82
+ # Crear punto
83
+ point = PointStruct(
84
+ id=point_id,
85
+ vector=row["embedding"],
86
+ payload=payload
87
+ )
88
+ points.append(point)
89
+
90
+ # Insertar en Qdrant (en batch)
91
+ self.client.upsert(
92
+ collection_name=self.collection_name,
93
+ points=points
94
+ )
95
+
96
+ logger.info(f"✅ {len(points)} embeddings cargados a Qdrant desde {parquet_path}")
97
+ return True
98
+
99
+ except Exception as e:
100
+ logger.error(f"❌ Error al cargar embeddings a Qdrant desde {parquet_path}: {e}", exc_info=True)
101
+ return False
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "embedding-flow"
7
+ version = "0.1.0"
8
+ description = "Pipeline to transform text chunks into embeddings and load to Qdrant"
9
+ authors = [{name = "facuvega"}]
10
+ requires-python = ">=3.10"
11
+ dependencies = [
12
+ "pandas>=2.0.0",
13
+ "pyarrow>=12.0.0",
14
+ "sentence-transformers>=2.2.0",
15
+ "torch>=2.0.0",
16
+ "qdrant-client>=1.7.0",
17
+ ]
18
+ classifiers = [
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.10",
21
+ "Programming Language :: Python :: 3.11",
22
+ "Programming Language :: Python :: 3.12",
23
+ "License :: OSI Approved :: MIT License",
24
+ "Operating System :: OS Independent",
25
+ ]
26
+
27
+ [project.optional-dependencies]
28
+ dev = [
29
+ "pytest>=7.0.0",
30
+ "pytest-cov>=4.0.0",
31
+ ]
32
+
33
+ [tool.setuptools.packages.find]
34
+ include = ["contracts*", "transform*", "load*"]
35
+ exclude = ["tests*", "venv*"]
36
+
@@ -0,0 +1,17 @@
1
+ # Core dependencies
2
+ pandas>=2.0.0
3
+ pyarrow>=12.0.0
4
+
5
+ # ML & Embeddings
6
+ sentence-transformers>=2.2.0
7
+ torch>=2.0.0
8
+
9
+ # Vector Database
10
+ qdrant-client>=1.7.0
11
+
12
+ # Airflow (si se necesita localmente, sino está en el servidor)
13
+ # apache-airflow>=2.7.0
14
+
15
+ # Utilities
16
+ python-dotenv>=1.0.0
17
+
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,6 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ packages=find_packages(exclude=["tests", "venv"]),
5
+ )
6
+
@@ -0,0 +1,63 @@
1
+ import pytest
2
+ import pandas as pd
3
+ import tempfile
4
+ import numpy as np
5
+ from pathlib import Path
6
+ from unittest.mock import MagicMock, patch
7
+ from load.load import load_embedding
8
+
9
+
10
+ @patch('load.load.QdrantClient')
11
+ def test_load_with_embeddings(mock_qdrant_client):
12
+ """Test que load carga correctamente embeddings de 768 dims"""
13
+ # Mock del cliente
14
+ mock_client = MagicMock()
15
+ mock_qdrant_client.return_value = mock_client
16
+ mock_client.get_collections.return_value.collections = []
17
+
18
+ # Crear parquet con embeddings de 768 dims
19
+ with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as tmp:
20
+ df = pd.DataFrame({
21
+ 'text': ['test 1', 'test 2'],
22
+ 'embedding': [np.random.rand(768).tolist(), np.random.rand(768).tolist()]
23
+ })
24
+ df.to_parquet(tmp.name, index=False)
25
+ tmp_path = tmp.name
26
+
27
+ try:
28
+ loader = load_embedding()
29
+ success = loader.load_data(tmp_path)
30
+
31
+ assert success is True
32
+ mock_client.upsert.assert_called_once()
33
+
34
+ # Verificar que se llamó con 2 puntos
35
+ call_args = mock_client.upsert.call_args
36
+ points = call_args.kwargs['points']
37
+ assert len(points) == 2
38
+
39
+ finally:
40
+ Path(tmp_path).unlink(missing_ok=True)
41
+
42
+
43
+ @patch('load.load.QdrantClient')
44
+ def test_load_without_embeddings(mock_qdrant_client):
45
+ """Test que load falla sin columna 'embedding'"""
46
+ mock_client = MagicMock()
47
+ mock_qdrant_client.return_value = mock_client
48
+ mock_client.get_collections.return_value.collections = []
49
+
50
+ with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as tmp:
51
+ df = pd.DataFrame({
52
+ 'text': ['test 1', 'test 2']
53
+ })
54
+ df.to_parquet(tmp.name, index=False)
55
+ tmp_path = tmp.name
56
+
57
+ try:
58
+ loader = load_embedding()
59
+ success = loader.load_data(tmp_path)
60
+ assert success is False
61
+ finally:
62
+ Path(tmp_path).unlink(missing_ok=True)
63
+
@@ -0,0 +1,54 @@
1
+ import pytest
2
+ import pandas as pd
3
+ import tempfile
4
+ from pathlib import Path
5
+ from transform.transform import transform_embedding
6
+
7
+
8
+ def test_transform_creates_embeddings():
9
+ """Test que transform genera embeddings de 768 dimensiones"""
10
+ # Crear parquet temporal con texto
11
+ with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as tmp:
12
+ df = pd.DataFrame({
13
+ 'text': ['test text 1', 'test text 2', 'test text 3']
14
+ })
15
+ df.to_parquet(tmp.name, index=False)
16
+ tmp_path = tmp.name
17
+
18
+ try:
19
+ # Transformar
20
+ transformer = transform_embedding()
21
+ output_path = transformer.transform_data(tmp_path)
22
+
23
+ # Verificar
24
+ assert output_path is not None
25
+ assert Path(output_path).exists()
26
+
27
+ # Verificar dimensiones
28
+ result_df = pd.read_parquet(output_path)
29
+ assert 'embedding' in result_df.columns
30
+ assert len(result_df['embedding'][0]) == 768
31
+
32
+ finally:
33
+ # Cleanup
34
+ Path(tmp_path).unlink(missing_ok=True)
35
+ if output_path:
36
+ Path(output_path).unlink(missing_ok=True)
37
+
38
+
39
+ def test_transform_missing_text_column():
40
+ """Test que transform falla sin columna 'text'"""
41
+ with tempfile.NamedTemporaryFile(suffix='.parquet', delete=False) as tmp:
42
+ df = pd.DataFrame({
43
+ 'wrong_column': ['data 1', 'data 2']
44
+ })
45
+ df.to_parquet(tmp.name, index=False)
46
+ tmp_path = tmp.name
47
+
48
+ try:
49
+ transformer = transform_embedding()
50
+ output_path = transformer.transform_data(tmp_path)
51
+ assert output_path is None
52
+ finally:
53
+ Path(tmp_path).unlink(missing_ok=True)
54
+
File without changes
@@ -0,0 +1,42 @@
1
+ from contracts.contracts import transform_data
2
+ from pathlib import Path
3
+ import pandas as pd
4
+ from sentence_transformers import SentenceTransformer
5
+ import logging
6
+ from typing import Optional
7
+
8
+ # Configurar logging
9
+ logging.basicConfig(
10
+ level=logging.INFO,
11
+ format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
12
+ )
13
+ logger = logging.getLogger(__name__)
14
+
15
+ class transform_embedding(transform_data):
16
+ def transform_data(self, parquet_path: str) -> Optional[str]:
17
+ try:
18
+ # Cargar datos del parquet
19
+ df = pd.read_parquet(parquet_path)
20
+ if "text" not in df.columns:
21
+ raise ValueError("El parquet no contiene una columna 'text' para generar embeddings.")
22
+
23
+ # Inicializar modelo con embeddings de 768 dimensiones
24
+ model = SentenceTransformer("all-mpnet-base-v2")
25
+
26
+ # Generar embeddings
27
+ embeddings = model.encode(df["text"].tolist(), show_progress_bar=True)
28
+ df["embedding"] = embeddings.tolist() # guardar como lista
29
+
30
+ # Guardar parquet procesado
31
+ output_dir = Path("datos_embeddings")
32
+ output_dir.mkdir(parents=True, exist_ok=True)
33
+
34
+ output_file = output_dir / Path(parquet_path).name
35
+ df.to_parquet(output_file, index=False)
36
+
37
+ logger.info(f"✅ Embeddings (768 dim) generados y guardados en: {output_file}")
38
+ return str(output_file)
39
+
40
+ except Exception as e:
41
+ logger.error(f"❌ Error al transformar en embeddings {parquet_path}: {e}", exc_info=True)
42
+ return None