quito comentarios
This commit is contained in:
parent
68a5528f2f
commit
937da3f90b
8 changed files with 48 additions and 496 deletions
|
|
@ -13,7 +13,6 @@ import torch
|
|||
logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s: %(message)s')
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
# ---------- Configuración DB ----------
|
||||
DB = dict(
|
||||
host=os.environ.get("DB_HOST", "localhost"),
|
||||
port=int(os.environ.get("DB_PORT", 5432)),
|
||||
|
|
@ -22,31 +21,22 @@ DB = dict(
|
|||
password=os.environ.get("DB_PASS", "x"),
|
||||
)
|
||||
|
||||
# ---------- Parámetros de worker ----------
|
||||
# Modelo por defecto: multilingüe, bueno para muchas lenguas
|
||||
EMB_MODEL = os.environ.get(
|
||||
"EMB_MODEL",
|
||||
"sentence-transformers/paraphrase-multilingual-mpnet-base-v2",
|
||||
)
|
||||
EMB_BATCH = int(os.environ.get("EMB_BATCH", "128"))
|
||||
SLEEP_IDLE = float(os.environ.get("EMB_SLEEP_IDLE", "5.0"))
|
||||
# Filtrado por idiomas destino (coma-separado). Por defecto sólo 'es'
|
||||
EMB_LANGS = [s.strip() for s in os.environ.get("EMB_LANGS", "es").split(",") if s.strip()]
|
||||
|
||||
# DEVICE_ENV: 'auto' | 'cpu' | 'cuda'
|
||||
DEVICE_ENV = os.environ.get("DEVICE", "auto").lower()
|
||||
|
||||
# Límite por iteración (para no tragar toda la tabla de golpe)
|
||||
EMB_LIMIT = int(os.environ.get("EMB_LIMIT", "1000"))
|
||||
|
||||
|
||||
# ---------- Utilidades ----------
|
||||
def get_conn():
|
||||
return psycopg2.connect(**DB)
|
||||
|
||||
|
||||
def ensure_schema(conn):
|
||||
"""Crea la tabla de embeddings para traducciones si no existe."""
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
|
|
@ -61,21 +51,12 @@ def ensure_schema(conn):
|
|||
);
|
||||
"""
|
||||
)
|
||||
# Alineado con init-db/08-embeddings.sql
|
||||
cur.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_tr_emb_model ON traduccion_embeddings(model);"
|
||||
)
|
||||
cur.execute(
|
||||
"CREATE INDEX IF NOT EXISTS idx_tr_emb_traduccion_id ON traduccion_embeddings(traduccion_id);"
|
||||
)
|
||||
cur.execute("CREATE INDEX IF NOT EXISTS idx_tr_emb_model ON traduccion_embeddings(model);")
|
||||
cur.execute("CREATE INDEX IF NOT EXISTS idx_tr_emb_traduccion_id ON traduccion_embeddings(traduccion_id);")
|
||||
conn.commit()
|
||||
|
||||
|
||||
def fetch_batch_pending(conn) -> List[psycopg2.extras.DictRow]:
|
||||
"""
|
||||
Devuelve un lote de traducciones 'done' del/los idioma(s) objetivo
|
||||
que no tienen embedding aún para el EMB_MODEL indicado.
|
||||
"""
|
||||
with conn.cursor(cursor_factory=psycopg2.extras.DictCursor) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
|
|
@ -96,15 +77,10 @@ def fetch_batch_pending(conn) -> List[psycopg2.extras.DictRow]:
|
|||
""",
|
||||
(EMB_MODEL, EMB_LANGS, EMB_LIMIT),
|
||||
)
|
||||
rows = cur.fetchall()
|
||||
return rows
|
||||
return cur.fetchall()
|
||||
|
||||
|
||||
def texts_from_rows(rows: List[psycopg2.extras.DictRow]) -> List[str]:
|
||||
"""
|
||||
Compone el texto a vectorizar por cada traducción:
|
||||
'titulo_trad' + '\n' + 'resumen_trad'. Si alguno falta, usa lo disponible.
|
||||
"""
|
||||
texts: List[str] = []
|
||||
for r in rows:
|
||||
title = (r["titulo_trad"] or "").strip()
|
||||
|
|
@ -117,15 +93,11 @@ def texts_from_rows(rows: List[psycopg2.extras.DictRow]) -> List[str]:
|
|||
|
||||
|
||||
def upsert_embeddings(conn, rows, embs: np.ndarray, model_name: str):
|
||||
"""
|
||||
Inserta/actualiza embeddings por traducción en lote (batch insert).
|
||||
"""
|
||||
if embs.size == 0 or not rows:
|
||||
return
|
||||
|
||||
dim = int(embs.shape[1])
|
||||
|
||||
# Preparamos los datos para execute_values
|
||||
data = [
|
||||
(
|
||||
int(r["traduccion_id"]),
|
||||
|
|
@ -152,7 +124,6 @@ def upsert_embeddings(conn, rows, embs: np.ndarray, model_name: str):
|
|||
conn.commit()
|
||||
|
||||
|
||||
# ---------- Main loop ----------
|
||||
def main():
|
||||
log.info("Arrancando embeddings_worker para TRADUCCIONES")
|
||||
log.info(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue