| |
| """ |
| patch_nb.py — genera los notebooks del curso para una PLATAFORMA concreta. |
| |
| Las plataformas del laboratorio NO traen la misma versión del stack: |
| - container / vagrant : PySpark 4.0 (Scala 2.13) -> Sedona _2.13:1.8.0, ANSI off |
| - portable (Windows) : PySpark 3.4 (Scala 2.12) -> Sedona _2.12:1.7.2 |
| |
| Por eso un mismo notebook NO sirve en ambas: este patcher produce la variante |
| correcta por perfil. Comunes a ambas: arreglos de pip, api.py, NameError y el |
| reemplazo del conector Spark-ES (inexistente en 4.0) por el cliente Python (bulk), |
| que funciona en las dos. |
| |
| Uso: python patch_nb.py <entrada> <salida> [container|portable] (def: container) |
| """ |
| import json, re, sys |
|
|
| |
| COMMON = [ |
| |
| |
| |
| ('pip_executable = "/opt/bdpv5/python/bin/pip"', 'pip_executable = "pip"'), |
| ("/opt/bdpv5/python/bin/pip", "pip"), |
| ("!{pip_executable} install pyspark==3.4.2", "# (no se reinstala pyspark: se usa el del laboratorio)"), |
| (r'PYTHON_EXECUTABLE_PATH = r"C:\BDP\python\python.exe" # Ejemplo de ruta en Windows', |
| 'import sys as _sys\nPYTHON_EXECUTABLE_PATH = _sys.executable # autodetección (corregido)'), |
| ("latitud_a_probar", "latitud_usuario"), |
| ("longitud_a_probar", "longitud_usuario"), |
| ] |
|
|
| |
| CONTAINER = [ |
| ("org.apache.sedona:sedona-spark-3.4_2.12:1.7.2", "org.apache.sedona:sedona-spark-4.0_2.13:1.8.0"), |
| ("org.datasyslab:geotools-wrapper:1.7.2-28.5", "org.datasyslab:geotools-wrapper:1.8.0-33.1"), |
| ("spark-sql-kafka-0-10_2.12:3.1.2", "spark-sql-kafka-0-10_2.13:4.0.0"), |
| ("spark-sql-kafka-0-10_2.12:3.4.1", "spark-sql-kafka-0-10_2.13:4.0.0"), |
| |
| |
| (".getOrCreate()", '.config("spark.sql.ansi.enabled", "false").getOrCreate()'), |
| ] |
|
|
| |
| PORTABLE = [ |
| ("org.apache.sedona:sedona-spark-4.0_2.13:1.8.0", "org.apache.sedona:sedona-spark-3.4_2.12:1.7.2"), |
| ("org.datasyslab:geotools-wrapper:1.8.0-33.1", "org.datasyslab:geotools-wrapper:1.7.2-28.5"), |
| ("spark-sql-kafka-0-10_2.13:4.0.0", "spark-sql-kafka-0-10_2.12:3.4.1"), |
| ("spark-sql-kafka-0-10_2.12:3.1.2", "spark-sql-kafka-0-10_2.12:3.4.1"), |
| |
| ] |
|
|
| PROFILES = {"container": (CONTAINER, "1.8.0"), "portable": (PORTABLE, "1.7.2")} |
|
|
| |
| |
| ES_PY_WRITE = '''# Indexación a Elasticsearch con el CLIENTE PYTHON (bulk). |
| # Funciona igual en Portable (Spark 3.4) y Container (Spark 4.0): el conector |
| # Spark-ES no existe para Spark 4.0, así que usamos el cliente Python, que es |
| # robusto y aprovecha que la seguridad de ES está desactivada en el laboratorio. |
| from elasticsearch import Elasticsearch, helpers |
| |
| index_name = "geocoder_mexico" |
| es = Elasticsearch("http://localhost:9200", request_timeout=120) |
| |
| # Mapeo: location como geo_point; texto y keywords para búsqueda. |
| mapping = {"mappings": {"properties": { |
| "DIRECCION_COMPLETA": {"type": "text"}, |
| "CP": {"type": "keyword"}, "NOM_MUN": {"type": "keyword"}, |
| "NOM_ENT": {"type": "keyword"}, "location": {"type": "geo_point"}}}} |
| if es.indices.exists(index=index_name): |
| es.indices.delete(index=index_name) |
| es.indices.create(index=index_name, body=mapping) |
| |
| def _gen(rows): |
| for r in rows: |
| yield {"_index": index_name, "_source": r.asDict()} |
| |
| # toLocalIterator evita traer todo a memoria del driver de una vez. |
| total = df_para_es.count() |
| print(f"Indexando {total:,} documentos en '{index_name}' (cliente Python, bulk)...") |
| ok, _ = helpers.bulk(es, _gen(df_para_es.toLocalIterator()), chunk_size=2000, request_timeout=120) |
| es.indices.refresh(index=index_name) |
| print(f"\\u2705 Indexados {ok:,} documentos. Conteo ES: {es.count(index=index_name)['count']:,}") |
| ''' |
|
|
| def patch_text(s, profile): |
| subs, sedona_py = PROFILES[profile] |
| for a, b in COMMON + subs: |
| s = s.replace(a, b) |
| |
| s = re.sub(r"apache-sedona(?!==)", f"apache-sedona=={sedona_py}", s) |
| |
| s = re.sub(r',?\s*\n?\s*"org\.elasticsearch:elasticsearch-spark[^"]*"', '', s) |
| return s |
|
|
| def patch_ipynb(src, out, profile): |
| nb = json.load(open(src, encoding="utf-8")) |
| for c in nb["cells"]: |
| if c["cell_type"] != "code": |
| continue |
| s = "".join(c["source"]) |
| if 'org.elasticsearch.spark.sql' in s and '.write' in s: |
| s = ES_PY_WRITE |
| else: |
| s = patch_text(s, profile) |
| c["source"] = s.splitlines(keepends=True) |
| json.dump(nb, open(out, "w", encoding="utf-8"), ensure_ascii=False, indent=1) |
| print(f"[{profile}] ipynb ->", out) |
|
|
| def patch_py(src, out, profile): |
| open(out, "w", encoding="utf-8").write(patch_text(open(src, encoding="utf-8").read(), profile)) |
| print(f"[{profile}] py ->", out) |
|
|
| if __name__ == "__main__": |
| src, out = sys.argv[1], sys.argv[2] |
| profile = sys.argv[3] if len(sys.argv) > 3 else "container" |
| (patch_ipynb if src.endswith(".ipynb") else patch_py)(src, out, profile) |
|
|