forked from diegoju/Ordina-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
2585 lines (2268 loc) · 91.6 KB
/
Copy pathapi.py
File metadata and controls
2585 lines (2268 loc) · 91.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import Body, FastAPI, Query, Request
import base64
import hashlib
import html
import httpx
import io
import json
import logging
import re
import threading
import unicodedata
import zipfile
from fastapi.responses import HTMLResponse, JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import os
import time
from urllib import parse
from typing import Any, Optional
from xml.etree import ElementTree
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s: %(message)s",
)
logger = logging.getLogger("ordina")
app = FastAPI()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
_raw_origins = os.getenv("ALLOWED_ORIGINS", "")
_allowed_origins: list[str] = [o.strip() for o in _raw_origins.split(",") if o.strip()] or ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=_allowed_origins,
allow_methods=["*"],
allow_headers=["*"],
)
@app.middleware("http")
async def rate_limit_middleware(request: Request, call_next):
client_ip = (request.client.host if request.client else None) or "unknown"
now = time.time()
cutoff = now - _RATE_LIMIT_WINDOW
with _rate_lock:
timestamps = _rate_buckets.setdefault(client_ip, [])
# Evict expired timestamps
while timestamps and timestamps[0] < cutoff:
timestamps.pop(0)
if len(timestamps) >= _RATE_LIMIT_MAX:
return JSONResponse(
status_code=429,
content={"error": "rate limit exceeded", "retryAfterSeconds": _RATE_LIMIT_WINDOW},
)
timestamps.append(now)
return await call_next(request)
with open(os.path.join(BASE_DIR, "IdLegislaciones.json"), encoding="utf-8") as f:
leyes = json.load(f)
SJF_BASE = os.getenv("SJF_BASE", "https://sjf2.scjn.gob.mx/services/sjftesismicroservice/api/public")
JURISLEX_BASE = os.getenv("JURISLEX_BASE", "https://jurislex.scjn.gob.mx/Legislaciones.Datos64/Aplicacion/Legislaciones.svc/web")
BJ_SCJN_BASE = os.getenv("BJ_SCJN_BASE", "https://bj.scjn.gob.mx/api/v1/bj")
# Compiled regex patterns — built once at import time
_RE_WHITESPACE = re.compile(r"\s+")
_RE_HTML_TAG = re.compile(r"<[^>]+>")
_RE_EXCESS_NEWLINES = re.compile(r"\n{3,}")
_RE_REGISTRO_DIGITAL = re.compile(r"\bregistro\s+digital\s+(\d{6,8})\b", re.IGNORECASE)
_RE_JURIS_CLAVE = re.compile(r"\b(?:jurisprudencia|tesis(?:\s+aislada)?|criterio\s+aislad[oa])\s+([A-Z0-9][A-Z0-9./\- ]{4,50}\d(?:\s*\([^\)]+\))?)", re.IGNORECASE)
_RE_J_CLAVE_COMPACTA = re.compile(r"\b(?:P\.|[12]a\.)/?J\.\s*\d+/\d{4}(?:\s*\(\d{1,2}a\.\))?(?!\w)", re.IGNORECASE)
_RE_TESIS_AISLADA_CLAVE = re.compile(r"\b(?:criterio\s+aislad[oa]|tesis\s+aislada)\s+((?:P\.|[12]a\.)\s*[A-Z]{1,6}/\d{4}(?:\s*\(\d{1,2}a\.\))?)", re.IGNORECASE)
_RE_ARTICULO_LEY = re.compile(
r"\b((?:art(?:[íi]culo|\.)|articulos?)\s+[0-9]+[A-Za-z\-]*(?:\s*(?:,|y|e)\s*[0-9]+[A-Za-z\-]*)*(?:\s+bis|\s+ter|\s+qu[áa]ter)?(?:\s*,?\s*fracci[oó]n\s+[IVXLCDM]+)?)\s+(?:de(?:l| la| los| las)?|en)\s+(.+?)(?=(?:,?\s+(?:(?:y|e)\s+)?(?:(?:el|la|los|las)\s+)?(?:art(?:[íi]culo|\.)|articulos?|jurisprudencia|tesis|criterio\s+aislad[oa]|registro\s+digital)\b)|[.;:\n]|$)",
re.IGNORECASE,
)
_RE_ARTICULO_CONSTITUCION = re.compile(
r"\b((?:art(?:[íi]culo|\.)|articulos?)\s+[0-9]+[A-Za-z\-]*(?:\s*(?:,|y|e)\s*[0-9]+[A-Za-z\-]*)*(?:\s+bis|\s+ter|\s+qu[áa]ter)?(?:\s*,?\s*fracci[oó]n\s+[IVXLCDM]+)?)\s+(?:constitucional|de la constituci[oó]n(?:\s+pol[ií]tica\s+de\s+los\s+estados\s+unidos\s+mexicanos)?)",
re.IGNORECASE,
)
_RE_ABREVIATURA_PARENTESIS = re.compile(
r"([A-ZÁÉÍÓÚÑ][A-Za-zÁÉÍÓÚÑáéíóúñ0-9 ,.;:/\-]{10,180}?)\s*\(([A-Z][A-Z0-9.]{1,15})\)",
)
_RE_ABREVIATURA_EN_LO_SUCESIVO = re.compile(
r"([A-ZÁÉÍÓÚÑ][A-Za-zÁÉÍÓÚÑáéíóúñ0-9 ,.;:/\-]{10,180}?)(?:,\s*)?en\s+lo\s+sucesivo(?:,\s*)?(?:se\s+denominar[aá]|denominad[oa]\s+como|citad[oa]\s+como)?\s*[\"“”']([A-Z][A-Z0-9.]{1,15})[\"“”']",
re.IGNORECASE,
)
_RE_ABREVIATURA_GLOSARIO = re.compile(
r"^\s*([A-Z][A-Z0-9.]{1,15})\s*[:=]\s*([^\n]{6,180})$",
re.MULTILINE,
)
# TTL response cache — only for successful, read-only upstream queries
_CACHE_TTL: int = int(os.getenv("CACHE_TTL", "300")) # seconds (default 5 min)
_cache: dict[str, tuple[float, int, Any]] = {} # key → (timestamp, status, data)
_cache_lock = threading.Lock()
def _cache_key(url: str, method: str, body: Optional[Any]) -> str:
body_str = json.dumps(body, sort_keys=True, ensure_ascii=False) if body is not None else ""
raw = f"{method}:{url}:{body_str}"
return hashlib.md5(raw.encode("utf-8")).hexdigest()
def _get_cached(key: str) -> Optional[tuple[int, Any]]:
with _cache_lock:
entry = _cache.get(key)
if entry is None:
return None
ts, status, data = entry
if time.time() - ts > _CACHE_TTL:
del _cache[key]
return None
return status, data
def _set_cached(key: str, status: int, data: Any) -> None:
if status >= 400:
return # never cache errors
with _cache_lock:
_cache[key] = (time.time(), status, data)
# Persistent HTTP client — reuses connections across requests
_HTTP_TIMEOUT = float(os.getenv("HTTP_TIMEOUT", "35"))
_http_client = httpx.Client(timeout=_HTTP_TIMEOUT, follow_redirects=True)
# Rate limiting — sliding window, no external deps
_RATE_LIMIT_WINDOW: int = int(os.getenv("RATE_LIMIT_WINDOW", "60")) # seconds
_RATE_LIMIT_MAX: int = int(os.getenv("RATE_LIMIT_MAX", "120")) # requests per window per IP
_rate_buckets: dict[str, list[float]] = {}
_rate_lock = threading.Lock()
def _parse_bool(value: Any, default: bool = False) -> bool:
if value is None:
return default
return str(value).lower() == "true"
def _normalize_text(value: str) -> str:
text = unicodedata.normalize("NFKD", str(value or ""))
text = "".join(ch for ch in text if not unicodedata.combining(ch))
text = _RE_WHITESPACE.sub(" ", text).strip().lower()
return text
def _normalize_search_text(value: str) -> str:
text = _normalize_text(value)
text = re.sub(r"[^\w]+", " ", text)
text = _RE_WHITESPACE.sub(" ", text).strip()
return text
_LEYES_INDEX = [
{
"id": ley.get("id"),
"categoria": ley.get("categoria"),
"nombre": ley.get("nombre") or "",
"nombreNormalizado": _normalize_text(ley.get("nombre") or ""),
}
for ley in leyes
if isinstance(ley, dict) and str(ley.get("nombre") or "").strip()
]
_LEYES_INDEX.sort(key=lambda item: len(item["nombreNormalizado"]), reverse=True)
def _default_sjf_payload(q: str) -> dict:
payload = {
"classifiers": [
{
"name": "idEpoca",
"value": ["210", "200", "100", "5", "4", "3", "2", "1"],
"allSelected": False,
"visible": False,
"isMatrix": False,
},
{
"name": "numInstancia",
"value": ["6", "0", "60", "7", "70", "80", "1", "2", "50", "3", "4", "5"],
"allSelected": False,
"visible": False,
"isMatrix": False,
},
{
"name": "tipoDocumento",
"value": ["1"],
"allSelected": False,
"visible": False,
"isMatrix": False,
},
],
"searchTerms": [],
"bFacet": True,
"ius": [],
"idApp": "SJFAPP2020",
"lbSearch": ["Todo"],
"filterExpression": "",
}
term = (q or "").strip()
if term:
payload["searchTerms"].append(
{
"expression": term,
"fields": ["localizacionBusqueda", "rubro", "texto", "precedentes"],
"fieldsUser": "",
"fieldsText": "",
"operator": 0,
"operatorUser": "Y",
"operatorText": "Y",
"lsFields": [],
"esInicial": True,
"esNRD": False,
}
)
return payload
_COMMON_HEADERS = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:148.0) Gecko/20100101 Firefox/148.0",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "es-MX,es;q=0.9,en-US;q=0.8,en;q=0.7",
}
def _build_headers(
origin: str,
referer: str,
cookie_env: str,
content_type: bool = False,
ct_value: str = "application/json",
) -> dict:
headers = {**_COMMON_HEADERS, "Origin": origin, "Referer": referer}
if content_type:
headers["Content-Type"] = ct_value
cookie = os.getenv(cookie_env)
if cookie:
headers["Cookie"] = cookie
return headers
def _sjf_headers(content_type: bool = False) -> dict:
return _build_headers(
"https://sjf2.scjn.gob.mx",
"https://sjf2.scjn.gob.mx/listado-resultado-tesis",
"SJF_COOKIE",
content_type,
)
def _jurislex_headers(content_type: bool = False) -> dict:
return _build_headers(
"https://jurislex.scjn.gob.mx",
"https://jurislex.scjn.gob.mx/",
"JURISLEX_COOKIE",
content_type,
ct_value="application/json;charset=utf-8",
)
def _bj_scjn_headers(content_type: bool = False) -> dict:
return _build_headers(
"https://bj.scjn.gob.mx",
"https://bj.scjn.gob.mx/",
"BJ_SCJN_COOKIE",
content_type,
)
def _http_json(
url: str,
method: str = "GET",
body: Optional[Any] = None,
headers: Optional[dict] = None,
use_cache: bool = False,
) -> tuple[int, Any]:
cache_key = _cache_key(url, method, body) if use_cache else None
if cache_key:
cached = _get_cached(cache_key)
if cached is not None:
return cached
content = json.dumps(body).encode("utf-8") if body is not None else None
try:
resp = _http_client.request(method=method, url=url, content=content, headers=headers or {})
try:
parsed: Any = resp.json()
except Exception:
parsed = {"rawText": resp.text}
status = resp.status_code
if status < 400 and cache_key:
_set_cached(cache_key, status, parsed)
elif status >= 400:
logger.warning("upstream HTTP error %s for %s %s", status, method, url)
return status, parsed
except httpx.TimeoutException as exc:
logger.error("upstream timeout for %s %s", method, url)
return 504, {"error": "upstream request timed out", "errorType": type(exc).__name__, "detail": str(exc)}
except httpx.RequestError as exc:
logger.error("upstream request error for %s %s: %s", method, url, exc)
return 502, {"error": "upstream request failed", "errorType": type(exc).__name__, "detail": str(exc)}
except Exception as exc:
logger.error("unexpected error for %s %s: %s", method, url, exc)
return 502, {"error": "upstream request failed", "errorType": type(exc).__name__, "detail": str(exc)}
def _redact_headers(headers: Optional[dict]) -> dict:
safe_headers = {}
for key, value in (headers or {}).items():
if str(key).lower() == "cookie":
safe_headers[key] = "<redacted>"
else:
safe_headers[key] = value
return safe_headers
def _sjf_detail_attempt(ius: int, host_name: str, is_semanal, include_host_name: bool):
params = {}
if include_host_name:
params["hostName"] = host_name
if is_semanal is True:
params["isSemanal"] = "true"
elif is_semanal is False:
params["isSemanal"] = "false"
query = parse.urlencode(params)
url = f"{SJF_BASE}/tesis/{ius}"
if query:
url = f"{url}?{query}"
headers = _sjf_headers(content_type=False)
started_at = time.time()
status, data = _http_json(url, method="GET", headers=headers)
elapsed_ms = int((time.time() - started_at) * 1000)
return {
"status": status,
"data": data,
"url": url,
"isSemanal": is_semanal,
"hostNameIncluded": include_host_name,
"durationMs": elapsed_ms,
"requestHeaders": _redact_headers(headers),
}
def _sjf_detail_attempts(ius: int, host_name: str, is_semanal: Optional[bool]):
if is_semanal is None:
plans = [(True, True), (False, True), (True, False), (False, False)]
else:
plans = [(bool(is_semanal), True), (bool(is_semanal), False)]
attempts = []
for sem_value, include_host_name in plans:
attempt = _sjf_detail_attempt(ius, host_name, sem_value, include_host_name)
attempts.append(attempt)
if attempt["status"] < 400:
return attempt, attempts
return attempts[-1], attempts
def _extract_results(payload: Any, *keys: str) -> list:
"""Return the first list found in payload (or payload["data"]) under any of the given keys."""
if not isinstance(payload, dict):
return []
for key in keys:
val = payload.get(key)
if isinstance(val, list):
return val
data = payload.get("data")
if isinstance(data, dict):
for key in keys:
val = data.get(key)
if isinstance(val, list):
return val
return []
def _normalize_doc(doc: dict, include_raw: bool = False) -> dict:
ius = doc.get("ius") or doc.get("registroDigital") or doc.get("id")
semanal_raw = doc.get("semanal")
if semanal_raw is None:
semanal_raw = doc.get("isSemanal")
if semanal_raw is None:
is_semanal = None
else:
is_semanal = semanal_raw is True or semanal_raw == 1 or str(semanal_raw) == "1"
rubro = _strip_html(doc.get("rubro") or doc.get("rubroTexto") or "").upper()
texto = str(doc.get("textoPublicacion") or doc.get("texto") or "")
texto_snippet = _strip_html(texto)[:500]
item = {
"ius": ius,
"isSemanal": is_semanal,
"rubro": rubro,
"fechaPublicacion": doc.get("fechaPublicacion") or doc.get("fecha") or "",
"instancia": doc.get("instancia") or "",
"epoca": doc.get("epoca") or "",
"tipoDocumento": doc.get("tipoDocumento") or "",
"textoSnippet": texto_snippet,
}
if include_raw:
item["raw"] = doc
return item
def _to_int(value: Any, fallback: int) -> int:
try:
return int(value)
except Exception:
return fallback
def _to_bool(value: Any, fallback: bool = False) -> bool:
if value is None:
return fallback
if isinstance(value, bool):
return value
return str(value).lower() in ("true", "1", "yes", "si")
def _strip_html(value: Any) -> str:
text = str(value or "")
text = html.unescape(text)
text = text.replace("<br>", "\n").replace("<br/>", "\n").replace("<br />", "\n")
text = text.replace("</p>", "\n\n").replace("<p>", "")
text = _RE_HTML_TAG.sub("", text)
text = _RE_EXCESS_NEWLINES.sub("\n\n", text)
return text.strip()
def _extract_docx_text_from_xml(raw_xml: bytes) -> str:
try:
root = ElementTree.fromstring(raw_xml)
except Exception:
return ""
paragraphs: list[str] = []
for paragraph_node in root.iter():
if paragraph_node.tag.rsplit("}", 1)[-1] != "p":
continue
current_parts: list[str] = []
for node in paragraph_node.iter():
tag = node.tag.rsplit("}", 1)[-1]
if tag == "t":
current_parts.append(node.text or "")
elif tag == "tab":
current_parts.append("\t")
elif tag in {"br", "cr"}:
current_parts.append("\n")
paragraph = "".join(current_parts).strip()
if paragraph:
paragraphs.append(paragraph)
return "\n\n".join(paragraphs)
def _extract_docx_text(content: bytes) -> str:
targets = [
"word/document.xml",
"word/footnotes.xml",
"word/endnotes.xml",
"word/header1.xml",
"word/header2.xml",
"word/header3.xml",
"word/footer1.xml",
"word/footer2.xml",
"word/footer3.xml",
]
parts: list[str] = []
try:
with zipfile.ZipFile(io.BytesIO(content)) as archive:
names = set(archive.namelist())
for target in targets:
if target not in names:
continue
text = _extract_docx_text_from_xml(archive.read(target))
if text:
parts.append(text)
except zipfile.BadZipFile:
return ""
except Exception:
return ""
merged = "\n\n".join(part for part in parts if part.strip())
return _RE_EXCESS_NEWLINES.sub("\n\n", merged).strip()
def _jurislex_filter_raw(id_legislacion: int, articulo_numero: Optional[int] = None) -> str:
if articulo_numero is None:
data = {
"bool": {
"should": [
{"terms": {"ordenamiento.idOrdenamiento": [int(id_legislacion)]}}
]
}
}
else:
data = {
"bool": {
"should": [
{
"bool": {
"must": [
{"term": {"ordenamiento.idOrdenamiento": int(id_legislacion)}},
{"terms": {"articulos": [int(articulo_numero)]}},
]
}
}
]
}
}
return json.dumps(data, ensure_ascii=False)
def _jurislex_desc_value(desc: str, articulo_numero: Optional[int]) -> str:
desc_text = str(desc or "").strip()
if desc_text:
return desc_text
if articulo_numero is not None:
return str(int(articulo_numero))
return ""
def _jurislex_search_filter_raw(id_legislacion: int, articulo_numero: Optional[int], raw_desc: str) -> str:
# Jurislex encuentra mejor artículos concretos usando Desc="<numero>" con filtro amplio por ordenamiento.
if articulo_numero is not None and not str(raw_desc or "").strip():
return _jurislex_filter_raw(id_legislacion, None)
return _jurislex_filter_raw(id_legislacion, articulo_numero)
def _normalize_jurislex_result(item: dict, include_raw: bool = False) -> dict:
normalized = {
"idArticulo": item.get("iId"),
"idLegislacion": item.get("iIdLey"),
"numeroArticulo": item.get("iNumArt"),
"tipo": item.get("iTipo"),
"ley": item.get("sDescLey") or "",
"texto": item.get("sDesc") or "",
"textoPlano": _strip_html(item.get("sDesc") or ""),
}
if include_raw:
normalized["raw"] = item
return normalized
# Convenience wrappers kept for clarity at call sites
def _extract_docs(payload: Any) -> list:
return _extract_results(payload, "documents", "content", "results")
def _extract_bj_items(data: Any) -> list:
return _extract_results(data, "resultados")
def _extracto_texto(extractos):
if isinstance(extractos, dict):
texto = extractos.get("Texto")
if isinstance(texto, list):
chunks = [_strip_html(x) for x in texto if str(x or "").strip()]
return " ... ".join(chunks[:3]).strip()
if isinstance(texto, str):
return _strip_html(texto)
if isinstance(extractos, list):
chunks = [_strip_html(x) for x in extractos if str(x or "").strip()]
return " ... ".join(chunks[:3]).strip()
if isinstance(extractos, str):
return _strip_html(extractos)
return ""
def _extract_bj_extractos(extractos: Any, limit: int = 5) -> list[dict]:
if not isinstance(extractos, dict):
return []
items = []
for tipo, value in extractos.items():
values = value if isinstance(value, list) else [value]
for snippet in values:
texto = _strip_html(snippet)
if not texto:
continue
items.append({"tipo": str(tipo or ""), "texto": texto[:700]})
if len(items) >= limit:
return items
return items
def _normalize_bj_item(item: dict, include_raw: bool = False) -> dict:
epoca = item.get("epoca") if isinstance(item.get("epoca"), dict) else {}
localizacion = item.get("localizacion") if isinstance(item.get("localizacion"), dict) else {}
texto = str(item.get("texto") or "")
extracto = _extracto_texto(item.get("extractos"))
normalized = {
"registroDigital": item.get("registroDigital"),
"rubro": _strip_html(item.get("rubro") or ""),
"tipoEjecutoria": item.get("tipoEjecutoria") or "",
"tipoAsunto": item.get("tipoAsunto") or "",
"asunto": item.get("asunto") or "",
"organoJurisdiccional": item.get("organoJurisdiccional") or "",
"instancia": item.get("instancia") or "",
"epoca": {
"numero": epoca.get("numero") or "",
"nombre": epoca.get("nombre") or "",
},
"tesis": item.get("tesis") or "",
"numeroExpediente": item.get("numeroExpediente") or "",
"promovente": item.get("promovente") or "",
"fuente": item.get("fuente") or "",
"volumen": item.get("volumen") or "",
"localizacion": {
"libro": localizacion.get("libro") or "",
"tomo": localizacion.get("tomo") or "",
"mes": localizacion.get("mes") or "",
"anio": localizacion.get("anio") or "",
"pagina": localizacion.get("pagina") or "",
},
"textoSnippet": _strip_html(texto)[:700],
"extractoSnippet": extracto[:700],
}
if include_raw:
normalized["raw"] = item
return normalized
def _normalize_bj_legislacion_item(item: dict, include_raw: bool = False) -> dict:
materias = item.get("materia") if isinstance(item.get("materia"), list) else []
extractos = _extract_bj_extractos(item.get("extractos"))
normalized = {
"id": item.get("id"),
"ordenamiento": item.get("ordenamiento") or "",
"categoriaOrdenamiento": item.get("categoriaOrdenamiento") or "",
"ambito": item.get("ambito") or "",
"estado": item.get("estado") or "",
"pais": item.get("pais") or "",
"vigencia": item.get("vigencia") or "",
"fechaPublicacion": item.get("fechaPublicado") or "",
"materias": [str(materia) for materia in materias if str(materia or "").strip()],
"resumen": _strip_html(item.get("resumen") or ""),
"extractos": extractos,
"textoSnippet": (extractos[0]["texto"] if extractos else ""),
}
if include_raw:
normalized["raw"] = item
return normalized
def _normalize_bj_legislacion_bloque(item: dict, include_raw: bool = False) -> dict:
normalized = {
"id": item.get("id"),
"orden": item.get("orden"),
"referencia": item.get("referencia") or "",
"numero": item.get("numero"),
"vigencia": item.get("vigencia") or "",
"fechaActualizacion": item.get("fechaActualizacion") or "",
"articuloVersion": item.get("articuloVersion"),
"contenido": item.get("contenido") or "",
"contenidoPlano": _strip_html(item.get("contenido") or ""),
}
if include_raw:
normalized["raw"] = item
return normalized
def _normalize_bj_legislacion_detail(data: dict, documento_id: int, include_raw: bool = False) -> dict:
articulos = data.get("articulos") if isinstance(data.get("articulos"), list) else []
bloques = [_normalize_bj_legislacion_bloque(item, include_raw=include_raw) for item in articulos if isinstance(item, dict)]
encabezado = next((bloque for bloque in bloques if bloque.get("referencia") == "ENCABEZADO"), None)
response = {
"id": data.get("id") or documento_id,
"ordenamiento": data.get("ordenamiento") or (encabezado or {}).get("contenidoPlano", "").split("\n\n", 1)[0],
"categoriaOrdenamiento": data.get("categoriaOrdenamiento") or "",
"ambito": data.get("ambito") or "",
"estado": data.get("estado") or "",
"pais": data.get("pais") or "",
"vigencia": data.get("vigencia") or "",
"fechaPublicacion": data.get("fechaPublicado") or "",
"fechaActualizacion": data.get("fechaActualizacion") or "",
"materias": [str(materia) for materia in (data.get("materia") or []) if str(materia or "").strip()] if isinstance(data.get("materia"), list) else [],
"resumen": _strip_html(data.get("resumen") or ""),
"totalBloques": len(bloques),
"bloques": bloques,
}
if include_raw:
response["raw"] = data
return response
def _extract_article_numbers(fragment: str) -> list[str]:
return re.findall(r"\d+[A-Za-z\-]*", str(fragment or ""))
def _resolve_ley_reference(raw_ley: str) -> Optional[dict]:
ley_norm = _normalize_text(raw_ley)
if not ley_norm:
return None
exact_matches = [candidate for candidate in _LEYES_INDEX if candidate["nombreNormalizado"] == ley_norm]
if exact_matches:
return min(exact_matches, key=lambda item: len(item["nombreNormalizado"]))
contains_matches = [candidate for candidate in _LEYES_INDEX if ley_norm and ley_norm in candidate["nombreNormalizado"]]
if contains_matches:
return min(contains_matches, key=lambda item: len(item["nombreNormalizado"]))
for candidate in _LEYES_INDEX:
candidate_norm = candidate["nombreNormalizado"]
if candidate_norm in ley_norm:
return candidate
tokens = [token for token in ley_norm.split(" ") if len(token) > 2]
if not tokens:
return None
best_match = None
best_score = 0
for candidate in _LEYES_INDEX:
score = sum(1 for token in tokens if token in candidate["nombreNormalizado"])
if score > best_score and score >= min(3, len(tokens)):
best_match = candidate
best_score = score
return best_match
def _resolve_constitucion_reference() -> Optional[dict]:
for candidate in _LEYES_INDEX:
if candidate["nombreNormalizado"] == "constitucion politica de los estados unidos mexicanos":
return candidate
return None
def _resolve_document_law_reference(raw_ley: str) -> Optional[dict]:
raw = str(raw_ley or "").strip()
if not raw:
return None
raw_norm = _normalize_text(raw)
if raw_norm in {
"constitucion politica de los estados unidos mexicanos",
"constitucion federal",
"cpeum",
}:
return _resolve_constitucion_reference()
return _resolve_ley_reference(raw)
def _clean_abbreviation(value: str) -> str:
cleaned = str(value or "").strip().strip("()[]{}.,;: ")
if not cleaned:
return ""
if not re.fullmatch(r"[A-Z][A-Z0-9.]{1,15}", cleaned):
return ""
return cleaned
def _register_abbreviation(
results: list[dict],
seen: set[tuple[str, str]],
abbreviation: str,
candidate_name: str,
start: int,
end: int,
source: str,
) -> None:
abbr = _clean_abbreviation(abbreviation)
if not abbr:
return
resolved = _resolve_document_law_reference(candidate_name)
if resolved is None:
return
resolved_name = str(resolved.get("nombre") or "").strip()
detected_name = str(candidate_name or "").strip()
if resolved_name and _normalize_text(resolved_name) in _normalize_text(detected_name):
detected_name = resolved_name
key = (abbr, resolved_name)
if key in seen:
return
seen.add(key)
results.append(
{
"abreviatura": abbr,
"nombreDetectado": detected_name,
"nombreResuelto": resolved_name or detected_name,
"idLegislacion": resolved.get("id"),
"categoria": resolved.get("categoria"),
"inicio": start,
"fin": end,
"confianza": "alta",
"fuente": source,
}
)
def _extract_document_abbreviations(texto: str) -> list[dict]:
abbreviations: list[dict] = []
seen: set[tuple[str, str]] = set()
for match in _RE_ABREVIATURA_PARENTESIS.finditer(texto):
_register_abbreviation(
abbreviations,
seen,
match.group(2),
match.group(1),
match.start(),
match.end(),
"parentesis",
)
for match in _RE_ABREVIATURA_EN_LO_SUCESIVO.finditer(texto):
_register_abbreviation(
abbreviations,
seen,
match.group(2),
match.group(1),
match.start(),
match.end(),
"enLoSucesivo",
)
for match in _RE_ABREVIATURA_GLOSARIO.finditer(texto):
_register_abbreviation(
abbreviations,
seen,
match.group(1),
match.group(2),
match.start(),
match.end(),
"glosario",
)
abbreviations.sort(key=lambda item: (item.get("inicio", 0), item.get("abreviatura", "")))
return abbreviations
def _abbreviation_map(abbreviations: list[dict]) -> dict[str, dict]:
mapping: dict[str, dict] = {}
for item in abbreviations:
abbr = _clean_abbreviation(item.get("abreviatura") or "")
if abbr and abbr not in mapping:
mapping[abbr] = item
return mapping
def _append_cita(citas: list[dict], seen: set[tuple], item: dict) -> None:
key = (item.get("tipo"), item.get("inicio"), item.get("fin"), item.get("textoOriginal"))
if key in seen:
return
seen.add(key)
citas.append(item)
def _append_cita_if_not_contained(citas: list[dict], seen: set[tuple], item: dict) -> None:
clave = str(item.get("clave") or "").strip().lower()
inicio = item.get("inicio")
fin = item.get("fin")
if clave and inicio is not None and fin is not None:
for existing in citas:
existing_clave = str(existing.get("clave") or "").strip().lower()
if existing_clave == clave and existing.get("inicio", -1) <= inicio and existing.get("fin", -1) >= fin:
return
_append_cita(citas, seen, item)
def _sjf_exact_match_for_clave(clave: str) -> Optional[dict]:
clave_norm = _normalize_search_text(clave)
if not clave_norm:
return None
status, data = _http_json(
f"{SJF_BASE}/tesis?page=0&size=5",
method="POST",
body=_default_sjf_payload(clave),
headers=_sjf_headers(content_type=True),
use_cache=True,
)
if status >= 400:
return None
docs = _extract_docs(data)
for doc in docs:
candidate = str(doc.get("claveTesis") or doc.get("tesis") or "")
if _normalize_search_text(candidate) == clave_norm:
return {
"ius": doc.get("ius") or doc.get("registroDigital") or doc.get("id"),
"claveCanonical": candidate,
"rubro": _strip_html(doc.get("rubro") or ""),
"fuente": doc.get("fuente") or "SJF",
"sala": doc.get("sala") or "",
"tipoTesis": doc.get("tipoTesis") or "",
"localizacion": doc.get("localizacion") or "",
}
return None
def _enrich_jurisprudencial_cita(item: dict) -> dict:
clave = str(item.get("clave") or "").strip()
if not clave:
item["confianza"] = "media"
item["requiereConfirmacion"] = True
item["motivoConfirmacion"] = "cita jurisprudencial sin clave verificable"
item["resuelta"] = False
return item
match = _sjf_exact_match_for_clave(clave)
if match is not None:
item["resuelta"] = True
item["confianza"] = "alta"
item["requiereConfirmacion"] = False
item["ius"] = match.get("ius")
item["claveCanonical"] = match.get("claveCanonical")
item["rubro"] = match.get("rubro")
item["fuenteProbable"] = match.get("fuente")
item["localizacion"] = match.get("localizacion")
return item
item["resuelta"] = False
item["confianza"] = "media"
item["requiereConfirmacion"] = True
item["motivoConfirmacion"] = "clave detectada sin coincidencia exacta en SJF"
item["fuenteProbable"] = "SJF"
item["consultaSugerida"] = clave
return item
def _resolve_cita_articulo(cita: dict) -> Optional[dict]:
articulos = cita.get("articulos") or []
if not articulos:
return None
articulo = str(articulos[0])
nombre = str(cita.get("ley") or cita.get("leyMencionada") or "")
if not nombre:
return None
detail = _normas_articulos_detalle_core(
nombre=nombre,
articulo=articulo,
q=None,
page=1,
size=5,
include_raw=False,
)
if isinstance(detail, JSONResponse):
return None
articulo_detail = detail.get("articulo") or {}
return {
"tipo": "articulo",
"textoOriginal": cita.get("textoOriginal"),
"fuenteUsada": detail.get("fuenteUsada") or "",
"ley": articulo_detail.get("ley") or nombre,
"numero": articulo_detail.get("numero"),
"referencia": articulo_detail.get("referencia") or "",
"libro": articulo_detail.get("libro") or "",
"titulo": articulo_detail.get("titulo") or "",
"capitulo": articulo_detail.get("capitulo") or "",
"texto": articulo_detail.get("textoPlano") or articulo_detail.get("texto") or "",
"meta": articulo_detail.get("meta") or {},
}
def _resolve_cita_jurisprudencial(cita: dict) -> Optional[dict]:
ius = cita.get("ius") or cita.get("registroDigital")
if ius is None:
return None
try:
ius_value = int(ius)
except Exception:
return None
detail = sjf_detail(ius=ius_value, isSemanal=None, hostName="https://sjf2.scjn.gob.mx", includeRaw=False, debug=False)
if isinstance(detail, JSONResponse):
return None
return {
"tipo": cita.get("tipo") or "jurisprudencia",
"textoOriginal": cita.get("textoOriginal"),
"ius": detail.get("ius") or ius_value,
"clave": cita.get("claveCanonical") or cita.get("clave") or "",
"rubro": detail.get("rubro") or cita.get("rubro") or "",
"fechaPublicacion": detail.get("fechaPublicacion") or "",
"texto": detail.get("textoPlano") or detail.get("texto") or "",
"fuenteUsada": "SJF",
}
def _resolve_cita_detalle(cita: dict) -> Optional[dict]:
if cita.get("tipo") == "articulo":
return _resolve_cita_articulo(cita)