hyper-reality-visualizer / backend /scripts /migrate_textures_case.py
eduardo4547's picture
Upload 182 files
d2df13f verified
"""
Script de migraci贸n: reemplaza referencias con `Texture_wpc_deck` por `Texture_WPC_DECK`
Uso:
- Configura `MONGODB_URI` como variable de entorno o edita la constante abajo.
- Ejecuta: `python backend/scripts/migrate_textures_case.py`
Qu茅 hace:
- Actualiza campos `textura` y `url_preview` dentro de documentos en la colecci贸n `catalog`.
- Busca y reemplaza tanto la ruta dentro de strings como partes de arrays/objetos anidados.
- Muestra un resumen de documentos inspeccionados y modificados.
"""
import os
import re
import sys
import certifi
from pymongo import MongoClient
MONGODB_URI = os.getenv("MONGODB_URI", "mongodb://127.0.0.1:27017")
DB_NAME = os.getenv("MONGODB_DB", "hyper_reality")
COL_NAME = os.getenv("MONGODB_COLLECTION", "catalog")
# Allow passing the MongoDB URI as a first command-line argument for
# environments where setting environment variables is inconvenient.
if len(sys.argv) > 1 and sys.argv[1].strip():
MONGODB_URI = sys.argv[1].strip()
OLD = "Texture_wpc_deck"
NEW = "Texture_WPC_DECK"
regex_old = re.compile(re.escape(OLD), flags=re.IGNORECASE)
# Use certifi bundle to verify Atlas TLS certificates on systems without
# a proper CA store configured (common in some Windows Python installs).
client = MongoClient(MONGODB_URI, tls=True, tlsCAFile=certifi.where())
db = client[DB_NAME]
col = db[COL_NAME]
def replace_in_value(val):
if isinstance(val, str):
if regex_old.search(val):
return regex_old.sub(NEW, val)
return val
if isinstance(val, list):
changed = False
out = []
for v in val:
nv = replace_in_value(v)
if nv != v:
changed = True
out.append(nv)
return out if changed else val
if isinstance(val, dict):
changed = False
out = {}
for k, v in val.items():
nv = replace_in_value(v)
if nv != v:
changed = True
out[k] = nv
return out if changed else val
return val
def migrate_batch(batch_size=200):
total = col.count_documents({})
print(f"Documentos totales en {DB_NAME}.{COL_NAME}: {total}")
cursor = col.find({})
modified = 0
inspected = 0
for doc in cursor:
inspected += 1
doc_id = doc.get("_id")
new_doc = False
updates = {}
# Revisa productos list si existe
productos = doc.get("productos")
if productos:
new_productos = []
changed_any = False
for p in productos:
new_p = dict(p)
for field in ["textura", "url_preview"]:
if field in new_p and isinstance(new_p[field], str) and regex_old.search(new_p[field]):
new_p[field] = regex_old.sub(NEW, new_p[field])
changed_any = True
new_productos.append(new_p)
if changed_any:
updates["productos"] = new_productos
new_doc = True
# Revisa cualquier otro campo a nivel superior (por si hay url_preview fuera de productos)
for key, value in doc.items():
if key in ["productos", "_id"]:
continue
new_val = replace_in_value(value)
if new_val != value:
updates[key] = new_val
new_doc = True
if new_doc and updates:
res = col.update_one({"_id": doc_id}, {"$set": updates})
if res.modified_count:
modified += 1
print(f"Modificado doc _id={doc_id}: campos actualizados: {list(updates.keys())}")
print(f"Inspeccionados: {inspected}, Modificados: {modified}")
if __name__ == "__main__":
print("Conectando a:", MONGODB_URI)
migrate_batch()
client.close()