backup source: patch_nb.py
Browse files- cuadernos/_build/patch_nb.py +117 -0
cuadernos/_build/patch_nb.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
patch_nb.py — genera los notebooks del curso para una PLATAFORMA concreta.
|
| 4 |
+
|
| 5 |
+
Las plataformas del laboratorio NO traen la misma versión del stack:
|
| 6 |
+
- container / vagrant : PySpark 4.0 (Scala 2.13) -> Sedona _2.13:1.8.0, ANSI off
|
| 7 |
+
- portable (Windows) : PySpark 3.4 (Scala 2.12) -> Sedona _2.12:1.7.2
|
| 8 |
+
|
| 9 |
+
Por eso un mismo notebook NO sirve en ambas: este patcher produce la variante
|
| 10 |
+
correcta por perfil. Comunes a ambas: arreglos de pip, api.py, NameError y el
|
| 11 |
+
reemplazo del conector Spark-ES (inexistente en 4.0) por el cliente Python (bulk),
|
| 12 |
+
que funciona en las dos.
|
| 13 |
+
|
| 14 |
+
Uso: python patch_nb.py <entrada> <salida> [container|portable] (def: container)
|
| 15 |
+
"""
|
| 16 |
+
import json, re, sys
|
| 17 |
+
|
| 18 |
+
# --- comunes a TODAS las plataformas ---
|
| 19 |
+
COMMON = [
|
| 20 |
+
# Usar `pip` (alineado al kernel de Jupyter), NO `python3 -m pip`: en el box de
|
| 21 |
+
# Vagrant `python3` apunta a OTRO Python (instala en el entorno equivocado / falla).
|
| 22 |
+
# Verificado en Vagrant: `pip install numpy pandas` funciona. (Dr. Coronado, jun-2026)
|
| 23 |
+
('pip_executable = "/opt/bdpv5/python/bin/pip"', 'pip_executable = "pip"'),
|
| 24 |
+
("/opt/bdpv5/python/bin/pip", "pip"),
|
| 25 |
+
("!{pip_executable} install pyspark==3.4.2", "# (no se reinstala pyspark: se usa el del laboratorio)"),
|
| 26 |
+
(r'PYTHON_EXECUTABLE_PATH = r"C:\BDP\python\python.exe" # Ejemplo de ruta en Windows',
|
| 27 |
+
'import sys as _sys\nPYTHON_EXECUTABLE_PATH = _sys.executable # autodetección (corregido)'),
|
| 28 |
+
("latitud_a_probar", "latitud_usuario"),
|
| 29 |
+
("longitud_a_probar", "longitud_usuario"),
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
# --- perfil CONTAINER / VAGRANT = Spark 4.0 / Scala 2.13 ---
|
| 33 |
+
CONTAINER = [
|
| 34 |
+
("org.apache.sedona:sedona-spark-3.4_2.12:1.7.2", "org.apache.sedona:sedona-spark-4.0_2.13:1.8.0"),
|
| 35 |
+
("org.datasyslab:geotools-wrapper:1.7.2-28.5", "org.datasyslab:geotools-wrapper:1.8.0-33.1"),
|
| 36 |
+
("spark-sql-kafka-0-10_2.12:3.1.2", "spark-sql-kafka-0-10_2.13:4.0.0"),
|
| 37 |
+
("spark-sql-kafka-0-10_2.12:3.4.1", "spark-sql-kafka-0-10_2.13:4.0.0"),
|
| 38 |
+
# Spark 4.0 activa ANSI por defecto -> cast('*' as int) truena (INEGI usa '*').
|
| 39 |
+
# Restauramos el comportamiento leniente de 3.x.
|
| 40 |
+
(".getOrCreate()", '.config("spark.sql.ansi.enabled", "false").getOrCreate()'),
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
# --- perfil PORTABLE (Windows nativo) = Spark 3.4 / Scala 2.12 ---
|
| 44 |
+
PORTABLE = [
|
| 45 |
+
("org.apache.sedona:sedona-spark-4.0_2.13:1.8.0", "org.apache.sedona:sedona-spark-3.4_2.12:1.7.2"),
|
| 46 |
+
("org.datasyslab:geotools-wrapper:1.8.0-33.1", "org.datasyslab:geotools-wrapper:1.7.2-28.5"),
|
| 47 |
+
("spark-sql-kafka-0-10_2.13:4.0.0", "spark-sql-kafka-0-10_2.12:3.4.1"),
|
| 48 |
+
("spark-sql-kafka-0-10_2.12:3.1.2", "spark-sql-kafka-0-10_2.12:3.4.1"),
|
| 49 |
+
# Spark 3.4 ya es leniente con los cast por defecto: NO se necesita el config ANSI.
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
PROFILES = {"container": (CONTAINER, "1.8.0"), "portable": (PORTABLE, "1.7.2")}
|
| 53 |
+
|
| 54 |
+
# Reemplazo del bloque de escritura ES-Spark por el CLIENTE PYTHON (bulk),
|
| 55 |
+
# compatible con ambas plataformas (el conector Spark-ES no existe para Spark 4.0).
|
| 56 |
+
ES_PY_WRITE = '''# Indexación a Elasticsearch con el CLIENTE PYTHON (bulk).
|
| 57 |
+
# Funciona igual en Portable (Spark 3.4) y Container (Spark 4.0): el conector
|
| 58 |
+
# Spark-ES no existe para Spark 4.0, así que usamos el cliente Python, que es
|
| 59 |
+
# robusto y aprovecha que la seguridad de ES está desactivada en el laboratorio.
|
| 60 |
+
from elasticsearch import Elasticsearch, helpers
|
| 61 |
+
|
| 62 |
+
index_name = "geocoder_mexico"
|
| 63 |
+
es = Elasticsearch("http://localhost:9200", request_timeout=120)
|
| 64 |
+
|
| 65 |
+
# Mapeo: location como geo_point; texto y keywords para búsqueda.
|
| 66 |
+
mapping = {"mappings": {"properties": {
|
| 67 |
+
"DIRECCION_COMPLETA": {"type": "text"},
|
| 68 |
+
"CP": {"type": "keyword"}, "NOM_MUN": {"type": "keyword"},
|
| 69 |
+
"NOM_ENT": {"type": "keyword"}, "location": {"type": "geo_point"}}}}
|
| 70 |
+
if es.indices.exists(index=index_name):
|
| 71 |
+
es.indices.delete(index=index_name)
|
| 72 |
+
es.indices.create(index=index_name, body=mapping)
|
| 73 |
+
|
| 74 |
+
def _gen(rows):
|
| 75 |
+
for r in rows:
|
| 76 |
+
yield {"_index": index_name, "_source": r.asDict()}
|
| 77 |
+
|
| 78 |
+
# toLocalIterator evita traer todo a memoria del driver de una vez.
|
| 79 |
+
total = df_para_es.count()
|
| 80 |
+
print(f"Indexando {total:,} documentos en '{index_name}' (cliente Python, bulk)...")
|
| 81 |
+
ok, _ = helpers.bulk(es, _gen(df_para_es.toLocalIterator()), chunk_size=2000, request_timeout=120)
|
| 82 |
+
es.indices.refresh(index=index_name)
|
| 83 |
+
print(f"\\u2705 Indexados {ok:,} documentos. Conteo ES: {es.count(index=index_name)['count']:,}")
|
| 84 |
+
'''
|
| 85 |
+
|
| 86 |
+
def patch_text(s, profile):
|
| 87 |
+
subs, sedona_py = PROFILES[profile]
|
| 88 |
+
for a, b in COMMON + subs:
|
| 89 |
+
s = s.replace(a, b)
|
| 90 |
+
# fijar la versión del paquete python apache-sedona acorde al perfil
|
| 91 |
+
s = re.sub(r"apache-sedona(?!==)", f"apache-sedona=={sedona_py}", s)
|
| 92 |
+
# quitar el conector ES-Spark (no existe para Spark 4.0) de listas de paquetes
|
| 93 |
+
s = re.sub(r',?\s*\n?\s*"org\.elasticsearch:elasticsearch-spark[^"]*"', '', s)
|
| 94 |
+
return s
|
| 95 |
+
|
| 96 |
+
def patch_ipynb(src, out, profile):
|
| 97 |
+
nb = json.load(open(src, encoding="utf-8"))
|
| 98 |
+
for c in nb["cells"]:
|
| 99 |
+
if c["cell_type"] != "code":
|
| 100 |
+
continue
|
| 101 |
+
s = "".join(c["source"])
|
| 102 |
+
if 'org.elasticsearch.spark.sql' in s and '.write' in s:
|
| 103 |
+
s = ES_PY_WRITE
|
| 104 |
+
else:
|
| 105 |
+
s = patch_text(s, profile)
|
| 106 |
+
c["source"] = s.splitlines(keepends=True)
|
| 107 |
+
json.dump(nb, open(out, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
|
| 108 |
+
print(f"[{profile}] ipynb ->", out)
|
| 109 |
+
|
| 110 |
+
def patch_py(src, out, profile):
|
| 111 |
+
open(out, "w", encoding="utf-8").write(patch_text(open(src, encoding="utf-8").read(), profile))
|
| 112 |
+
print(f"[{profile}] py ->", out)
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
src, out = sys.argv[1], sys.argv[2]
|
| 116 |
+
profile = sys.argv[3] if len(sys.argv) > 3 else "container"
|
| 117 |
+
(patch_ipynb if src.endswith(".ipynb") else patch_py)(src, out, profile)
|