embedding-flow 0.1.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.
- contracts/__init__.py +0 -0
- contracts/contracts.py +14 -0
- embedding_flow-0.1.0.dist-info/METADATA +22 -0
- embedding_flow-0.1.0.dist-info/RECORD +11 -0
- embedding_flow-0.1.0.dist-info/WHEEL +5 -0
- embedding_flow-0.1.0.dist-info/licenses/LICENSE +22 -0
- embedding_flow-0.1.0.dist-info/top_level.txt +3 -0
- load/__init__.py +0 -0
- load/load.py +101 -0
- transform/__init__.py +0 -0
- transform/transform.py +42 -0
contracts/__init__.py
ADDED
File without changes
|
contracts/contracts.py
ADDED
@@ -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,11 @@
|
|
1
|
+
contracts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
2
|
+
contracts/contracts.py,sha256=im3wzTHMxZFVIVyjVVN1u4eZ5J_HxYGrcu3oQ8BXoOk,441
|
3
|
+
embedding_flow-0.1.0.dist-info/licenses/LICENSE,sha256=Vi3cItkblr6fZwGbNlp_HnBaMFwXSWYPkrVQLXX3LCs,1057
|
4
|
+
load/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
5
|
+
load/load.py,sha256=Y0JbC1x7SfG_EzsSDacDK8fuIcv7K1guQ8AD0birheE,3706
|
6
|
+
transform/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
7
|
+
transform/transform.py,sha256=GPeea6D2EbdNwmxdCDtDGgTGIPVLs_Z4VePYQJfzROc,1585
|
8
|
+
embedding_flow-0.1.0.dist-info/METADATA,sha256=uFM06vDN-pagU7V_GoZ1wNU6ZPsX8MzdlxNMjV2JoaA,802
|
9
|
+
embedding_flow-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
10
|
+
embedding_flow-0.1.0.dist-info/top_level.txt,sha256=VfSCJdxLtTjvyUSe1z1kQgIf0j2zFt3--FivJqWMxxA,25
|
11
|
+
embedding_flow-0.1.0.dist-info/RECORD,,
|
@@ -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
|
+
|
load/__init__.py
ADDED
File without changes
|
load/load.py
ADDED
@@ -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
|
transform/__init__.py
ADDED
File without changes
|
transform/transform.py
ADDED
@@ -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
|