Add scrapers_and_normalizers overlay (courts+caselaw/courts_caselaw, data/* untouched) [2/3]
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/americas/__init__.pyAdded+5
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/asia_pacific/__init__.pyAdded+5
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/__init__.pyAdded+73
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/base.pyAdded+161
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/complaint_types.pyAdded+1520
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/legal_patterns.pyAdded+489
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/civil_rights_tree.jsonAdded+95
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/consumer_tree.jsonAdded+97
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/criminal_defense_tree.jsonAdded+72
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/dei_tree.jsonAdded+55
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/employment_tree.jsonAdded+129
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/environmental_law_tree.jsonAdded+71
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/family_law_tree.jsonAdded+74
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/free_speech_tree.jsonAdded+72
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/healthcare_tree.jsonAdded+83
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/housing_tree.jsonAdded+141
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/immigration_tree.jsonAdded+70
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/intellectual_property_tree.jsonAdded+72
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/probate_tree.jsonAdded+116
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/tax_law_tree.jsonAdded+74
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/__init__.pyAdded+19
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/__main__.pyAdded+463
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/admit.pyAdded+702
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/auth.pyAdded+38
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/bm25.pyAdded+227
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/build.pyAdded+661
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/catalog.pyAdded+307
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/cidutil.pyAdded+102
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/citations.pyAdded+139
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/coverage.pyAdded+455
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/duckdb_store.pyAdded+475
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/graph.pyAdded+350
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/html_legal.pyAdded+213
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/incremental.pyAdded+562
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/instrument_inherit.pyAdded+442
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/mem.pyAdded+301
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/national_directory.pyAdded+697
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize.pyAdded+1272
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize_loop.pyAdded+621
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/package.pyAdded+1010
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/parquet_io.pyAdded+83
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/profiles.pyAdded+342
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/query.pyAdded+221
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/raw_package.pyAdded+324
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/reconstruct.pyAdded+232
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/resources.pyAdded+200
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/schema.pyAdded+128
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/sparse.pyAdded+144
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/spill.pyAdded+532
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/structure.pyAdded+2203
12345"""Americas official-gazette collectors (North, Central, South America, Caribbean)."""
from ipfs_datasets_py.processors.legal_scrapers.regions import Americas
__all__ = ["Americas"]12345"""Asia-Pacific official-gazette collectors, including Oceania."""
from ipfs_datasets_py.processors.legal_scrapers.regions import AsiaPacific
__all__ = ["AsiaPacific"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273"""Shared components for legal search and complaint analysis.
This module contains components that are used by both:- Brave Legal Search system (query_processor, search_term_generator)- Complaint Analysis system (analyzer, indexer, risk_scoring)
Components extracted from complaint_analysis for reusability:- keywords.py: Keyword registry and management- legal_patterns.py: Pattern extraction and matching- base.py: Abstract base classes and interfaces- complaint_types.py: Complaint type definitions and registry
Usage: from ipfs_datasets_py.processors.legal_scrapers.common import ( get_keywords, LegalPatternExtractor, BaseComplaintAnalyzer, get_registered_types )"""
# Import all shared components for easy accessfrom .keywords import ( COMPLAINT_KEYWORDS, register_keywords, register_legal_terms, get_keywords, get_type_specific_keywords,)
from .legal_patterns import ( LegalPatternExtractor, ComplaintLegalPatternExtractor, extract_legal_patterns, extract_complaint_patterns,)
from .base import ( BaseComplaintAnalyzer, BaseRiskScorer, BaseComplaintIndexer,)
from .complaint_types import ( ComplaintType, register_complaint_type, get_registered_types, get_complaint_type,)
__all__ = [ # Keywords "COMPLAINT_KEYWORDS", "register_keywords", "register_legal_terms", "get_keywords", "get_type_specific_keywords", # Legal Patterns "LegalPatternExtractor", "ComplaintLegalPatternExtractor", "extract_legal_patterns", "extract_complaint_patterns", # Base Classes "BaseComplaintAnalyzer", "BaseRiskScorer", "BaseComplaintIndexer", # Complaint Types "ComplaintType", "register_complaint_type", "get_registered_types", "get_complaint_type",]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161"""Base Classes for Extensible Complaint Analysis
These abstract base classes define the interface for extending the complaintanalysis system with new complaint types, keywords, and risk scoring logic."""
from abc import ABC, abstractmethodfrom typing import Dict, List, Optional, Any
class BaseLegalPatternExtractor(ABC): """ Abstract base class for legal pattern extraction.
Extend this class to add custom legal term patterns for new complaint types. """
@abstractmethod def extract_provisions(self, text: str, context_chars: int = 200) -> Dict[str, Any]: """ Extract legal provisions from text.
Args: text: Text to analyze context_chars: Number of characters to include before/after match
Returns: Dictionary with provisions, terms_found, provision_count, etc. """ pass
@abstractmethod def extract_citations(self, text: str) -> List[Dict[str, str]]: """ Extract legal citations from text.
Args: text: Text to analyze
Returns: List of found citations with metadata """ pass
@abstractmethod def categorize_complaint_type(self, text: str) -> List[str]: """ Categorize the complaint based on content.
Args: text: Text to analyze
Returns: List of applicable complaint categories """ pass
class BaseKeywordRegistry(ABC): """ Abstract base class for keyword registry.
Extend this class to implement custom keyword management for different complaint types or domains. """
@abstractmethod def register_keywords( self, category: str, keywords: List[str], complaint_type: Optional[str] = None ) -> None: """ Register keywords for a category.
Args: category: Category name (e.g., 'complaint', 'evidence', 'legal') keywords: List of keywords to register complaint_type: Optional complaint type to scope keywords to """ pass
@abstractmethod def get_keywords(self, category: str, complaint_type: Optional[str] = None) -> List[str]: """ Get keywords for a category.
Args: category: Category name complaint_type: Optional complaint type to filter by
Returns: List of keywords """ pass
@abstractmethod def get_all_categories(self, complaint_type: Optional[str] = None) -> List[str]: """ Get all registered categories.
Args: complaint_type: Optional complaint type to filter by
Returns: List of category names """ pass
class BaseRiskScorer(ABC): """ Abstract base class for risk scoring.
Extend this class to implement custom risk scoring logic for different complaint types or risk models. """
@abstractmethod def calculate_risk( self, text: str, legal_provisions: Optional[List[Dict]] = None, **kwargs ) -> Dict[str, Any]: """ Calculate risk score for a complaint.
Args: text: Document text to analyze legal_provisions: Optional pre-extracted legal provisions **kwargs: Additional parameters for risk calculation
Returns: Dictionary containing: - score: Risk score (numeric) - level: Risk level name - factors: List of contributing factors - recommendations: Suggested actions """ pass
@abstractmethod def get_risk_levels(self) -> List[str]: """ Get available risk levels.
Returns: List of risk level names (e.g., ['minimal', 'low', 'medium', 'high']) """ pass
@abstractmethod def is_actionable(self, text: str, threshold: float = 0.5) -> bool: """ Determine if complaint is actionable.
Args: text: Document text threshold: Minimum score threshold
Returns: True if actionable """ pass12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520"""Complaint Type Registration
Provides convenience functions for registering different complaint typeswith their specific keywords, patterns, and scoring models."""
from typing import Any, Dict, List, Optionalfrom .keywords import register_keywordsfrom .legal_patterns import register_legal_terms
def register_housing_complaint(): """Register keywords and patterns for housing complaints.""" # Already registered in keywords.py, but this allows for programmatic registration pass
def register_employment_complaint(): """Register keywords and patterns for employment complaints.""" # Already registered in keywords.py pass
def register_civil_rights_complaint(): """Register keywords and patterns for civil rights complaints.""" # Additional civil rights specific keywords register_keywords( "complaint", [ "police brutality", "excessive force", "unlawful search", "unlawful seizure", "first amendment", "freedom of speech", "freedom of assembly", "voting rights", ], complaint_type="civil_rights", )
def register_consumer_complaint(): """Register keywords and patterns for consumer protection complaints.""" register_keywords( "complaint", [ "fraud", "deception", "misrepresentation", "unfair practice", "deceptive practice", "false advertising", "bait and switch", "warranty breach", "consumer protection", "ftc", "federal trade commission", ], complaint_type="consumer", )
register_legal_terms( "consumer", [ r"\b(fraud|fraudulent)\b", r"\b(deceptive (practice|trade))\b", r"\b(false advertising)\b", r"\b(consumer protection)\b", r"\b(ftc|federal trade commission)\b", ], )
def register_healthcare_complaint(): """Register keywords and patterns for healthcare complaints.""" register_keywords( "complaint", [ "medical malpractice", "negligence", "hipaa", "medical privacy", "patient rights", "informed consent", "emergency medical", "emtala", ], complaint_type="healthcare", )
def register_free_speech_complaint(): """Register keywords and patterns for censorship and free speech complaints.""" register_keywords( "complaint", [ # First Amendment "first amendment", "free speech", "freedom of speech", "freedom of expression", "freedom of the press", "prior restraint", "viewpoint discrimination", "content-based restriction", "content-neutral", # Censorship "censorship", "censor", "censored", "suppression", "silenced", "deplatformed", "banned", "suspension", "account termination", # Social media / platforms "content moderation", "platform moderation", "community guidelines", "terms of service violation", "shadowban", "demonetized", "demonetization", "algorithm bias", "content suppression", # Public forum / government "public forum", "limited public forum", "government censorship", "state action", "chilling effect", "prior restraint", # Academic / institutional "academic freedom", "intellectual freedom", "library censorship", "book ban", "curriculum restriction", # Whistleblower / retaliation "whistleblower", "retaliation for speech", "protected speech", "political speech", ], complaint_type="free_speech", )
register_legal_terms( "free_speech", [ r"\b(first amendment)\b", r"\b(free(dom of)? speech)\b", r"\b(free(dom of)? (expression|press))\b", r"\b(prior restraint)\b", r"\b(viewpoint discrimination)\b", r"\b(content[- ]based restriction)\b", r"\b(public forum)\b", r"\b(state action)\b", r"\b(chilling effect)\b", r"\b(censorship|censor(ed)?)\b", ], )
def register_immigration_complaint(): """Register keywords and patterns for immigration law complaints.""" register_keywords( "complaint", [ # Immigration status "immigration", "immigrant", "undocumented", "visa", "green card", "permanent resident", "naturalization", "citizenship", "asylum", "refugee", "asylee", "temporary protected status", "tps", "daca", "dreamer", "deferred action", # Agencies and processes "uscis", "ice", "cbp", "immigration and customs enforcement", "customs and border protection", "immigration court", "eoir", "deportation", "removal proceedings", "detention", "immigration detention", "bond hearing", # Employment immigration "h-1b", "h-2a", "h-2b", "l-1", "o-1", "employment-based visa", "labor certification", "perm", "prevailing wage", # Family immigration "family-based immigration", "family petition", "i-130", "marriage-based green card", "adjustment of status", "consular processing", # Immigration violations "immigration fraud", "unlawful presence", "visa overstay", "bars to admission", "inadmissibility", "removal order", # Rights and remedies "withholding of removal", "cancellation of removal", "relief from removal", "stay of removal", "travel document", "advance parole", "employment authorization", "work permit", ], complaint_type="immigration", )
register_legal_terms( "immigration", [ r"\b(immigration|immigrant)\b", r"\b(visa|green card)\b", r"\b(asylum|refugee|asylee)\b", r"\b(deportation|removal)\b", r"\b(uscis|ice|cbp|eoir)\b", r"\b(daca|dreamer)\b", r"\b(h-?1b|h-?2[ab]|l-?1|o-?1)\b", r"\b(adjustment of status)\b", r"\b(withholding of removal)\b", r"\b(cancellation of removal)\b", ], )
def register_family_law_complaint(): """Register keywords and patterns for family law complaints.""" register_keywords( "complaint", [ # Divorce / dissolution "divorce", "dissolution of marriage", "legal separation", "annulment", "marital property", "community property", "equitable distribution", "property division", # Child custody "child custody", "parenting time", "visitation", "sole custody", "joint custody", "shared custody", "physical custody", "legal custody", "custodial parent", "non-custodial parent", "parenting plan", "custody order", # Child support "child support", "support obligation", "child support arrears", "support enforcement", "support modification", # Spousal support "alimony", "spousal support", "maintenance", "temporary support", "rehabilitative support", "permanent support", # Domestic violence "domestic violence", "domestic abuse", "protective order", "restraining order", "order of protection", "no-contact order", # Adoption / guardianship "adoption", "guardianship", "foster care", "termination of parental rights", # Paternity "paternity", "parentage", "genetic testing", ], complaint_type="family_law", )
register_legal_terms( "family_law", [ r"\b(divorce|dissolution)\b", r"\b(child custody|parenting time)\b", r"\b(child support)\b", r"\b(alimony|spousal support)\b", r"\b(domestic (violence|abuse))\b", r"\b((protective|restraining) order)\b", r"\b(adoption|guardianship)\b", r"\b(paternity|parentage)\b", ], )
def register_criminal_defense_complaint(): """Register keywords and patterns for criminal defense complaints.""" register_keywords( "complaint", [ # Constitutional rights "fourth amendment", "unreasonable search", "illegal search", "warrantless search", "fifth amendment", "self-incrimination", "miranda rights", "right to remain silent", "sixth amendment", "right to counsel", "effective assistance of counsel", "speedy trial", "jury trial", "eighth amendment", "cruel and unusual punishment", "excessive bail", "excessive fine", # Due process "due process", "procedural due process", "substantive due process", "fundamental fairness", # Criminal procedure "arrest", "detention", "probable cause", "search warrant", "arrest warrant", "suppression of evidence", "exclusionary rule", "fruit of the poisonous tree", "interrogation", "confession", "coerced confession", # Criminal charges "criminal charge", "indictment", "information", "misdemeanor", "felony", "infraction", # Trial rights "jury selection", "voir dire", "peremptory challenge", "confrontation clause", "cross-examination", "prosecutorial misconduct", "brady violation", "exculpatory evidence", # Sentencing "sentencing", "sentence enhancement", "three strikes", "mandatory minimum", "parole", "probation", "supervised release", # Post-conviction "habeas corpus", "post-conviction relief", "ineffective assistance", "actual innocence", "wrongful conviction", ], complaint_type="criminal_defense", )
register_legal_terms( "criminal_defense", [ r"\b((fourth|fifth|sixth|eighth) amendment)\b", r"\b(miranda (rights|warning))\b", r"\b(right to (counsel|remain silent|jury trial))\b", r"\b(due process)\b", r"\b(unreasonable search)\b", r"\b(probable cause)\b", r"\b(exclusionary rule)\b", r"\b(brady violation)\b", r"\b(habeas corpus)\b", r"\b(ineffective assistance)\b", ], )
def register_tax_law_complaint(): """Register keywords and patterns for tax law complaints.""" register_keywords( "complaint", [ # Tax agencies "irs", "internal revenue service", "tax court", "u.s. tax court", "state tax", "state department of revenue", # Tax types "income tax", "corporate tax", "estate tax", "gift tax", "payroll tax", "employment tax", "excise tax", "sales tax", "property tax", # Tax processes "tax audit", "examination", "revenue agent", "notice of deficiency", "statutory notice", "tax assessment", "tax liability", "collection due process", "cdp hearing", # Tax penalties "tax penalty", "accuracy penalty", "fraud penalty", "failure to file", "failure to pay", "estimated tax penalty", # Tax remedies "innocent spouse relief", "offer in compromise", "installment agreement", "currently not collectible", "penalty abatement", "interest abatement", # Tax collection "tax levy", "tax lien", "wage garnishment", "bank levy", "seizure", "collection action", # Tax procedure "tax return", "amended return", "refund claim", "statute of limitations", "collection statute", "assessment statute", ], complaint_type="tax_law", )
register_legal_terms( "tax_law", [ r"\b(irs|internal revenue service)\b", r"\b(tax court)\b", r"\b(tax (audit|assessment|liability))\b", r"\b(notice of deficiency)\b", r"\b(tax (penalty|levy|lien))\b", r"\b(innocent spouse)\b", r"\b(offer in compromise)\b", r"\b(collection due process)\b", ], )
def register_intellectual_property_complaint(): """Register keywords and patterns for intellectual property complaints.""" register_keywords( "complaint", [ # Patents "patent", "patent infringement", "utility patent", "design patent", "patent pending", "prior art", "obviousness", "enablement", "patent claim", "patent prosecution", # Trademarks "trademark", "service mark", "trade name", "trademark infringement", "likelihood of confusion", "trademark dilution", "famous mark", "generic mark", "descriptive mark", "suggestive mark", "arbitrary mark", "trade dress", "secondary meaning", # Copyrights "copyright", "copyright infringement", "fair use", "transformative use", "derivative work", "copyright registration", "dmca", "digital millennium copyright act", "takedown notice", "counter-notice", # Trade secrets "trade secret", "confidential information", "misappropriation", "utsa", "non-disclosure agreement", "nda", "non-compete agreement", # General IP "intellectual property", "ip", "licensing", "royalty", "license agreement", "infringement", "cease and desist", "damages", "injunctive relief", ], complaint_type="intellectual_property", )
register_legal_terms( "intellectual_property", [ r"\b(patent( infringement)?)\b", r"\b(trademark( infringement)?)\b", r"\b(copyright( infringement)?)\b", r"\b(trade secret)\b", r"\b(fair use)\b", r"\b(dmca)\b", r"\b(likelihood of confusion)\b", r"\b(trade dress)\b", ], )
def register_environmental_law_complaint(): """Register keywords and patterns for environmental law complaints.""" register_keywords( "complaint", [ # Environmental agencies "epa", "environmental protection agency", "clean air act", "clean water act", "safe drinking water act", # Environmental issues "pollution", "contamination", "air pollution", "water pollution", "soil contamination", "groundwater contamination", "toxic waste", "hazardous waste", "hazardous substance", "pollutant", # Environmental laws "cercla", "superfund", "rcra", "resource conservation and recovery act", "comprehensive environmental response", "nepa", "environmental impact statement", "endangered species act", "esa", # Environmental violations "environmental violation", "permit violation", "discharge violation", "emission violation", "npdes", "national pollutant discharge", # Environmental liability "environmental liability", "cleanup cost", "remediation", "natural resource damage", "citizen suit", "environmental enforcement", # Climate "greenhouse gas", "carbon emission", "climate change", "global warming", ], complaint_type="environmental_law", )
register_legal_terms( "environmental_law", [ r"\b(epa|environmental protection agency)\b", r"\b(clean (air|water) act)\b", r"\b(cercla|superfund)\b", r"\b(rcra)\b", r"\b(nepa)\b", r"\b(endangered species act)\b", r"\b((air|water) pollution)\b", r"\b((toxic|hazardous) waste)\b", r"\b(contamination|remediation)\b", ], )
def register_probate_complaint(): """Register keywords and patterns for probate and estate law complaints.""" register_keywords( "complaint", [ # Probate process "probate", "probate court", "probate proceeding", "estate administration", "estate proceeding", "surrogate court", "orphans court", # Parties "decedent", "deceased", "testator", "testatrix", "estate", "estate of", "probate estate", "executor", "executrix", "personal representative", "administrator", "administratrix", "beneficiary", "heir", "legatee", "devisee", "guardian", "conservator", "ward", "trustee", "trust beneficiary", "settlor", "grantor", # Documents "will", "last will and testament", "testament", "codicil", "holographic will", "nuncupative will", "living will", "advance directive", "trust", "living trust", "testamentary trust", "revocable trust", "irrevocable trust", "trust agreement", "trust instrument", "letters testamentary", "letters of administration", # Estate types "testate", "intestate", "intestacy", "partial intestacy", # Assets and property "estate asset", "probate asset", "non-probate asset", "real property", "personal property", "tangible property", "intangible property", "estate inventory", "asset appraisal", "estate account", "estate accounting", # Inheritance and distribution "inheritance", "inherit", "heir", "intestate succession", "statutory share", "elective share", "forced share", "distribution", "final distribution", "per stirpes", "per capita", "right of survivorship", "joint tenancy", "payable on death", "pod", "transfer on death", "tod", # Debts and taxes "estate debt", "estate claim", "creditor claim", "claim against estate", "notice to creditors", "estate tax", "inheritance tax", "death tax", "estate expenses", "administration expenses", # Guardianship and conservatorship "guardianship", "guardian of the person", "guardian of the estate", "guardian ad litem", "conservatorship", "conservator", "incapacitated person", "protected person", "ward", "minor", "adult guardianship", "guardianship proceeding", # Disputes and litigation "will contest", "challenge will", "contested will", "undue influence", "lack of capacity", "testamentary capacity", "sound mind", "fraud", "forgery", "duress", "coercion", "trust dispute", "trust litigation", "breach of fiduciary duty", "fiduciary duty", "removal of executor", "removal of trustee", "surcharge", "accounting dispute", "construction of will", "interpretation of will", # Trust types and issues "charitable trust", "special needs trust", "spendthrift trust", "discretionary trust", "marital trust", "bypass trust", "credit shelter trust", "qualified terminable interest property", "qtip trust", "trust modification", "trust termination", "trust reformation", "trust amendment", # Powers and authority "power of attorney", "durable power of attorney", "springing power of attorney", "healthcare power of attorney", "attorney in fact", "agent", # Estate planning "estate plan", "estate planning", "succession plan", "wealth transfer", "gift", "inter vivos gift", "gift causa mortis", # Marital property "community property", "separate property", "marital property", "quasi-community property", "surviving spouse", "widow", "widower", # Small estate procedures "small estate affidavit", "summary administration", "affidavit of heirship", "muniment of title", # Appeals and review "probate appeal", "estate litigation", "accounting review", "estate audit", ], complaint_type="probate", )
register_legal_terms( "probate", [ r"\b(probate( court| proceeding)?)\b", r"\b(estate (administration|proceeding))\b", r"\b(surrogate court|orphans court)\b", r"\b(executor|executrix|personal representative)\b", r"\b(administrator|administratrix)\b", r"\b((last )?will and testament|testament)\b", r"\b(codicil)\b", r"\b(living trust|testamentary trust)\b", r"\b(revocable trust|irrevocable trust)\b", r"\b(letters testamentary)\b", r"\b(letters of administration)\b", r"\b(testate|intestate|intestacy)\b", r"\b(beneficiary|heir|legatee|devisee)\b", r"\b(guardianship|conservatorship)\b", r"\b(guardian|conservator)\b", r"\b(will contest)\b", r"\b(undue influence)\b", r"\b(testamentary capacity)\b", r"\b(breach of fiduciary duty)\b", r"\b(estate (tax|debt|claim))\b", r"\b(inheritance tax)\b", r"\b(per stirpes|per capita)\b", r"\b(elective share|forced share)\b", r"\b(power of attorney)\b", r"\b(trust (dispute|litigation|modification|termination))\b", r"\b(charitable trust|special needs trust)\b", r"\b(small estate affidavit)\b", r"\b(summary administration)\b", ], )
def register_dei_complaint(): """ Register keywords and patterns for DEI (Diversity, Equity, and Inclusion) complaints.
This encompasses discrimination, harassment, and civil rights violations across multiple domains including housing, employment, and public accommodations. Integrates comprehensive DEI keywords from HACC repository for policy analysis. """ # Core DEI keywords from HACC's index_and_tag.py register_keywords( "complaint", [ # Core DEI terms "diversity", "diverse", "equity", "equitable", "inclusion", "inclusive", "dei", "deia", "deib", "deij", # Justice frameworks "racial justice", "social justice", "environmental justice", "justice-centered", "justice oriented", "anti-racist", "anti discrimination", # Community descriptors "marginalized", "minority", "minorities", "bipoc", "people of color", "underrepresented", "underrepresented groups", "underserved", "underserviced", "historically underrepresented", "marginalized communities", "socially disadvantaged", "economically disadvantaged", # Equity frameworks "equity lens", "equity framework", "equity initiatives", "equity plan", "cultural humility", "cultural responsiveness", "accessibility", "barrier reduction", "inclusive environment", # Discrimination types "discrimination", "discriminate", "discriminatory", "harassment", "hostile environment", "retaliation", "retaliate", "retaliatory", # Fair housing "fair housing", "housing discrimination", "reasonable accommodation", "reasonable modification", "familial status", "source of income", # Protected classes "protected class", "protected classes", "race", "racial", "color", "national origin", "nationality", "religion", "religious", "sex", "gender", "disability", "disabled", "handicap", "age", "elderly", "sexual orientation", "gender identity", # Legal impact "disparate impact", "disparate treatment", "intentional discrimination", "unintentional discrimination", "adverse impact", "adverse effect", # Housing specific "section 8", "housing choice voucher", "public housing", "affordable housing", "tenant", "landlord", "lease", "rental", "eviction", "housing authority", # Employment specific "employment discrimination", "workplace discrimination", "equal employment opportunity", "eeoc", "title vii", "ada", "adea", "fmla", # Civil rights "civil rights", "equal protection", "due process", "constitutional rights", "constitutional violation", # Complaint process "complainant", "respondent", "charging party", "aggrieved person", "complaint", "charge", # Community benefits "community benefit", "community benefits", "section 3", "equal opportunity", ], complaint_type="dei", )
# DEI proxy keywords from HACC (euphemisms and indirect references) register_keywords( "dei_proxy", [ "cultural competence", "cultural competency", "lived experience", "diversity statement", "safe space", "minority-only", "first-generation", "low-income targeting", "overcoming obstacles", "implicit bias", "unconscious bias", "affirmative action", ], complaint_type="dei", )
# Evidence-related keywords register_keywords( "evidence", [ "evidence", "proof", "documentation", "witness", "testimony", "statement", "document", "record", "file", "exhibit", "attachment", "appendix", "correspondence", "email", "letter", "notice", "communication", "photograph", "image", "video", "recording", "audio", "contract", "agreement", "lease", "policy", "procedure", "manual", "complaint form", "intake form", "medical record", "doctor note", "police report", "incident report", ], complaint_type="dei", )
# Legal authority keywords register_keywords( "legal", [ "statute", "law", "code", "regulation", "ordinance", "rule", "act", "u.s.c.", "c.f.r.", "federal register", "case law", "precedent", "holding", "opinion", "decision", "ruling", "court order", "judgment", "decree", "constitution", "constitutional", "amendment", "provision", "section", "subsection", "clause", "paragraph", "title", "chapter", "article", ], complaint_type="dei", )
# Binding/enforceable indicators register_keywords( "binding", [ "policy", "ordinance", "statewide", "model policy", "contract", "agreement", "standard", "required", "must", "shall", "mandatory", "applicable to", "applicability", "enforceable", "governing", "binding", "regulation", "rule", "directive", "compliance", "obligated", "stipulation", ], complaint_type="dei", )
# Severity/risk indicators register_keywords( "severity_high", [ "systemic", "pattern", "practice", "intentional", "willful", "deliberate", "egregious", "severe", "pervasive", "ongoing", "repeated", "continuous", "punitive damages", "injunctive relief", ], complaint_type="dei", )
register_keywords( "severity_medium", [ "violation", "breach", "failure", "inadequate", "insufficient", "disparate impact", "adverse effect", "compensatory damages", ], complaint_type="dei", )
register_keywords( "severity_low", [ "potential", "possible", "may", "unintentional", "inadvertent", "technical", "procedural", "correctable", "remediable", ], complaint_type="dei", )
# Applicability keywords - DEI context covers these domains register_keywords( "applicability_housing", [ "housing", "lease", "tenant", "landlord", "rental", "dwelling", "residence", "apartment", "unit", "eviction", "termination", "nonrenewal", "affordable", "public housing", "section 8", "housing authority", "housing choice voucher", "reasonable accommodation", "accessibility", ], complaint_type="dei", )
register_keywords( "applicability_employment", [ "employment", "workplace", "job", "work", "hire", "hiring", "recruit", "recruitment", "fire", "firing", "terminate", "termination", "promote", "promotion", "demote", "demotion", "employee", "employer", "supervisor", "wages", "salary", "compensation", "benefits", "fmla", "leave", "accommodation", ], complaint_type="dei", )
register_keywords( "applicability_public_accommodation", [ "public accommodation", "place of public accommodation", "service", "facility", "establishment", "access", "accessibility", "barrier", "restaurant", "hotel", "store", "shop", "theater", "stadium", "park", "transportation", "bus", "train", ], complaint_type="dei", )
register_keywords( "applicability_lending", [ "lending", "loan", "mortgage", "credit", "financing", "financial", "bank", "lender", "interest rate", "terms", "approval", "denial", "redlining", "appraisal", ], complaint_type="dei", )
register_keywords( "applicability_education", [ "education", "school", "university", "college", "student", "enrollment", "admission", "classroom", "teacher", "faculty", "curriculum", "program", "degree", "disability services", "accommodations", ], complaint_type="dei", )
register_keywords( "applicability_government_services", [ "government", "agency", "department", "public service", "benefits", "assistance", "program", "eligibility", "application", "permit", "license", "approval", ], complaint_type="dei", )
# Procurement and contracting (from HACC DEI research) register_keywords( "applicability_procurement", [ "procurement", "contract", "contracting", "vendor", "supplier", "bid", "bidding", "rfp", "request for proposal", "award", "purchase", "purchasing", "disadvantaged business enterprise", "dbe", "minority-owned business", "mbe", "women-owned business", "wbe", "mwesb", "esb", "socially disadvantaged", "economically disadvantaged", "small business", "certification", "subcontractor", "subcontracting", ], complaint_type="dei", )
# Training and development (from HACC index_and_tag.py) register_keywords( "applicability_training", [ "training", "workshop", "course", "curriculum", "education", "seminar", "professional development", "orientation", "onboarding", "certification", "cultural competency training", "implicit bias training", "diversity training", "sensitivity training", ], complaint_type="dei", )
# Community engagement (from HACC) register_keywords( "applicability_community_engagement", [ "community engagement", "public input", "stakeholder", "outreach", "consultation", "community participation", "public comment", "engagement plan", "community benefits", ], complaint_type="dei", )
# DEI-specific legal patterns # DEI-specific legal patterns (unique patterns only, avoiding duplicates) # Note: Common patterns like "discrimination", "fair housing", etc. are already # registered in other categories and will be loaded by LegalPatternExtractor register_legal_terms( "dei", [ # DEI Core Terms (unique to DEI taxonomy) r"\b(diversity|diverse)\b", r"\b(equity|equitable)\b", r"\b(inclusion|inclusive)\b", r"\b(underrepresented minorit(y|ies))\b", r"\b(underserved communit(y|ies))\b", r"\b(disadvantaged business enterprise|DBE)\b", r"\b(minority[- ]owned business|MBE)\b", r"\b(wom[ae]n[- ]owned business|WBE)\b", r"\b(MWESB|ESB)\b", r"\b(affirmative action)\b", r"\b(cultural competen(cy|ce))\b", r"\b(implicit bias|unconscious bias)\b", r"\b(racial equity)\b", r"\b(social equity)\b", r"\b(environmental justice)\b", r"\b(historically underrepresented)\b", r"\b(marginalized communit(y|ies))\b", r"\b(BIPOC)\b", r"\b(equal opportunity)\b", r"\b(Section 3)\b", r"\b(community benefit(s)?)\b", r"\b(socially disadvantaged)\b", r"\b(economically disadvantaged)\b", r"\b(racial justice)\b", r"\b(social justice)\b", r"\b(people of color)\b", r"\b(underserved|underserviced)\b", r"\b(equity (lens|framework|initiative))\b", r"\b(cultural (humility|responsiveness))\b", r"\b(justice[- ]centered|justice[- ]oriented)\b", r"\b(anti[- ]racist)\b", r"\b(lived experience)\b", r"\b(safe space)\b", r"\b(first[- ]generation)\b", ], )
def get_registered_types() -> List[str]: """ Get all registered complaint types.
Returns: List of complaint type names """ from .keywords import _global_registry
return _global_registry.get_complaint_types()
def get_complaint_type(complaint_type: str) -> Optional[Dict[str, Any]]: """Return basic metadata for a registered complaint type.
This is used by mediator hooks (e.g., LegalCorpusRAGHook) to retrieve type-scoped keyword categories.
Returns None when the type is unknown. """
if not isinstance(complaint_type, str): return None
name = complaint_type.strip() if not name: return None
from .keywords import _global_registry
if name not in _global_registry.get_complaint_types(): return None
categories = _global_registry.get_all_categories(name) primary_category = "complaint" if categories: primary_category = "complaint" if "complaint" in categories else categories[0]
return { "name": name, "category": primary_category, "categories": categories, }
# Register default types on module importregister_housing_complaint()register_employment_complaint()register_civil_rights_complaint()register_consumer_complaint()register_healthcare_complaint()register_free_speech_complaint()register_immigration_complaint()register_family_law_complaint()register_criminal_defense_complaint()register_tax_law_complaint()register_intellectual_property_complaint()register_environmental_law_complaint()register_probate_complaint() # Probate and estate lawregister_dei_complaint() # DEI taxonomy (formerly hacc_integration)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489"""Legal Pattern Extraction for Complaints
Extensible framework for extracting complaint-relevant legal provisions from text.Uses a registry pattern to allow adding new complaint types and legal term patterns.
This module includes default patterns for:- Fair housing law- Employment discrimination- Civil rights violations- Protected class references- Legal remedies and relief
New complaint types can be added by registering additional patterns."""
import refrom typing import List, Dict, Optional, Anyfrom datetime import datetimefrom .base import BaseLegalPatternExtractor
# Constants for complaint categorization# Minimum keyword matches required to categorize a complaint as a specific typeDEFAULT_KEYWORD_MATCH_THRESHOLD = 2# Minimum number of keywords a type must have before applying the threshold# (types with fewer keywords use threshold of 1 to avoid being too strict)MIN_KEYWORDS_FOR_THRESHOLD = 10
# Registry for legal term patterns by categoryLEGAL_TERMS_REGISTRY: Dict[str, List[str]] = {}
def register_legal_terms(category: str, patterns: List[str]) -> None: """ Register legal term patterns for a category.
Args: category: Category name (e.g., 'housing', 'employment', 'civil_rights') patterns: List of regex patterns """ if category not in LEGAL_TERMS_REGISTRY: LEGAL_TERMS_REGISTRY[category] = [] LEGAL_TERMS_REGISTRY[category].extend(patterns)
def get_legal_terms(category: Optional[str] = None) -> List[str]: """ Get legal term patterns for a category.
Args: category: Category name, or None for all patterns
Returns: List of regex patterns """ if category: return LEGAL_TERMS_REGISTRY.get(category, []) else: # Return all patterns from all categories all_patterns = [] for patterns in LEGAL_TERMS_REGISTRY.values(): all_patterns.extend(patterns) return all_patterns
# Default legal term patterns (maintained for backward compatibility)COMPLAINT_LEGAL_TERMS = [ # Fair Housing & Discrimination r"\b(fair housing)\b", r"\b(Fair Housing Act)\b", r"\b(FHA)\b", r"\b(discrimination)\b", r"\b(discriminate|discriminatory)\b", r"\b(harassment)\b", r"\b(retaliation|retaliate)\b", r"\b(hostile environment)\b", # Reasonable Accommodation r"\b(reasonable accommodation)\b", r"\b(reasonable modification)\b", r"\b(disability accommodation)\b", r"\b(auxiliary aids?)\b", # Protected Classes r"\b(protected class(es)?)\b", r"\b(familial status)\b", r"\b(disability|disabled)\b", r"\b(race|racial)\b", r"\b(color)\b", r"\b(national origin)\b", r"\b(religion|religious)\b", r"\b(sex|gender)\b", r"\b(sexual orientation)\b", r"\b(gender identity)\b", r"\b(source of income)\b", r"\b(marital status)\b", # Legal Impact r"\b(disparate (impact|treatment))\b", r"\b(intentional discrimination)\b", r"\b(unintentional discrimination)\b", r"\b(discriminatory effect)\b", r"\b(adverse (impact|effect))\b", # Housing Specific r"\b(Section 8)\b", r"\b(Housing Choice Voucher)\b", r"\b(public housing)\b", r"\b(affordable housing)\b", r"\b(tenant|tenancy)\b", r"\b(landlord)\b", r"\b(lease|rental agreement)\b", r"\b(eviction)\b", r"\b(housing authority)\b", # Employment Specific r"\b(Title VII)\b", r"\b(ADA)\b", r"\b(Americans with Disabilities Act)\b", r"\b(ADEA)\b", r"\b(Age Discrimination in Employment Act)\b", r"\b(FMLA)\b", r"\b(Family and Medical Leave Act)\b", r"\b(EEOC)\b", r"\b(Equal Employment Opportunity)\b", # Federal Law Citations r"\b(42 U\.S\.C\.)\b", r"\b(29 U\.S\.C\.)\b", r"\b(C\.F\.R\.)\b", r"\b(Federal Register)\b", # Remedies & Relief r"\b(damages)\b", r"\b(compensatory damages)\b", r"\b(punitive damages)\b", r"\b(injunctive relief)\b", r"\b(declaratory relief)\b", r"\b(attorney('s)? fees)\b", r"\b(equitable relief)\b", r"\b(monetary relief)\b", # Civil Rights r"\b(civil rights)\b", r"\b(equal protection)\b", r"\b(due process)\b", r"\b(constitutional (right|violation))\b", # Complaint-Specific Terms r"\b(complainant)\b", r"\b(respondent)\b", r"\b(charging party)\b", r"\b(aggrieved person)\b", r"\b(prima facie case)\b", r"\b(burden of proof)\b", r"\b(preponderance of evidence)\b",]
# Register default patterns in categoriesregister_legal_terms( "housing", [ r"\b(fair housing)\b", r"\b(Fair Housing Act)\b", r"\b(FHA)\b", r"\b(Section 8)\b", r"\b(Housing Choice Voucher)\b", r"\b(public housing)\b", r"\b(affordable housing)\b", r"\b(tenant|tenancy)\b", r"\b(landlord)\b", r"\b(lease|rental agreement)\b", r"\b(eviction)\b", r"\b(housing authority)\b", ],)
register_legal_terms( "employment", [ r"\b(Title VII)\b", r"\b(ADA)\b", r"\b(Americans with Disabilities Act)\b", r"\b(ADEA)\b", r"\b(Age Discrimination in Employment Act)\b", r"\b(FMLA)\b", r"\b(Family and Medical Leave Act)\b", r"\b(EEOC)\b", r"\b(Equal Employment Opportunity)\b", ],)
register_legal_terms( "discrimination", [ r"\b(discrimination)\b", r"\b(discriminate|discriminatory)\b", r"\b(harassment)\b", r"\b(retaliation|retaliate)\b", r"\b(hostile environment)\b", r"\b(disparate (impact|treatment))\b", r"\b(intentional discrimination)\b", r"\b(unintentional discrimination)\b", r"\b(discriminatory effect)\b", r"\b(adverse (impact|effect))\b", ],)
register_legal_terms( "protected_classes", [ r"\b(protected class(es)?)\b", r"\b(familial status)\b", r"\b(disability|disabled)\b", r"\b(race|racial)\b", r"\b(color)\b", r"\b(national origin)\b", r"\b(religion|religious)\b", r"\b(sex|gender)\b", r"\b(sexual orientation)\b", r"\b(gender identity)\b", r"\b(source of income)\b", r"\b(marital status)\b", ],)
register_legal_terms( "accommodations", [ r"\b(reasonable accommodation)\b", r"\b(reasonable modification)\b", r"\b(disability accommodation)\b", r"\b(auxiliary aids?)\b", ],)
register_legal_terms( "remedies", [ r"\b(damages)\b", r"\b(compensatory damages)\b", r"\b(punitive damages)\b", r"\b(injunctive relief)\b", r"\b(declaratory relief)\b", r"\b(attorney('s)? fees)\b", r"\b(equitable relief)\b", r"\b(monetary relief)\b", ],)
register_legal_terms( "civil_rights", [ r"\b(civil rights)\b", r"\b(equal protection)\b", r"\b(due process)\b", r"\b(constitutional (right|violation))\b", ],)
register_legal_terms( "federal_law", [ r"\b(42 U\.S\.C\.)\b", r"\b(29 U\.S\.C\.)\b", r"\b(C\.F\.R\.)\b", r"\b(Federal Register)\b", ],)
class LegalPatternExtractor(BaseLegalPatternExtractor): """ Extensible legal pattern extractor for complaints.
This class extracts legal provisions using regex patterns organized by category. New complaint types can be added by registering additional patterns using register_legal_terms().
Example: >>> # Use default patterns >>> extractor = LegalPatternExtractor() >>> result = extractor.extract_provisions(document_text)
>>> # Add custom patterns for consumer protection >>> register_legal_terms('consumer', [r'\b(consumer protection)\b']) >>> extractor = LegalPatternExtractor(categories=['consumer', 'civil_rights']) """
def __init__( self, categories: Optional[List[str]] = None, custom_patterns: Optional[List[str]] = None ): """ Initialize the legal pattern extractor.
Args: categories: List of pattern categories to use (None = all registered) custom_patterns: Optional additional regex patterns to include """ # Get patterns from specified categories or all if None if categories: patterns = [] for category in categories: patterns.extend(get_legal_terms(category)) else: patterns = get_legal_terms() # All patterns
# Add backwards compatibility with COMPLAINT_LEGAL_TERMS if not patterns: patterns = COMPLAINT_LEGAL_TERMS
self.patterns = [re.compile(p, re.IGNORECASE) for p in patterns]
if custom_patterns: self.patterns.extend([re.compile(p, re.IGNORECASE) for p in custom_patterns])
def extract_provisions(self, text: str, context_chars: int = 200) -> Dict[str, Any]: """ Extract legal provisions with context from text.
Args: text: Text to analyze context_chars: Number of characters to include before/after match
Returns: Dictionary containing: - provisions: List of found provisions with context - terms_found: Set of unique legal terms found - citation_count: Number of legal citations found - timestamp: When analysis was performed """ provisions = [] terms_found = set()
for pattern in self.patterns: for match in pattern.finditer(text): # Extract context around the match start = max(0, match.start() - context_chars) end = min(len(text), match.end() + context_chars) context = text[start:end]
# Clean up context (remove extra whitespace) context = " ".join(context.split())
term = match.group(0) terms_found.add(term.lower())
provisions.append( { "term": term, "context": context, "position": match.start(), "pattern": pattern.pattern, } )
# Sort by position in document provisions.sort(key=lambda x: x["position"])
return { "provisions": provisions, "terms_found": list(terms_found), "provision_count": len(provisions), "unique_terms": len(terms_found), "timestamp": datetime.now().isoformat(), }
def extract_citations(self, text: str) -> List[Dict[str, str]]: """ Extract legal citations (e.g., 42 U.S.C. § 3604).
Args: text: Text to analyze
Returns: List of found citations with metadata """ citation_patterns = [ # Federal statutes (e.g., 42 U.S.C. § 3604) (r"\b\d+\s+U\.S\.C\.\s+§\s*\d+[a-z]?(?:\(\w+\))?", "federal_statute"), # Code of Federal Regulations (e.g., 24 C.F.R. § 100.70) (r"\b\d+\s+C\.F\.R\.\s+§\s*\d+\.\d+", "cfr"), # State statutes (e.g., Cal. Civ. Code § 51) (r"\b[A-Z][a-z]+\.\s+[A-Z][a-z]+\.\s+Code\s+§\s*\d+", "state_statute"), # Case citations (simplified) (r"\b\d+\s+F\.\s*(?:2d|3d|Supp\.)?\s+\d+", "federal_case"), ]
citations = [] for pattern, citation_type in citation_patterns: regex = re.compile(pattern, re.IGNORECASE) for match in regex.finditer(text): citations.append( {"citation": match.group(0), "type": citation_type, "position": match.start()} )
return citations
def categorize_complaint_type(self, text: str) -> List[str]: """ Categorize the complaint based on legal terms found.
Uses keyword matching with configurable thresholds to identify applicable complaint categories. Requires multiple keyword matches to avoid false positives.
Args: text: Text to analyze
Returns: List of applicable complaint categories """ # Import here to avoid circular dependency issues during module initialization from .keywords import get_type_specific_keywords, _global_registry
text_lower = text.lower() categories = []
# Check each registered complaint type complaint_types = _global_registry.get_complaint_types()
for complaint_type in complaint_types: # Get type-specific keywords (excluding global keywords) type_keywords = get_type_specific_keywords("complaint", complaint_type)
# Check if any type-specific keywords appear in text # Use a threshold to avoid false positives matches = sum(1 for kw in type_keywords if kw.lower() in text_lower)
# If at least threshold keywords match, include this type # Use lower threshold for types with fewer keywords to avoid being too strict threshold = ( DEFAULT_KEYWORD_MATCH_THRESHOLD if len(type_keywords) > MIN_KEYWORDS_FOR_THRESHOLD else 1 ) if matches >= threshold: categories.append(complaint_type)
# Legacy categorization for backward compatibility # Disability if ( "disability" in text_lower or "ada" in text_lower or "reasonable accommodation" in text_lower ): if "disability" not in categories: categories.append("disability")
# Discrimination type if "discrimination" in text_lower or "discriminate" in text_lower: if "discrimination" not in categories: categories.append("discrimination")
# Harassment if "harassment" in text_lower or "hostile environment" in text_lower: if "harassment" not in categories: categories.append("harassment")
# Retaliation if "retaliation" in text_lower or "retaliate" in text_lower: if "retaliation" not in categories: categories.append("retaliation")
return categories or ["general"]
def find_protected_classes(self, text: str) -> List[str]: """ Identify protected classes mentioned in the text.
Args: text: Text to analyze
Returns: List of protected classes found """ protected_classes = { "race": ["race", "racial"], "color": ["color"], "national_origin": ["national origin", "nationality"], "religion": ["religion", "religious", "creed"], "sex": ["sex", "gender"], "familial_status": ["familial status", "family status", "children"], "disability": ["disability", "disabled", "handicap"], "age": ["age", "elderly", "senior"], "sexual_orientation": ["sexual orientation", "lgbt", "gay", "lesbian"], "gender_identity": ["gender identity", "transgender"], "source_of_income": ["source of income", "section 8", "voucher"], }
text_lower = text.lower() found_classes = []
for class_name, keywords in protected_classes.items(): if any(keyword in text_lower for keyword in keywords): found_classes.append(class_name)
return found_classes1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495{ "complaint_type": "civil_rights", "category": "civil_rights", "description": "Decision tree for civil rights complaints", "root_questions": [ "q1", "q2", "q3" ], "questions": { "q1": { "id": "q1", "question": "Who violated your civil rights?", "field_name": "violating_party", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "police", "government", "official", "agency" ] }, "q2": { "id": "q2", "question": "What right was violated?", "field_name": "protected_right", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "speech", "assembly", "religion", "privacy", "due process" ] }, "q3": { "id": "q3", "question": "What type of violation occurred?", "field_name": "violation_type", "required": true, "depends_on": [ "protected_right" ], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "Please describe the incident in detail.", "field_name": "incident_description", "required": true, "depends_on": [ "violation_type" ], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "When did this occur?", "field_name": "date_of_incident", "required": true, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] }, "q6": { "id": "q6", "question": "What damages did you suffer?", "field_name": "damages", "required": false, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] } }, "required_fields": [ "protected_right", "date_of_incident", "violating_party", "incident_description", "violation_type" ], "optional_fields": [ "damages" ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697{ "complaint_type": "consumer", "category": "consumer", "description": "Decision tree for consumer complaints", "root_questions": [ "q1", "q2", "q3" ], "questions": { "q1": { "id": "q1", "question": "What is the name of the business?", "field_name": "business_name", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "What product or service did you purchase?", "field_name": "product_or_service", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q3": { "id": "q3", "question": "What type of problem occurred?", "field_name": "fraud_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "fraud", "misrepresentation", "defective", "breach" ] }, "q4": { "id": "q4", "question": "Please describe the issue in detail.", "field_name": "issue_description", "required": true, "depends_on": [ "fraud_type" ], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "When did you make the purchase?", "field_name": "date_of_purchase", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q6": { "id": "q6", "question": "How much money did you lose?", "field_name": "amount_lost", "required": false, "depends_on": [ "issue_description" ], "follow_ups": [], "keywords": [] }, "q7": { "id": "q7", "question": "Have you tried to resolve this with the business?", "field_name": "attempts_to_resolve", "required": false, "depends_on": [ "issue_description" ], "follow_ups": [], "keywords": [] } }, "required_fields": [ "issue_description", "date_of_purchase", "business_name", "product_or_service", "fraud_type" ], "optional_fields": [ "amount_lost", "attempts_to_resolve" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "complaint_type": "criminal_defense", "category": "criminal", "description": "Decision tree for criminal defense complaints", "root_questions": [ "q1", "q2" ], "questions": { "q1": { "id": "q1", "question": "Which law enforcement agency was involved?", "field_name": "law_enforcement_agency", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "What type of rights violation occurred?", "field_name": "violation_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "search", "seizure", "miranda", "counsel" ] }, "q3": { "id": "q3", "question": "When were you arrested?", "field_name": "date_of_arrest", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "What charges were filed?", "field_name": "charges", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "Are there any issues with evidence?", "field_name": "evidence_issues", "required": false, "depends_on": [ "violation_type" ], "follow_ups": [], "keywords": [] } }, "required_fields": [ "law_enforcement_agency", "violation_type" ], "optional_fields": [ "date_of_arrest", "evidence_issues", "charges" ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455{ "complaint_type": "dei", "category": "employment", "description": "Generic decision tree for dei complaints", "root_questions": [ "q1", "q2" ], "questions": { "q1": { "id": "q1", "question": "Who is the other party involved?", "field_name": "party_name", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "Please describe the issue.", "field_name": "issue_description", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q3": { "id": "q3", "question": "When did this occur?", "field_name": "date_of_incident", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "What damages did you suffer?", "field_name": "damages", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] } }, "required_fields": [ "issue_description", "date_of_incident", "party_name" ], "optional_fields": [ "damages" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129{ "complaint_type": "employment", "category": "employment", "description": "Decision tree for employment complaints", "root_questions": [ "q1", "q2", "q3" ], "questions": { "q1": { "id": "q1", "question": "What is the name of your employer?", "field_name": "employer_name", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "What was/is your position or job title?", "field_name": "position", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q3": { "id": "q3", "question": "What type of employment issue are you experiencing?", "field_name": "issue_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "discrimination", "termination", "harassment", "wage" ] }, "q4": { "id": "q4", "question": "Can you describe what happened in detail?", "field_name": "incident_description", "required": true, "depends_on": [ "issue_type" ], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "When did this occur?", "field_name": "date_of_incident", "required": true, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] }, "q6": { "id": "q6", "question": "Did you report this to HR or management?", "field_name": "hr_complaints", "required": false, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] }, "q7": { "id": "q7", "question": "Were there any witnesses?", "field_name": "witnesses", "required": false, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] }, "q8": { "id": "q8", "question": "If this involves discrimination, what protected class are you a member of?", "field_name": "protected_class", "required": false, "depends_on": [ "issue_type" ], "follow_ups": [], "keywords": [ "race", "age", "gender", "disability", "religion" ] }, "q9": { "id": "q9", "question": "How long were you employed there?", "field_name": "years_employed", "required": false, "depends_on": [ "employer_name" ], "follow_ups": [], "keywords": [] } }, "required_fields": [ "issue_type", "date_of_incident", "incident_description", "position", "employer_name" ], "optional_fields": [ "witnesses", "hr_complaints", "protected_class", "years_employed" ]}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071{ "complaint_type": "environmental_law", "category": "environmental", "description": "Decision tree for environmental law complaints", "root_questions": [ "q1", "q2" ], "questions": { "q1": { "id": "q1", "question": "Who is violating environmental law?", "field_name": "violating_party", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "What type of violation is occurring?", "field_name": "violation_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "pollution", "contamination", "hazardous waste" ] }, "q3": { "id": "q3", "question": "Where is the violation occurring?", "field_name": "location", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "When did you discover the violation?", "field_name": "date_discovered", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "What is the environmental impact?", "field_name": "environmental_impact", "required": false, "depends_on": [ "violation_type" ], "follow_ups": [], "keywords": [] } }, "required_fields": [ "violating_party", "date_discovered", "violation_type" ], "optional_fields": [ "environmental_impact", "location" ]}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{ "complaint_type": "family_law", "category": "family_law", "description": "Decision tree for family law complaints", "root_questions": [ "q1", "q2" ], "questions": { "q1": { "id": "q1", "question": "Who is the other party involved?", "field_name": "other_party", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "What is the nature of the issue?", "field_name": "issue_description", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "custody", "support", "visitation", "divorce" ] }, "q3": { "id": "q3", "question": "If children are involved, please list their names and ages.", "field_name": "children", "required": false, "depends_on": [ "issue_description" ], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "What is the current custody or support arrangement?", "field_name": "custody_arrangement", "required": false, "depends_on": [ "children" ], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "Are there any prior court orders in this matter?", "field_name": "prior_orders", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] } }, "required_fields": [ "other_party", "issue_description" ], "optional_fields": [ "children", "prior_orders", "custody_arrangement" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "complaint_type": "free_speech", "category": "civil_rights", "description": "Decision tree for free speech complaints", "root_questions": [ "q1", "q3" ], "questions": { "q1": { "id": "q1", "question": "Who censored or suppressed your speech?", "field_name": "censoring_party", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "platform", "government", "school", "employer" ] }, "q2": { "id": "q2", "question": "What platform or venue was involved?", "field_name": "platform_or_venue", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q3": { "id": "q3", "question": "What content was censored?", "field_name": "content_censored", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "When did the censorship occur?", "field_name": "date_of_censorship", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "What reason was given for the censorship, if any?", "field_name": "reason_given", "required": false, "depends_on": [ "date_of_censorship" ], "follow_ups": [], "keywords": [] } }, "required_fields": [ "censoring_party", "content_censored", "date_of_censorship" ], "optional_fields": [ "platform_or_venue", "reason_given" ]}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283{ "complaint_type": "healthcare", "category": "healthcare", "description": "Decision tree for healthcare complaints", "root_questions": [ "q1", "q3" ], "questions": { "q1": { "id": "q1", "question": "Who was the healthcare provider?", "field_name": "healthcare_provider", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "What facility did this occur at?", "field_name": "facility_name", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q3": { "id": "q3", "question": "What type of negligence or malpractice occurred?", "field_name": "type_of_negligence", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "misdiagnosis", "surgical error", "medication error" ] }, "q4": { "id": "q4", "question": "Please describe what happened.", "field_name": "incident_description", "required": true, "depends_on": [ "type_of_negligence" ], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "When did this occur?", "field_name": "date_of_incident", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q6": { "id": "q6", "question": "What injuries or harm resulted?", "field_name": "injuries_sustained", "required": false, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] } }, "required_fields": [ "healthcare_provider", "date_of_incident", "incident_description", "type_of_negligence" ], "optional_fields": [ "facility_name", "injuries_sustained" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141{ "complaint_type": "housing", "category": "housing", "description": "Decision tree for housing complaints", "root_questions": [ "q1", "q2", "q3" ], "questions": { "q1": { "id": "q1", "question": "Who is the landlord or property owner?", "field_name": "landlord_name", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "landlord", "owner", "property manager" ] }, "q2": { "id": "q2", "question": "What is the address of the property?", "field_name": "property_address", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "address", "property", "location" ] }, "q3": { "id": "q3", "question": "What type of issue are you experiencing?", "field_name": "issue_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "discrimination", "eviction", "harassment", "repair" ] }, "q4": { "id": "q4", "question": "Can you describe the specific incident or action that occurred?", "field_name": "incident_description", "required": true, "depends_on": [ "issue_type" ], "follow_ups": [], "keywords": [ "affordable housing", "eviction", "fair housing", "familial status", "housing authority", "housing choice voucher", "housing discrimination", "landlord", "lease", "public housing", "reasonable accommodation", "reasonable modification", "rental", "section 8", "source of income", "tenant" ] }, "q5": { "id": "q5", "question": "When did this incident occur?", "field_name": "date_of_incident", "required": true, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] }, "q6": { "id": "q6", "question": "Were there any witnesses to this incident?", "field_name": "witnesses", "required": false, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] }, "q7": { "id": "q7", "question": "Have you filed any prior complaints about this issue?", "field_name": "prior_complaints", "required": false, "depends_on": [ "incident_description" ], "follow_ups": [], "keywords": [] }, "q8": { "id": "q8", "question": "If this involves discrimination, what protected class are you a member of?", "field_name": "protected_class", "required": false, "depends_on": [ "issue_type" ], "follow_ups": [], "keywords": [ "race", "gender", "disability", "religion" ] } }, "required_fields": [ "issue_type", "date_of_incident", "incident_description", "landlord_name", "property_address" ], "optional_fields": [ "witnesses", "protected_class", "prior_complaints" ]}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970{ "complaint_type": "immigration", "category": "immigration", "description": "Decision tree for immigration complaints", "root_questions": [ "q1", "q2" ], "questions": { "q1": { "id": "q1", "question": "Which government agency is involved?", "field_name": "government_agency", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "uscis", "ice", "cbp", "immigration" ] }, "q2": { "id": "q2", "question": "What type of violation occurred?", "field_name": "violation_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q3": { "id": "q3", "question": "What is your current immigration status?", "field_name": "immigration_status", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "When did this occur?", "field_name": "date_of_incident", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "What relief or remedy are you seeking?", "field_name": "relief_sought", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] } }, "required_fields": [ "government_agency", "date_of_incident", "violation_type" ], "optional_fields": [ "immigration_status", "relief_sought" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172{ "complaint_type": "intellectual_property", "category": "intellectual_property", "description": "Decision tree for intellectual property complaints", "root_questions": [ "q1", "q2" ], "questions": { "q1": { "id": "q1", "question": "Who is infringing on your intellectual property?", "field_name": "infringing_party", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q2": { "id": "q2", "question": "What type of IP is involved?", "field_name": "ip_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "patent", "trademark", "copyright", "trade secret" ] }, "q3": { "id": "q3", "question": "What is the registration number, if applicable?", "field_name": "registration_number", "required": false, "depends_on": [ "ip_type" ], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "When did you discover the infringement?", "field_name": "date_of_infringement", "required": true, "depends_on": [], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "What are your estimated damages?", "field_name": "damages_estimate", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] } }, "required_fields": [ "date_of_infringement", "ip_type", "infringing_party" ], "optional_fields": [ "damages_estimate", "registration_number" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116{ "complaint_type": "probate", "category": "probate", "description": "Decision tree for probate and estate law complaints", "root_questions": [ "q1", "q2", "q3" ], "questions": { "q1": { "id": "q1", "question": "What is the name of the decedent (deceased person)?", "field_name": "decedent_name", "required": true, "depends_on": [], "follow_ups": ["q4"], "keywords": ["decedent", "deceased", "testator"] }, "q2": { "id": "q2", "question": "What is the date of death?", "field_name": "date_of_death", "required": true, "depends_on": [], "follow_ups": [], "keywords": ["death", "died", "deceased"] }, "q3": { "id": "q3", "question": "What type of probate issue are you experiencing? (e.g., will contest, executor dispute, trust dispute, guardianship, estate administration)", "field_name": "probate_issue_type", "required": true, "depends_on": [], "follow_ups": ["q5", "q6"], "keywords": ["will contest", "executor", "trustee", "guardianship", "conservatorship", "estate administration"] }, "q4": { "id": "q4", "question": "In which county and state did the decedent reside at the time of death?", "field_name": "decedent_residence", "required": true, "depends_on": ["q1"], "follow_ups": [], "keywords": ["residence", "domicile", "county", "state"] }, "q5": { "id": "q5", "question": "Did the decedent leave a will or trust?", "field_name": "will_or_trust_exists", "required": true, "depends_on": ["q3"], "follow_ups": ["q7"], "keywords": ["will", "testament", "trust", "testate", "intestate"] }, "q6": { "id": "q6", "question": "Who is the executor, administrator, or trustee involved?", "field_name": "fiduciary_name", "required": false, "depends_on": ["q3"], "follow_ups": [], "keywords": ["executor", "administrator", "trustee", "personal representative"] }, "q7": { "id": "q7", "question": "What are the specific issues or disputes? (e.g., undue influence, lack of capacity, breach of fiduciary duty, improper distribution)", "field_name": "specific_issues", "required": true, "depends_on": ["q5"], "follow_ups": ["q8"], "keywords": ["undue influence", "capacity", "fraud", "breach", "fiduciary duty", "distribution"] }, "q8": { "id": "q8", "question": "What are the estate assets involved? (e.g., real property, bank accounts, investments, personal property)", "field_name": "estate_assets", "required": false, "depends_on": ["q7"], "follow_ups": [], "keywords": ["assets", "property", "real estate", "bank account", "investment"] }, "q9": { "id": "q9", "question": "What is your relationship to the decedent? (e.g., spouse, child, heir, beneficiary, creditor)", "field_name": "relationship_to_decedent", "required": true, "depends_on": [], "follow_ups": [], "keywords": ["spouse", "heir", "beneficiary", "child", "family", "creditor"] }, "q10": { "id": "q10", "question": "Has probate been opened, and if so, in which court?", "field_name": "probate_court_info", "required": false, "depends_on": [], "follow_ups": [], "keywords": ["probate court", "case number", "proceeding", "filed"] } }, "required_fields": [ "decedent_name", "date_of_death", "probate_issue_type", "decedent_residence", "will_or_trust_exists", "specific_issues", "relationship_to_decedent" ], "optional_fields": [ "fiduciary_name", "estate_assets", "probate_court_info" ]}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374{ "complaint_type": "tax_law", "category": "tax", "description": "Decision tree for tax law complaints", "root_questions": [ "q1", "q2" ], "questions": { "q1": { "id": "q1", "question": "Which tax authority is involved?", "field_name": "tax_authority", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "irs", "state", "local" ] }, "q2": { "id": "q2", "question": "What type of dispute is this?", "field_name": "dispute_type", "required": true, "depends_on": [], "follow_ups": [], "keywords": [ "assessment", "collection", "refund", "audit" ] }, "q3": { "id": "q3", "question": "What tax year is involved?", "field_name": "tax_year", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q4": { "id": "q4", "question": "What is the amount in dispute?", "field_name": "amount_in_dispute", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] }, "q5": { "id": "q5", "question": "Have you filed any prior appeals?", "field_name": "prior_appeals", "required": false, "depends_on": [], "follow_ups": [], "keywords": [] } }, "required_fields": [ "tax_authority", "dispute_type" ], "optional_fields": [ "tax_year", "prior_appeals", "amount_in_dispute" ]}12345678910111213141516171819"""Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
__version__ = "0.5.0"# Layout matches SkillCenter HF release / publicus-ir family; schema string is domain-specific.SCHEMA_VERSION = "country-laws-ir-graphrag/v1"LAYOUT_FAMILY = "skillcenter-huggingface-release/v3"ENTRY_IDENTITY_SCHEMA = "country-laws-entry/v1"LAW_IDENTITY_SCHEMA = "country-laws-law/v1"FACET_IDENTITY_SCHEMA = "country-laws-facet/v1"EDGE_IDENTITY_SCHEMA = "country-laws-edge/v1"MAX_ROWS_PER_FILE = 4096TARGET_ORG = "justicedao"
# CID payload: UTF-8 bytes of json.dumps(obj, sort_keys=True, ensure_ascii=False,# separators=(",", ":")) hashed as CIDv1 codec=raw (0x55) hash=sha2-256 (0x12)# multibase base32 (`bafkrei...`). Same payload -> same CID.CID_CODEC = "raw"CID_HASH = "sha2-256"CID_MULTIBASE = "base32"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463"""python -m country_laws_ir {build,query,batch,catalog,normalize,package-raw}"""
from __future__ import annotations
import argparseimport jsonimport sysfrom pathlib import Path
def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(prog="country_laws_ir") sub = ap.add_subparsers(dest="cmd", required=True)
p_build = sub.add_parser("build") p_build.add_argument("--source-repo", "--source", dest="source", default="malta", help="Hub dataset id (endomorphosis/ipfs_<slug>_laws), country slug, or local pack dir") p_build.add_argument("--out", default=None) p_build.add_argument( "--device", default="cuda", help="Embedding device (cuda by default, like US Code / Open US Law; falls back to cpu)", ) p_build.add_argument("--neighbor-k", type=int, default=8) p_build.add_argument("--skip-vectors", action="store_true") p_build.add_argument("--upload", action="store_true", help="Publish the packaged release to justicedao/ipfs_<slug>_laws_ir (requires HF_TOKEN)") p_build.add_argument("--mode", default="auto", choices=["auto", "full", "delta"], help="auto skips unchanged Hub revisions and reuses embeddings by entry_cid") p_build.add_argument("--force", action="store_true", help="Ignore source fingerprint skip and reuse caches") p_build.add_argument("--prior-dir", default=None, help="Prior GraphRAG release to delta against")
p_batch = sub.add_parser("batch") p_batch.add_argument("--slugs", nargs="*", default=None) p_batch.add_argument("--upload", action="store_true") p_batch.add_argument("--no-skip-done", action="store_true", help="Force a full rebuild of every country (ignore unchanged fingerprints)") p_batch.add_argument("--mode", default="auto", choices=["auto", "full", "delta"]) p_batch.add_argument("--skip-vectors", action="store_true")
p_q = sub.add_parser("query") p_q.add_argument("--local-dir", required=True) p_q.add_argument("rest", nargs=argparse.REMAINDER)
p_norm = sub.add_parser("normalize") p_norm.add_argument("--source-repo", "--source", dest="source", default="malta") p_norm.add_argument("--out", default=None, help="Optional JSON report path")
p_cat = sub.add_parser("catalog") p_cat.add_argument("--refresh", action="store_true", help="List public endomorphosis/ipfs_*_laws datasets and persist new slugs")
p_cov = sub.add_parser("coverage", help="Compare endomorphosis sources vs justicedao GraphRAG releases") p_cov.add_argument("--gaps", action="store_true", help="Scan Hub for missing, stale, and incomplete IR (downloads manifests)") p_cov.add_argument("--workers", type=int, default=8)
p_re = sub.add_parser( "reindex", help="Scan endomorphosis vs justicedao and incrementally rebuild stale/missing IR", ) p_re.add_argument("--upload", action="store_true", help="Publish rebuilt packs to justicedao (requires HF_TOKEN)") p_re.add_argument("--slugs", nargs="*", default=None) p_re.add_argument("--limit", type=int, default=None) p_re.add_argument("--max-corpus-rows", type=int, default=20000, help="Skip IR larger than this many rows (0 = no cap)") p_re.add_argument("--skip-vectors", action="store_true") p_re.add_argument("--workers", type=int, default=2, help="Ceiling for adaptive workers. Memory, disk, and free GPU memory shrink it and back off when the host is full") p_re.add_argument("--device", default="cuda") p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"]) p_re.add_argument("--all", action="store_true", help="Process every indexable catalog country (not only Hub gaps)") p_re.add_argument("--force", action="store_true", help="Rebuild even when the source SHA matches, and re-encode every row") p_re.add_argument("--renormalize", action="store_true", help="Rerun normalization, then reindex only packs whose entry rows changed")
p_ver = sub.add_parser( "verify", help="Normalize a country pack and run admission verifiers (no GraphRAG)", ) p_ver.add_argument("--source-repo", "--source", dest="source", default=None) p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country") p_ver.add_argument("--limit", type=int, default=None)
p_loop = sub.add_parser( "normalize-loop", help="scan residuals, improve the normalizer script with llm_router, or apply that script", ) p_loop.add_argument("stage", choices=["scan", "improve", "apply", "run"]) p_loop.add_argument("--cache", default=None) p_loop.add_argument("--out", default=None) p_loop.add_argument("--reports", default=None, help="Per-country residual JSON directory") p_loop.add_argument("--slug", default=None, help="One country, for a subprocess") p_loop.add_argument("--workers", type=int, default=None, help="Country processes (default: one per CPU)") p_loop.add_argument("--limit", type=int, default=None) p_loop.add_argument("--passes", type=int, default=40, help="Improve batches sent to llm_router") p_loop.add_argument("--force", action="store_true", help="Redo finished countries and retry unresolved lines") p_loop.add_argument("--progress", default=None, help="JSONL file appended as each country or improve pass finishes")
p_raw = sub.add_parser("package-raw") p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir") p_raw.add_argument("--instruments-dir", default=None, help="Collector JSON directory (default: $LEGAL_CORPORA_ROOT/<iso-or-slug>/instruments)") p_raw.add_argument("--iso", default=None, help="Collector ISO directory name if different from slug") p_raw.add_argument("--out", default=None, help="Local pack directory (laws.parquet + pack_meta.json)") p_raw.add_argument("--source-dataset", default=None, help="Raw Hub id (default endomorphosis/ipfs_<slug>_laws)") p_raw.add_argument("--prior-pack", default=None, help="Existing parquet pack to merge into")
p_pack = sub.add_parser( "pack-shards", help="Concatenate local data/laws-*.parquet into data/laws.parquet. Does not upload.", ) p_pack.add_argument("--source", required=True) p_pack.add_argument("--out", required=True) p_pack.add_argument("--slug", required=True) p_pack.add_argument("--revision", required=True) p_pack.add_argument("--source-dataset", default=None)
args = ap.parse_args(argv) if args.cmd == "build": from .build import build_country
result = build_country( args.source, out=Path(args.out) if args.out else None, upload=args.upload, device=args.device, neighbor_k=args.neighbor_k, skip_vectors=args.skip_vectors, mode=args.mode, force=args.force, prior_dir=Path(args.prior_dir) if args.prior_dir else None, ) print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str)) print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str)) return 0 if args.cmd == "batch": from .build import batch
results = batch( slugs=args.slugs, upload=args.upload, skip_done=not args.no_skip_done, mode=args.mode, skip_vectors=args.skip_vectors, ) print(json.dumps( [{"country": r["country"], "out": r["out"], "skipped": r.get("skipped", False)} for r in results], indent=2, )) return 0 if args.cmd == "query": from .query import main as qmain
argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"] return qmain(argv2) if args.cmd == "normalize": from .build import CACHE, REPORTS from .catalog import get_country from .normalize import build_corpus, load_source
country = get_country(args.source) local = country.get("local_source_dir") laws, articles, source_meta = load_source(local or country["repo"], CACHE) corpus, report = build_corpus(laws, articles, source_meta) out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json" out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2)) return 0 if args.cmd == "catalog": from .catalog import all_countries, refresh_from_hub
countries = refresh_from_hub() if args.refresh else all_countries() print(json.dumps( {"n": len(countries), "indexable": len([c for c in countries if c.get("indexable")]), "countries": countries}, indent=2, )) return 0 if args.cmd == "coverage": from .coverage import coverage_report, gap_report
report = gap_report(workers=args.workers) if args.gaps else coverage_report() print(json.dumps(report, indent=2, default=str)) return 0 if args.cmd == "reindex": from .build import reindex_from_gaps
cap = None if args.all or int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows) results = reindex_from_gaps( upload=args.upload, slugs=args.slugs or None, limit=args.limit, max_corpus_rows=cap, skip_vectors=args.skip_vectors, workers=args.workers, mode=args.mode, force=args.force, all_indexable=args.all, device=args.device, renormalize=args.renormalize, ) print(json.dumps( [ { "country": r.get("country"), "skipped": r.get("skipped", False), "out": r.get("out"), "hub": (r.get("hub") or {}).get("url") if isinstance(r.get("hub"), dict) else r.get("hub"), "error": r.get("error"), "kind": (r.get("incremental") or {}).get("kind"), "n_added": ((r.get("incremental") or {}).get("delta") or {}).get("n_added"), "n_unchanged": ((r.get("incremental") or {}).get("delta") or {}).get("n_unchanged"), } for r in results ], indent=2, default=str, )) return 1 if any(r.get("error") for r in results) else 0 if args.cmd == "verify": from .catalog import indexable_countries from .verify import verify_source
slugs = [] if args.all: slugs = [c["slug"] for c in indexable_countries()] if args.limit: slugs = slugs[: int(args.limit)] elif args.source: slugs = [args.source] else: print(json.dumps({"error": "pass --source or --all"}, indent=2)) return 2 rows = [] failed = 0 for slug in slugs: try: row = verify_source(slug) except Exception as exc: row = {"slug": slug, "error": str(exc), "verification": {"admitted": False}} rows.append(row) if not (row.get("verification") or {}).get("admitted", False): failed += 1 from collections import Counter
units = Counter(str(r.get("unit") or "") for r in rows) mismatch = [] latin_blocked = [] for r in rows: for chk in (r.get("verification") or {}).get("checks") or []: if chk.get("id") != "heading_language": continue ev = chk.get("evidence") or {} if chk.get("severity") == "fail" and not chk.get("passed"): latin_blocked.append(r.get("slug")) if "review samples" in str(chk.get("message") or ""): mismatch.append( { "slug": r.get("slug"), "document_language": ev.get("document_language"), "heading_language": ev.get("heading_language"), } ) print( json.dumps( { "n": len(rows), "n_failed": failed, "by_unit": dict(units), "heading_mismatch": mismatch, "latin_split_blocked": latin_blocked, "countries": rows, }, indent=2, default=str, ) ) return 1 if failed else 0 if args.cmd == "normalize-loop": from .build import CACHE, ROOT from .normalize_loop import ( _apply_job, _scan_job, append_progress, apply_done, cache_packs, improve_from_reports, load_generate_text, run_parallel, scan_done, worker_count, )
cache = Path(args.cache) if args.cache else CACHE reports = Path(args.reports) if args.reports else ROOT / "reports" / "residuals" out = Path(args.out) if args.out else ROOT / "llm-normalized" packs = cache_packs(cache, slug=args.slug) if args.limit: packs = packs[: int(args.limit)] workers = worker_count(args.workers) progress = Path(args.progress) if args.progress else ROOT / "reports" / f"normalize_{args.stage}.jsonl"
def _pending(stage: str) -> tuple[list[tuple[str, str, str]], list[str]]: jobs: list[tuple[str, str, str]] = [] skipped: list[str] = [] for slug, path in packs: done = scan_done(reports, slug) if stage == "scan" else apply_done(out, slug) if done and not args.force: skipped.append(slug) continue dest = reports if stage == "scan" else out jobs.append((slug, str(path), str(dest))) return jobs, skipped
def _run(stage: str, worker) -> list[dict]: jobs, skipped = _pending(stage) total = len(jobs) + len(skipped) done = len(skipped) print(json.dumps({ "event": "start", "stage": stage, "workers": workers, "done": done, "pending": len(jobs), "total": total, "progress": str(progress), }), flush=True) state = {"done": done}
def _on_done(row: dict) -> None: state["done"] += 1 print(json.dumps({ "event": stage, "done": state["done"], "total": total, **row, }), flush=True)
return run_parallel(jobs, worker, workers, progress_path=progress, on_done=_on_done)
if args.stage == "scan": rows = _run("scan", _scan_job) failed = [row for row in rows if row.get("error")] print(json.dumps({"stage": "scan", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2)) return 1 if failed else 0 if args.stage == "apply": rows = _run("apply", _apply_job) failed = [row for row in rows if row.get("error")] print(json.dumps({"stage": "apply", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2)) return 1 if failed else 0 def _on_pass(row: dict) -> None: print(json.dumps({"event": "improve", **row}, ensure_ascii=False), flush=True) append_progress(progress, {"event": "improve", **row})
def _improve(): print(json.dumps({ "event": "start", "stage": "improve", "passes": args.passes, "reports": str(reports), }), flush=True) try: generate = load_generate_text() except Exception as exc: print(json.dumps({"error": f"llm_router unavailable: {exc}"}), flush=True) return None return improve_from_reports( reports, generate, max_passes=args.passes, on_pass=_on_pass, reset_unresolved=bool(args.force), )
if args.stage == "improve": result = _improve() if result is None: return 1 print(json.dumps({"stage": "improve", **result}, indent=2, ensure_ascii=False)) return 0 # run scans, then improves the script. Applying the script to every # pack is the separate ``apply`` stage. scan_rows = _run("scan", _scan_job) failed = [row for row in scan_rows if row.get("error")] if failed: print(json.dumps({"stage": "run", "n_scanned": len(scan_rows), "n_failed": len(failed)}, indent=2)) return 1 improved = _improve() if improved is None: return 1 print(json.dumps( {"stage": "run", "workers": workers, "improve": improved, "n_scanned": len(scan_rows)}, indent=2, ensure_ascii=False, default=str, )) return 0 if args.cmd == "package-raw": from .build import RELEASES from .raw_package import default_instruments_dir, package_instruments
instruments = ( Path(args.instruments_dir) if args.instruments_dir else default_instruments_dir(args.iso or args.slug) ) out = Path(args.out) if args.out else RELEASES / "raw-packs" / args.slug meta = package_instruments( instruments_dir=instruments, out=out, slug=args.slug, source_dataset=args.source_dataset, prior_pack=Path(args.prior_pack) if args.prior_pack else None, ) print(json.dumps(meta, indent=2, default=str)) return 0 if args.cmd == "pack-shards": from ipfs_datasets_py.processors.legal_scrapers.world_law.export_norm import ( ExportRefused, choose_export_command, ) from ipfs_datasets_py.processors.legal_scrapers.world_law.load_sharded_laws import ( load_sharded_laws, )
source = Path(args.source) siblings = [str(path.relative_to(source)) for path in source.rglob("*") if path.is_file()] try: command = choose_export_command(args.slug, siblings) except ExportRefused as exc: print(json.dumps({"error": str(exc), "slug": args.slug})) return 2 if command != "load_sharded_laws": print(json.dumps({ "error": "pack-shards only accepts sharded laws parquet", "command": command, "slug": args.slug, })) return 2 dataset = args.source_dataset or f"endomorphosis/ipfs_{args.slug}_laws" try: written = load_sharded_laws( source, Path(args.out), slug=args.slug, source_dataset=dataset, source_revision=args.revision, ) except (OSError, ValueError) as exc: print(json.dumps({"error": str(exc), "slug": args.slug})) return 2 print(json.dumps(written, indent=2)) return 0 return 1
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702"""Admit endomorphosis country-law rows that can fill a national gap.
``world_national_law`` stays thin for some countries while``endomorphosis/ipfs_<slug>_laws`` already holds the statute text. A fillmay copy only a row that is still a queryable law after cleaning. Metadatacards, website pages, newsletters, chrome, chapter captions, label tables,municipal and other sub-national corpora, and the excluded national harvestsare refused. A sharednumeric document id is not a citation. One leading article or section headingis copied onto the locator so the row can be queried. This module does notdownload, does not upload, and does not rewrite statute text."""
from __future__ import annotations
import jsonimport refrom collections import Counterfrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Iterable, Mapping
from ipfs_datasets_py.processors.legal_data.iso_slug_crosswalk import ( national_slug, resolve_jurisdiction,)from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.catalog import ( EXCLUDED_SLUGS,)from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.structure import ( normalize_legal_text, segment_exclusive,)from ipfs_datasets_py.processors.legal_scrapers.world_law.atomic_corpus import ( expand_legal_record, render_atomic,)from ipfs_datasets_py.processors.legal_scrapers.world_law.schema import ( LEGAL_RECORD_FIELDS,)from ipfs_datasets_py.processors.legal_scrapers.world_law.textutil import ( sha256_text,)from ipfs_datasets_py.processors.legal_scrapers.world_law.document_role import ( classify_document_role,)
THIN_NATIONAL_DOCS = 10FILL_NORMALIZER = "country-source-admit/v1"_MAX_FILL_BYTES = 64 * 1024 * 1024_NON_NATIONAL_MARKERS = ("_municipal", "_provincial", "_governorate", "_local")_FILL_COLUMNS = ( "id", "cid", "entry_cid", "title", "instrument_title", "text", "body", "language", "jurisdiction", "country", "source_url", "article_number", "official_identifier", "metadata_json", "doc_type", "source_official", "source_policy", "source_revision",)_LOCATORS = ("title", "chapter", "part", "article", "section")_STRUCTURAL = frozenset({"title", "chapter", "part", "article", "section"})_PROVISION_NUMBER = re.compile( r"(?i)^(?:art(?:icle)?\.?|neni|nen|član|clan|section|sec\.?|paragraph|§|มาตรา)?\s*" r"([0-9]{1,5}|[IVXLCDM]{1,8})\.?$")_CAPTION_HEADING = re.compile( r"(?i)^(cap[ií]tulo|chapter|titre|title|t[ií]tulo|secci[oó]n|section|part(?:ie)?|teil)\b")_SENTENCE_END = re.compile(r"[.!?。؟](?:\s|$)")_LEADING_ARTICLE = re.compile( r"(?i)^(?:article|art\.?|neni|section|sec\.?)\s*([0-9]{1,5})\b")_DROP_POLICIES = frozenset({ "archived_robots_disallowed", "noarchive_meta", "noindex_meta", "robots_unreachable",})_NOTICE_RE = re.compile( r"(?i)(\bnewsletter\b|\bblog\b|press release|communiqu[eé]|" r"\bnews item\b|\bnotice board\b|^lista\s+\d)")_CITATION_MARK = re.compile( r"(?i)\b(?:nr|no|act|law|ordinance|gazette|loi|legge|gesetz|decree|code)\b")_NOTICE_TYPES = frozenset({ "newsletter", "blog", "press", "press_release", "notice",})_STATUTORY = re.compile( r"(?i)\b(?:shall|hereby|s'applique|gilt|enacted|pursuant)\b|يجب|بموجب")_MIN_PROVISION = 40
@dataclass(frozen=True)class SourceAdmission: admitted: bool reason: str records: tuple[dict[str, object], ...]
def admit_source_law( row: Mapping[str, object], *, source_dataset: str, source_revision: str,) -> SourceAdmission: """Return queryable legal-record atoms, or a refusal with no text."""
slug = _slug(source_dataset) if slug in EXCLUDED_SLUGS or _jurisdiction_slug(row) in EXCLUDED_SLUGS: return _refuse("excluded") if _non_national(slug): return _refuse("not_national") policy = row.get("source_policy") if isinstance(policy, str) and policy in _DROP_POLICIES: return _refuse("source_policy") if row.get("source_official") is False: return _refuse("unofficial") raw_text = row.get("text") if isinstance(row.get("text"), str) else row.get("body") cleaned = normalize_legal_text(raw_text if isinstance(raw_text, str) else "") if not cleaned: return _refuse("empty") meta = _metadata(row.get("metadata_json")) document_type = str(meta.get("document_type") or row.get("doc_type") or "") title = _string(row.get("title")) if _NOTICE_RE.search(title) or document_type.strip().casefold() in _NOTICE_TYPES: return _refuse("notice") language = _string(row.get("language")) source_url = _string(row.get("source_url")) labeled = { "title": title, "language": language, "source_url": source_url, "doc_type": document_type, } raw_role, _raw_reason = classify_document_role( {**labeled, "text": raw_text if isinstance(raw_text, str) else cleaned} ) if raw_role != "law": return _refuse(raw_role) role, _reason = classify_document_role({**labeled, "text": cleaned}) if role != "law": return _refuse(role) if not _provision_prose(cleaned): return _refuse("not_queryable") citation = _record_citation(row) jurisdiction = _jurisdiction_code(row) record = { "entry_cid": _string(row.get("id")) or _string(row.get("cid")), "title": title, "text": cleaned, "language": language, "jurisdiction": jurisdiction, "citation": citation or None, "source_url": source_url or None, "instrument_type": "statute", "source_repo": source_dataset, "source_revision": source_revision, "provenance": {}, } atoms = tuple(expand_legal_record(record)) kept = tuple(atom for atom in atoms if _law_atom(atom)) if not kept: return _refuse("not_queryable") stamped = tuple(_with_leading_heading(atom, language) for atom in kept) if not _queryable(stamped, cleaned, citation): return _refuse("not_queryable") return SourceAdmission(True, "law", stamped)
def fill_source_rows( rows: Iterable[Mapping[str, object]], *, source_dataset: str, source_revision: str,) -> dict[str, object]: """Admit a local batch. Refused rows contribute a reason and no text."""
admitted: list[dict[str, object]] = [] reasons: Counter[str] = Counter() for row in rows: decision = admit_source_law( row, source_dataset=source_dataset, source_revision=source_revision, ) reasons[decision.reason] += 1 if decision.admitted: admitted.extend(decision.records) return { "source_dataset": source_dataset, "source_revision": source_revision, "admitted": admitted, "reasons": dict(reasons), }
def national_gap_plan(card_docs: Mapping[str, int]) -> list[dict[str, object]]: """Name the country dataset that can fill a thin national card.
A card with more than 10 documents is not a gap. Belgium, Portugal, Lithuania, and Ghana are listed as skipped. Nothing is downloaded. """
plan: list[dict[str, object]] = [] for code, docs in sorted(card_docs.items()): if not isinstance(docs, int): continue token = str(code or "").strip().upper() slug = national_slug(token) if token else None if docs > THIN_NATIONAL_DOCS or not slug: continue source = f"endomorphosis/ipfs_{slug}_laws" if slug in EXCLUDED_SLUGS: plan.append( { "code": token, "slug": slug, "source_dataset": source, "card_docs": docs, "action": "skip", "reason": "excluded", } ) continue plan.append( { "code": token, "slug": slug, "source_dataset": source, "card_docs": docs, "action": "fill", "reason": "thin_docs", } ) return plan
def fill_country_parquet( source_path: Path | str, dest_dir: Path | str, *, source_dataset: str, source_revision: str,) -> dict[str, object]: """Write admitted legal-record rows from one local country parquet.
The file must already be on disk. A municipal corpus, an excluded national harvest, or a file over 64 MiB is refused before any row is read. Refused rows are counted and their text is not written. """
return fill_country_corpus( [source_path], dest_dir, source_dataset=source_dataset, source_revision=source_revision, flush_atoms=10**12, )
def fill_country_corpus( source_paths: Iterable[Path | str], dest_dir: Path | str, *, source_dataset: str, source_revision: str, flush_atoms: int = 8192,) -> dict[str, object]: """Admit every local corpus part into queryable legal-record shards.
Files must already be on disk. An excluded harvest, a municipal or other sub-national corpus, a missing file, or a part over 64 MiB is refused before any row is read. Atoms are written in numbered parts so a whole country is not held in memory. Refused rows are counted and their text is not written. This function does not download or upload. """
slug = _slug(source_dataset) if slug in EXCLUDED_SLUGS: raise ValueError("excluded") if _non_national(slug): raise ValueError("not_national") if not _is_sha(source_revision): raise ValueError("source_revision") if flush_atoms < 1: raise ValueError("flush_atoms") sources = [Path(path) for path in source_paths] if not sources: raise ValueError("source") total_bytes = 0 for source in sources: if not source.is_file(): raise ValueError("source") size = source.stat().st_size if size > _MAX_FILL_BYTES: raise ValueError("source") total_bytes += size destination = Path(dest_dir) / slug destination.mkdir(parents=True, exist_ok=True) stale_report = destination / "report.json" if stale_report.exists(): stale_report.unlink() for stale in destination.glob("part-*.parquet"): stale.unlink() reasons: Counter[str] = Counter() revisions: set[str] = set() rows_read = 0 located = 0 atoms_written = 0 pending: list[dict[str, str | None]] = [] written: list[str] = []
def flush() -> None: nonlocal pending if not pending: return written.append(_write_fill_part(destination, len(written), pending)) pending = []
for source in sources: for revision, decision in _iter_source_decisions( source, source_dataset=source_dataset, source_revision=source_revision, ): rows_read += 1 if isinstance(revision, str): revisions.add(revision) reasons[decision.reason] += 1 if not decision.admitted: continue for atom in decision.records: pending.append(_encode_fill_atom(atom)) provenance = atom.get("provenance") if isinstance(provenance, dict) and _located(provenance): located += 1 atoms_written += 1 if len(pending) >= flush_atoms: flush() flush() report = { "source_dataset": source_dataset, "source_revision": source_revision, "source_path": str(sources[0]), "source_files": [path.name for path in sources], "source_bytes": total_bytes, "slug": slug, "rows_read": rows_read, "atoms_written": atoms_written, "atoms_with_locator": located, "revisions": sorted(revisions), "reasons": dict(reasons), "coverage": "snapshot" if atoms_written else "not_published", "corpus_complete": True, "normalizer_version": FILL_NORMALIZER, "files": written, } (destination / "report.json").write_text( json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) return report
def _fill_row(row: Mapping[str, object]) -> dict[str, object]: title = row.get("title") if isinstance(row.get("title"), str) else row.get("instrument_title") text = row.get("text") if isinstance(row.get("text"), str) else row.get("body") entry = row.get("id") if isinstance(row.get("id"), str) else row.get("entry_cid") if not isinstance(entry, str): entry = row.get("cid") return { "id": entry if isinstance(entry, str) else "", "title": title if isinstance(title, str) else "", "text": text if isinstance(text, str) else "", "language": row.get("language") if isinstance(row.get("language"), str) else "", "jurisdiction": row.get("jurisdiction") if isinstance(row.get("jurisdiction"), str) else "", "country": row.get("country") if isinstance(row.get("country"), str) else "", "source_url": row.get("source_url") if isinstance(row.get("source_url"), str) else "", "article_number": row.get("article_number") if isinstance(row.get("article_number"), str) else "", "official_identifier": row.get("official_identifier") if isinstance(row.get("official_identifier"), str) else "", "metadata_json": row.get("metadata_json") if isinstance(row.get("metadata_json"), str) else "", "doc_type": row.get("doc_type") if isinstance(row.get("doc_type"), str) else "", "source_official": row.get("source_official"), "source_policy": row.get("source_policy"), }
def _encode_fill_atom(atom: Mapping[str, object]) -> dict[str, str | None]: provenance = atom.get("provenance") copied = dict(provenance) if isinstance(provenance, dict) else {} record: dict[str, object] = {field: None for field in LEGAL_RECORD_FIELDS} record.update( { "jurisdiction": atom.get("jurisdiction"), "admin_level": "country", "instrument_type": "statute", "citation": atom.get("citation"), "title": atom.get("title"), "text": atom.get("text"), "language": atom.get("language"), "source_url": atom.get("source_url"), "content_sha256": atom.get("content_sha256") or sha256_text(atom.get("text") if isinstance(atom.get("text"), str) else None), "scraper_id": "country_laws_ir", "normalizer_version": FILL_NORMALIZER, "source_repo": atom.get("source_repo"), "source_revision": atom.get("source_revision"), "entry_cid": atom.get("entry_cid"), "provenance": copied, } ) copied["jsonld"] = render_atomic(record, "jsonld") encoded: dict[str, str | None] = {} for field in LEGAL_RECORD_FIELDS: value = record.get(field) if field == "provenance": encoded[field] = json.dumps(copied, sort_keys=True, ensure_ascii=False) elif value is None: encoded[field] = None else: encoded[field] = str(value) return encoded
def _fill_schema(): import pyarrow as pa
return pa.schema([pa.field(name, pa.string()) for name in LEGAL_RECORD_FIELDS])
def _is_sha(value: object) -> bool: return ( isinstance(value, str) and len(value) == 40 and all(char in "0123456789abcdef" for char in value) )
def _refuse(reason: str) -> SourceAdmission: return SourceAdmission(False, reason, ())
def _iter_source_decisions( source: Path, *, source_dataset: str, source_revision: str,): import pyarrow.parquet as pq
columns = [name for name in _FILL_COLUMNS if name in pq.read_schema(source).names] parquet = pq.ParquetFile(source) for batch in parquet.iter_batches(batch_size=256, columns=columns): for row in batch.to_pylist(): row_revision = row.get("source_revision") revision = row_revision if _is_sha(row_revision) else source_revision decision = admit_source_law( _fill_row(row), source_dataset=source_dataset, source_revision=revision, ) yield revision, decision
def _write_fill_part( destination: Path, part_index: int, encoded: list[dict[str, str | None]],) -> str: import pyarrow as pa import pyarrow.parquet as pq
part = destination / f"part-{part_index:06d}.parquet" table = pa.Table.from_pylist(encoded, schema=_fill_schema()) pq.write_table(table, part, compression="zstd") return str(part)
def _non_national(slug: str) -> bool: return (not slug) or any(marker in slug for marker in _NON_NATIONAL_MARKERS)
def _slug(source_dataset: str) -> str: name = str(source_dataset or "").strip() if name.startswith("endomorphosis/"): name = name.split("/", 1)[1] if name.startswith("ipfs_") and name.endswith("_laws"): return name[len("ipfs_") : -len("_laws")] return ""
def _jurisdiction_slug(row: Mapping[str, object]) -> str: resolved = resolve_jurisdiction(_string(row.get("jurisdiction")) or _string(row.get("country"))) if resolved is None or resolved.admin_level != "country" or not resolved.slug: return "" return resolved.slug
def _jurisdiction_code(row: Mapping[str, object]) -> str | None: resolved = resolve_jurisdiction(_string(row.get("jurisdiction")) or _string(row.get("country"))) if resolved is None or resolved.admin_level != "country": return None return resolved.code
def _metadata(value: object) -> dict[str, object]: if isinstance(value, dict): return value if isinstance(value, str) and value.strip().startswith("{"): try: loaded = json.loads(value) except json.JSONDecodeError: return {} if isinstance(loaded, dict): return loaded return {}
def _string(value: object) -> str: if isinstance(value, str): return value.strip() return ""
def _provision_number(value: object) -> str: """Article, section, or paragraph number. A chapter label is not one."""
match = _PROVISION_NUMBER.match(_string(value)) if match is None: return "" return match.group(1)
def _record_citation(row: Mapping[str, object]) -> str: """Instrument citation, or the provision number when the id is only digits.
Country rows store a shared document number in ``official_identifier``. That number is the same on every article, so it is not a provision citation. """
official = _string(row.get("official_identifier")) number = _provision_number(row.get("article_number")) title = _string(row.get("title")) if ( official and official != title and not official.isdigit() and re.search(r"\d", official) and _CITATION_MARK.search(official) ): return official return number
def _provision_prose(text: str) -> bool: """True when the cleaned row is a provision, not a caption or a label table."""
if _caption_shell(text): return False if _STATUTORY.search(text): return True for raw in text.splitlines(): line = raw.strip() if not line or _CAPTION_HEADING.match(line): continue words = re.findall(r"[^\W\d_]{2,}", line) if len(words) >= 8 and _SENTENCE_END.search(line): return True letters = re.findall(r"[^\W\d_]", line) if len(letters) >= 40: return True return False
def _caption_shell(text: str) -> bool: """A chapter or title line plus a label, with no provision sentence."""
lines = [line.strip() for line in text.splitlines() if line.strip()] if not lines or len(lines) > 4 or not _CAPTION_HEADING.match(lines[0]): return False if _STATUTORY.search(text): return False for line in lines: words = re.findall(r"[^\W\d_]{2,}", line) if len(words) >= 8 and _SENTENCE_END.search(line): return False return True
def _with_leading_heading(atom: dict[str, object], language: str) -> dict[str, object]: """Copy one leading article or section number onto the unsplit atom."""
provenance = atom.get("provenance") text = atom.get("text") if not isinstance(provenance, dict) or not isinstance(text, str): return atom if _located(provenance): return atom leading = _LEADING_ARTICLE.match(text.lstrip()) if leading is not None: number = leading.group(1) provenance["article"] = number provenance.setdefault("section", number) provenance.setdefault("hierarchy_path", f"Article {number}") statute = provenance.get("statute") if not isinstance(statute, str) or not statute.strip(): provenance["statute"] = number return atom units = [ unit for unit in segment_exclusive(text, language=language) if unit.kind in _STRUCTURAL and unit.number and len(unit.body.strip()) >= 16 ] if not units: return atom numbers = {unit.number for unit in units} if len(numbers) != 1: return atom lead = min(units, key=lambda unit: unit.char_start) if lead.char_start > 80: return atom number = lead.number kind = "article" if any(unit.kind == "article" for unit in units) else lead.kind if kind == "article": provenance["article"] = number provenance.setdefault("section", number) elif kind == "section": provenance.setdefault("section", number) elif kind in {"chapter", "part", "title"}: provenance.setdefault(kind, number) else: return atom if lead.hierarchy_path: provenance.setdefault("hierarchy_path", lead.hierarchy_path) statute = provenance.get("statute") if not isinstance(statute, str) or not statute.strip(): provenance["statute"] = number return atom
def _located(provenance: Mapping[str, object]) -> bool: for key in _LOCATORS: value = provenance.get(key) if isinstance(value, str) and value.strip(): return True return False
def _law_atom(atom: Mapping[str, object]) -> bool: text = atom.get("text") provenance = atom.get("provenance") if not isinstance(text, str) or not text.strip(): return False if not isinstance(provenance, dict): return False return provenance.get("document_role") == "law"
def _queryable( atoms: tuple[dict[str, object], ...], cleaned: str, citation: str,) -> bool: if any(_has_locator(atom) for atom in atoms): return True if len(cleaned) >= _MIN_PROVISION and _STATUTORY.search(cleaned): return True return bool(citation) and len(cleaned) >= _MIN_PROVISION
def _has_locator(atom: Mapping[str, object]) -> bool: provenance = atom.get("provenance") if not isinstance(provenance, dict): return False for key in _LOCATORS: value = provenance.get(key) if isinstance(value, str) and value.strip(): return True path = provenance.get("hierarchy_path") return isinstance(path, str) and any( label in path for label in ("Title ", "Chapter ", "Part ", "Article ", "Section ") )1234567891011121314151617181920212223242526272829303132333435363738"""Hugging Face auth helpers.
Default reads stay anonymous. Gap scans and JusticeDAO uploads may use theoperator token from the Hugging Face cache file or the environment. The tokenis never logged."""
from __future__ import annotations
import osfrom pathlib import Path
def configure_hf() -> None: """Do not implicitly pick up ambient tokens for anonymous public reads.""" os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
def public_token() -> bool: """huggingface_hub `token=False` means anonymous (do not pick up env tokens).""" return False
def operator_token() -> str | bool: """Return a token for authenticated Hub reads/writes, or False if none.""" for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"): value = (os.environ.get(key) or "").strip() if value: return value path = Path.home() / ".cache" / "huggingface" / "token" if path.is_file(): try: value = path.read_text(encoding="utf-8").strip() except OSError: return False if value: return value return False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227"""Okapi BM25 (k1=1.2, b=0.75, title_weight=5, body_weight=1) + posting shards."""
from __future__ import annotations
import mathfrom collections import defaultdictfrom typing import Any, Iterable
import numpy as npimport pandas as pd
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSIONfrom .tokenize import tokenize
K1 = 1.2B = 0.75TITLE_WEIGHT = 5.0BODY_WEIGHT = 1.0POSTING_ROWS_PER_RECORD = 4096TERMS_PER_SHARD = 4096MAX_QUERY_TERMS = 64
def _idf(n_docs: int, df: int) -> float: # rank_bm25 Okapi: ln((N - df + 0.5) / (df + 0.5) + 1) return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
def build_index(corpus: pd.DataFrame) -> dict[str, Any]: n = len(corpus) titles = corpus["title"].fillna("").astype(str).tolist() bodies = corpus["body"].fillna("").astype(str).tolist() title_toks = [tokenize(t) for t in titles] body_toks = [tokenize(t) for t in bodies]
title_len = np.array([len(t) for t in title_toks], dtype=np.int32) body_len = np.array([len(t) for t in body_toks], dtype=np.int32) doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64) avgdl = float(doc_len.mean()) if n else 0.0
# term -> {doc: [title_tf, body_tf]} postings: dict[str, dict[int, list[int]]] = defaultdict(dict) for i, (tt, bt) in enumerate(zip(title_toks, body_toks)): tf_t: dict[str, int] = defaultdict(int) tf_b: dict[str, int] = defaultdict(int) for tok in tt: tf_t[tok] += 1 for tok in bt: tf_b[tok] += 1 for tok in set(tf_t) | set(tf_b): postings[tok][i] = [int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0))]
terms = sorted(postings) idf = {t: _idf(n, len(postings[t])) for t in terms}
doc_rows = [] for i, row in corpus.iterrows(): idx = int(row["document_index"]) doc_rows.append( { "entry_cid": row["entry_cid"], "document_index": idx, "law_cid": row.get("law_cid", ""), "instrument_id": row.get("instrument_id", row.get("law_id", "")), "law_id": row.get("law_id", row.get("instrument_id", "")), "source_id": row["source_id"], "title": row["title"], "instrument_title": row.get("instrument_title", ""), "article_number": row.get("article_number", ""), "article_title": row.get("article_title", ""), "record_type": row["record_type"], "language": row.get("language", ""), "jurisdiction": row.get("jurisdiction", ""), "title_length": int(title_len[idx]), "body_length": int(body_len[idx]), "document_length": int(round(doc_len[idx])), "schema_version": SCHEMA_VERSION, } ) documents = pd.DataFrame(doc_rows).sort_values("document_index").reset_index(drop=True)
posting_rows = [] for term in terms: items = sorted(postings[term].items()) chunks = [ items[i : i + POSTING_ROWS_PER_RECORD] for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD) ] n_chunks = len(chunks) dfreq = len(items) cfreq = sum(v[0] + v[1] for _, v in items) for cidx, chunk in enumerate(chunks): posting_rows.append( { "term": term, "document_indices": [d for d, _ in chunk], "title_frequencies": [v[0] for _, v in chunk], "body_frequencies": [v[1] for _, v in chunk], "tfs": [TITLE_WEIGHT * v[0] + BODY_WEIGHT * v[1] for _, v in chunk], "lengths": [int(round(doc_len[d])) for d, _ in chunk], "document_lengths": [int(round(doc_len[d])) for d, _ in chunk], "document_frequency": int(dfreq), "corpus_frequency": int(cfreq), "idf": float(idf[term]), "posting_chunk_index": int(cidx), "posting_chunk_count": int(n_chunks), "schema_version": SCHEMA_VERSION, } ) postings_df = pd.DataFrame(posting_rows)
stats = { "k1": K1, "b": B, "title_weight": TITLE_WEIGHT, "body_weight": BODY_WEIGHT, "average_document_length": avgdl, "tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1", "max_query_terms": MAX_QUERY_TERMS, "posting_rows_per_record": POSTING_ROWS_PER_RECORD, "terms_per_shard": TERMS_PER_SHARD, "n_docs": n, "n_terms": len(terms), "n_posting_rows": int(len(postings_df)), "n_postings": int(sum(len(postings[t]) for t in terms)), } return { "documents": documents, "postings": postings_df, "postings_map": postings, "idf": idf, "doc_len": doc_len, "avgdl": avgdl, "title_toks": title_toks, "body_toks": body_toks, "stats": stats, }
def _tf_score(tf: float, dl: float, avgdl: float) -> float: denom = tf + K1 * (1.0 - B + B * (dl / avgdl if avgdl else 0.0)) if denom == 0: return 0.0 return (tf * (K1 + 1.0)) / denom
def score_query( query: str, index: dict[str, Any], top_k: int = 10,) -> list[tuple[int, float]]: q_terms = tokenize(query)[:MAX_QUERY_TERMS] if not q_terms: return [] postings = index["postings_map"] idf = index["idf"] doc_len = index["doc_len"] avgdl = index["avgdl"] or 1.0 scores: dict[int, float] = defaultdict(float) for term in q_terms: plist = postings.get(term) if not plist: continue w = idf.get(term, 0.0) for doc, (ttf, btf) in plist.items(): tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf scores[doc] += w * _tf_score(tf, float(doc_len[doc]), avgdl) ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True) return ranked[:top_k]
def bm25_neighbors(index: dict[str, Any], k: int = 8) -> list[list[tuple[int, float, list[str]]]]: """Top-k BM25 neighbors from title tokens (body prefix only if title is empty).
Each neighbor is (document_index, score, matched_terms). """ import heapq
n = index["stats"]["n_docs"] postings = index["postings_map"] idf = index["idf"] doc_len = index["doc_len"] avgdl = index["avgdl"] or 1.0 title_toks = index["title_toks"] body_toks = index["body_toks"] df_cap = max(256, min(1500, n // 40 or 1)) term_docs: dict[str, np.ndarray] = {} term_pay: dict[str, np.ndarray] = {} for term, plist in postings.items(): if len(plist) > df_cap: continue docs = np.fromiter(plist.keys(), dtype=np.int32, count=len(plist)) tfs = np.empty(len(plist), dtype=np.float64) for j, (doc, (ttf, btf)) in enumerate(plist.items()): tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf tfs[j] = _tf_score(tf, float(doc_len[doc]), avgdl) term_docs[term] = docs term_pay[term] = tfs * float(idf.get(term, 0.0))
neighbors: list[list[tuple[int, float, list[str]]]] = [[] for _ in range(n)] step = 20000 if n >= 40000 else max(n, 1) for i in range(n): if i and i % step == 0: print(f"bm25 neighbors {i}/{n}", flush=True) q_terms = title_toks[i][:16] or body_toks[i][:16] if not q_terms: continue tf_q: dict[str, int] = defaultdict(int) for tok in q_terms: tf_q[tok] += 1 scores: dict[int, float] = defaultdict(float) matched: dict[int, set[str]] = defaultdict(set) for term, qtf in tf_q.items(): docs = term_docs.get(term) if docs is None: continue pay = term_pay[term] * qtf for doc, val in zip(docs, pay): di = int(doc) if di != i: scores[di] += float(val) matched[di].add(term) if scores: top = heapq.nlargest(k, scores.items(), key=lambda kv: kv[1]) neighbors[i] = [(doc, score, sorted(matched[doc])) for doc, score in top] print(f"bm25 neighbors {n}/{n}", flush=True) return neighbors123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661"""End-to-end build: normalize → incremental vectors → BM25 → graph → package.
Default mode is ``auto``: skip when the endomorphosis source revision isunchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuildBM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-invia ``upload=True``."""
from __future__ import annotations
import os
import json
import pandas as pdimport tracebackfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
from .sparse import export_sparse_graphragfrom .mem import MemAbort, checkpoint, log_memfrom .spill import spill_dir_for, spill_picklefrom .package import package_from_spill, package_releasefrom .catalog import get_country, indexable_countries, is_local_law_pack, target_repo
from .incremental import ( fetch_hub_prior, load_embedding_cache, load_prior_release, load_release_vectors_by_cid, merge_embedding_maps, plan_rebuild, save_embedding_cache,)from .normalize import build_corpus, load_sourcefrom .auth import configure_hffrom .vectors import ( DIMENSION, MODEL_NAME, assemble_embeddings, embeddings_by_cid, layout_stub_vectors, layout_vectors, select_device,)
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))CACHE = ROOT / "cache"RELEASES = ROOT / "releases"REPORTS = ROOT / "reports"PROGRESS = ROOT / "progress.jsonl"
def _log(msg: str) -> None: ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") print(f"[{ts}] {msg}", flush=True)
def record_progress(event: dict[str, Any]) -> None: event = dict(event) event.setdefault("ts", datetime.now(timezone.utc).isoformat()) PROGRESS.parent.mkdir(parents=True, exist_ok=True) lock_path = PROGRESS.with_suffix(".lock") with lock_path.open("a", encoding="utf-8") as lock_fh: try: import fcntl
fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX) except Exception: pass with PROGRESS.open("a", encoding="utf-8") as f: f.write(json.dumps(event, ensure_ascii=False) + "\n")
def _prior_dir_for( slug: str, out: Path, prior_dir: Path | None, *, fetch_hub: bool = True,) -> Path | None: if prior_dir is not None: return Path(prior_dir) if out.is_dir() and (out / "manifest.json").is_file(): return out default = RELEASES / f"ipfs_{slug}_laws_ir" if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve(): return default if not fetch_hub: return None hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir") if hub is not None: _log(f"using justicedao prior {hub}") return hub
def _encode_vectors( *, corpus: pd.DataFrame, country_slug: str, prior, plan, skip_vectors: bool, device: str,) -> tuple[dict[str, Any], str | None, dict[str, Any]]: import gc
vector_report: dict[str, Any] = {"status": "stub"} vector_blocker = None if skip_vectors: vectors = layout_stub_vectors(corpus, reason="skip_vectors flag") return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet" prior_by_cid = {} if plan.reuse_embeddings: prior_by_cid = merge_embedding_maps( load_embedding_cache(cid_cache_path), None if prior is None else load_release_vectors_by_cid(prior.directory), ) _log(f"embedding cache reused_cids={len(prior_by_cid)}") try: positional = CACHE / "embeddings" / f"{country_slug}.npy" resolved, fallback = select_device(device) if fallback: _log(f"embedding device fallback requested={device} using={resolved}") embeddings, vector_report = assemble_embeddings( corpus, prior_by_cid, encode_missing=True, device=resolved, checkpoint_path=str(positional), ) if ( vector_report.get("status") in {"stub_missing_encoder", "incomplete"} and not int(vector_report.get("n_reused") or 0) ): vector_blocker = vector_report.get("reason") or vector_report.get("status") vectors = layout_stub_vectors(corpus, reason=str(vector_blocker)) return vectors, vector_blocker, vector_report vectors = layout_vectors(corpus, embeddings) n_reused = int(vector_report.get("n_reused") or 0) n_encoded = int(vector_report.get("n_encoded") or 0) n_missing = int(vector_report.get("n_missing") or 0) if n_reused: vectors["stats"]["n_reused"] = n_reused if n_encoded: vectors["stats"]["n_encoded"] = n_encoded # A complete 384-d table is embedded. partial is only a real gap. complete = n_missing == 0 and (n_reused + n_encoded) >= len(corpus) and len(corpus) > 0 if not complete: vectors["stats"]["status"] = "partial" vectors["stats"]["n_missing"] = n_missing save_embedding_cache( cid_cache_path, merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)), model_name=MODEL_NAME, dimension=DIMENSION, ) del embeddings gc.collect() _log( f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} " f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}" ) return vectors, None, vector_report except Exception as exc: vector_blocker = f"embedding_failed: {exc}" _log(f"vector embedding failed; writing stub ({exc})") vectors = layout_stub_vectors(corpus, reason=vector_blocker) return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
def build_country( source: str, out: Path | None = None, upload: bool = False, device: str = "cuda", neighbor_k: int = 8, skip_vectors: bool = False, mode: str = "auto", force: bool = False, prior_dir: Path | None = None, fetch_hub_prior_ir: bool = True, renormalize: bool = False,) -> dict[str, Any]: from .normalize import preflight_local_shard_source
preflight_local_shard_source(source) country = get_country(source) if not country.get("indexable", True): raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}") repo = country["repo"] out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir" local_dir = country.get("local_source_dir") or ( str(Path(source).resolve()) if is_local_law_pack(Path(source)) else None ) _log( f"build start {repo} -> {out} " f"(upload={upload} mode={mode} force={force} renormalize={renormalize}) local={local_dir}" ) configure_hf() CACHE.mkdir(parents=True, exist_ok=True) REPORTS.mkdir(parents=True, exist_ok=True) laws, articles, source_meta = load_source(local_dir or repo, CACHE) _log( f"source loaded laws={source_meta['n_laws_source']} " f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}" ) prior = load_prior_release( _prior_dir_for( country["slug"], out, prior_dir, fetch_hub=fetch_hub_prior_ir, ) ) plan = plan_rebuild( mode=mode, source_meta=source_meta, prior=prior, force=force, rebuild_stub_vectors=not skip_vectors, ) if plan.skip_build and not renormalize: _log(f"skip unchanged {country['slug']} rev={plan.source_revision}") result = { "country": country["slug"], "source": repo, "source_revision": source_meta["source_revision"], "out": str(out), "target_hub_id": target_repo(country["slug"]), "skipped": True, "incremental": plan.to_dict(), "normalization": {"n_out": plan.delta.current_count if plan.delta else 0}, "vector_blocker": None, "neighbor_via": None, "schema_version": "country-laws-ir-graphrag/v1", } record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}}) return result
corpus, norm_report = build_corpus(laws, articles, source_meta) report_path = REPORTS / f"{country['slug']}_normalization.json" report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") (REPORTS / "normalization.json").write_text( json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) _log( f"normalized docs={len(corpus)} unit={norm_report['unit']} " f"dropped={norm_report['n_dropped_total']} report={report_path}" ) if corpus.empty: raise RuntimeError("Normalized corpus is empty; refusing to package") verdict = (norm_report or {}).get("verification") or {} if verdict.get("blocks_graphrag") and not force: from .verify import NormalizationAdmissionError
raise NormalizationAdmissionError( f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}" )
import gc
plan = plan_rebuild( mode=mode, source_meta=source_meta, prior=prior, current_corpus=corpus, force=force, rebuild_stub_vectors=not skip_vectors, compare_normalized=renormalize and not force, ) _log( f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} " f"added={0 if plan.delta is None else plan.delta.n_added} " f"removed={0 if plan.delta is None else plan.delta.n_removed}" ) if plan.skip_build: _log(f"skip unchanged after normalize {country['slug']}") hub = _publish_unchanged_revision( prior, str(source_meta.get("source_revision") or ""), country["slug"], upload, ) result = { "country": country["slug"], "source": repo, "source_revision": source_meta["source_revision"], "out": str(out), "target_hub_id": target_repo(country["slug"]), "skipped": True, "incremental": plan.to_dict(), "normalization": { "n_out": norm_report.get("n_out"), "unit": norm_report.get("unit"), "n_law_rows": norm_report.get("n_law_rows"), "n_child_rows": norm_report.get("n_child_rows"), }, "vector_blocker": None, "neighbor_via": None, "schema_version": "country-laws-ir-graphrag/v1", } if hub: result["hub"] = hub record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}}) return result
n_docs = len(corpus) spill = spill_dir_for(country["slug"], CACHE) spill.mkdir(parents=True, exist_ok=True) corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet" corpus.to_parquet(corpus_ckpt, index=False) checkpoint("after_normalize", log=_log)
vectors, vector_blocker, vector_report = _encode_vectors( corpus=corpus, country_slug=country["slug"], prior=prior, plan=plan, skip_vectors=skip_vectors, device=device, ) spill_pickle(spill / "vectors.pkl", vectors) del vectors gc.collect() checkpoint("vectors_spilled", log=_log) extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
neighbor_via = "hf_graphrag" if out.exists(): import shutil as _shutil
_shutil.rmtree(out) out.mkdir(parents=True, exist_ok=True) _log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}") sparse_report = export_sparse_graphrag(corpus, out) extra_manifest["sparse"] = sparse_report with open(spill / "vectors.pkl", "rb") as _vf: import pickle as _pickle
vectors = _pickle.load(_vf) dummy_bm25 = { "documents": pd.DataFrame(), "postings": pd.DataFrame(), "stats": (sparse_report.get("bm25") or {}).get("bm25") or (sparse_report.get("bm25") or {}), } dummy_graph = { "nodes": pd.DataFrame(), "edges": pd.DataFrame(), "incoming": pd.DataFrame(), "outgoing": pd.DataFrame(), "stats": sparse_report.get("graph") or {}, } code_root = Path(__file__).resolve().parent.parent manifest = package_release( out, corpus, dummy_bm25, dummy_graph, vectors, source_meta, country, code_root, normalization_report=norm_report, extra_manifest=extra_manifest, wipe=False, skip_bm25_graph=True, ) del corpus, vectors gc.collect() _log(f"packaged {out}") result = { "country": country["slug"], "source": repo, "source_revision": source_meta["source_revision"], "out": str(out), "target_hub_id": target_repo(country["slug"]), "counts": manifest["counts"], "normalization": norm_report, "vector_blocker": vector_blocker, "neighbor_via": neighbor_via, "schema_version": manifest["schema_version"], "skipped": False, "incremental": extra_manifest["incremental"], } if upload: from .upload import upload_release
hub = upload_release(out, target_repo(country["slug"])) result["hub"] = hub _log(f"uploaded {hub['url']} rev={hub['revision']}") record_progress({"event": "uploaded", **result}) else: record_progress({"event": "built_local", **{k: v for k, v in result.items() if k != "normalization"}}) return result
def batch( slugs: list[str] | None = None, upload: bool = False, skip_done: bool = True, mode: str = "auto", force: bool = False, skip_vectors: bool = False,) -> list[dict[str, Any]]: """Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
``skip_done`` is kept for compatibility: it no longer skips a country whose source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to rebuild regardless of CID overlap. """ targets = slugs or [c["slug"] for c in indexable_countries()] if "malta" in targets: targets = ["malta"] + [s for s in targets if s != "malta"] results = [] rebuild_force = force or not skip_done for slug in targets: try: results.append( build_country( slug, upload=upload, mode=mode, force=rebuild_force, skip_vectors=skip_vectors, ) ) except Exception as exc: _log(f"FAILED {slug}: {exc}") record_progress( { "event": "failed", "country": slug, "error": str(exc), "traceback": traceback.format_exc(), } ) continue return results
def reindex_from_gaps( *, upload: bool = False, slugs: list[str] | None = None, limit: int | None = None, max_corpus_rows: int | None = 20_000, skip_vectors: bool = False, workers: int = 4, mode: str = "auto", force: bool = False, all_indexable: bool = False, device: str = "cuda", renormalize: bool = False, corpus_rows: dict[str, int] | None = None,) -> list[dict[str, Any]]: """Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
``workers`` is a ceiling. Live memory, disk, and free GPU memory shrink it, and a full host backs off instead of starting another country. Default cap skips huge corpora (Finland, Dominican Republic). Pass ``max_corpus_rows=None`` to include them. """ from .catalog import indexable_countries from .coverage import gap_report
if slugs is None: if all_indexable: rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()] _log(f"reindex all indexable n={len(rows)}") else: report = gap_report(workers=workers) rows = [c for c in report["countries"] if c.get("rebuild")] _log( f"reindex targets n={len(rows)} " f"(from scan rebuild={len(report.get('rebuild') or [])})" ) rows.sort(key=lambda r: int(r.get("corpus_rows") or 0)) if max_corpus_rows is not None: rows = [ r for r in rows if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows) ] if limit is not None: rows = rows[: int(limit)] queued = [(str(r["slug"]), int(r.get("corpus_rows") or 0)) for r in rows] else: known = corpus_rows or {} queued = [(str(slug), int(known.get(str(slug)) or 0)) for slug in slugs] kwargs = { "upload": upload, "mode": mode, "force": force, "skip_vectors": skip_vectors, "fetch_hub_prior_ir": True, "device": device, "renormalize": renormalize, } ceiling = max(1, int(workers or 1)) _log(f"reindex adaptive ceiling={ceiling} countries={len(queued)} device={device}") return _run_adaptive(queued, kwargs, ceiling)
def _run_adaptive( queued: list[tuple[str, int]], kwargs: dict[str, Any], ceiling: int,) -> list[dict[str, Any]]: """Start countries only while memory, disk, and a GPU have room."""
import multiprocessing as mp import time from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
from .resources import ( admission_budget_gib, admit_parallelism, assign_device, backoff_seconds, can_admit, job_slots, probe_host, )
try: mp.set_start_method("spawn", force=False) except RuntimeError: pass
pending = list(enumerate(queued)) inflight: dict[Any, tuple[int, str, str, int]] = {} results: list[dict[str, Any] | None] = [None] * len(queued) pressure = 0 last_sig: tuple[Any, ...] | None = None requested = str(kwargs.get("device") or "cuda") with ProcessPoolExecutor(max_workers=ceiling, max_tasks_per_child=1) as pool: while pending or inflight: snap = probe_host() admission = admit_parallelism(snap, ceiling=ceiling) devices = admission.devices if requested == "cpu": devices = ("cpu",) if admission.workers else () elif requested.startswith("cuda:") and requested not in devices: devices = () limit = admission.workers if devices else 0 signature = (limit, devices, admission.reason) if signature != last_sig: _log( f"admit workers={limit} devices={list(devices)} reason={admission.reason} " f"mem={snap.mem_available_gib:.1f}G sched={admission_budget_gib(snap):.1f}G " f"disk={snap.disk_free_gib:.0f}G " f"inflight={len(inflight)} pending={len(pending)}" ) last_sig = signature used = sum(item[3] for item in inflight.values()) started = False while pending and devices: _idx, (_source, rows) = pending[0] cost = job_slots(rows) if not can_admit(used, limit, cost): break device = assign_device(devices, tuple(item[2] for item in inflight.values())) idx, (source, _rows) = pending.pop(0) held = cost task_kwargs = dict(kwargs) task_kwargs["device"] = device future = pool.submit(_reindex_one_country, (source, task_kwargs)) inflight[future] = (idx, source, device, held) used += held started = True _log(f"admit start {source} device={device} slots={cost}") if started: pressure = 0 if inflight: done, _pending_futs = wait( set(inflight), timeout=5.0, return_when=FIRST_COMPLETED ) for future in done: idx, source, _device, _held = inflight.pop(future) try: results[idx] = future.result() except Exception as exc: _log(f"FAILED {source}: {exc}") results[idx] = {"country": source, "skipped": False, "error": str(exc)} continue if not pending: break delay = backoff_seconds(admission.backoff_s or 15.0, pressure) pressure += 1 _log(f"backoff {delay:.0f}s reason={admission.reason} pressure={pressure}") time.sleep(delay) return [row for row in results if row is not None]
def _publish_unchanged_revision( prior, source_revision: str, slug: str, upload: bool,) -> dict[str, Any] | None: """Upload the existing pack with the new raw SHA when the rows did not change."""
if prior is None or not upload: return None from .incremental import stamp_source_revision
manifest_path = Path(prior.directory) / "manifest.json" if not manifest_path.is_file(): return None manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if not isinstance(manifest, dict) or not stamp_source_revision(manifest, source_revision): return None manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8") from .upload import upload_release
hub = upload_release(Path(prior.directory), target_repo(slug)) _log(f"uploaded unchanged {hub['url']} source={source_revision}") return hub
def _external_build_owns(source: str) -> bool: """True when a build outside this pool already claimed the country."""
import os
root = Path( os.environ.get( "COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir"), ) ) name = str(source).rstrip("/").rsplit("/", 1)[-1] if name.startswith("ipfs_") and name.endswith("_laws"): name = name[len("ipfs_") : -len("_laws")] return (root / "external-builds" / name).is_file()
def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]: slug, kwargs = item if _external_build_owns(slug): _log(f"skip {slug}: external build owns it") return {"country": slug, "skipped": True, "reason": "external"} _log(f"reindex start {slug}") try: return build_country(slug, **kwargs) except Exception as exc: _log(f"FAILED {slug}: {exc}") record_progress( { "event": "failed", "country": slug, "error": str(exc), "traceback": traceback.format_exc(), } ) return {"country": slug, "skipped": False, "error": str(exc)}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307"""Catalog of endomorphosis/ipfs_*_laws corpora.
Belgium, Portugal, and Lithuania are incomplete Wayback harvests and areexcluded from indexing. american_municipal_law is out of scope.
The static ``COUNTRIES`` list is the fail-closed baseline. ``refresh_from_hub``persists a sidecar cache of newly listed Hub datasets so incremental scrapesof additional jurisdictions are indexable without a code change."""
from __future__ import annotations
import jsonimport osfrom pathlib import Pathfrom typing import Any
EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania", "ghana"}EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS}
_SKIP_REASONS = { "belgium": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)", "portugal": "incomplete Wayback harvest (Diário da República archive shard)", "lithuania": "incomplete Wayback harvest (e-TAR archive shard)", "ghana": "thin scrape; Act PDF path blocked by robots",}
def catalog_cache_path() -> Path: root = Path( os.environ.get( "COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir"), ) ) return root / "catalog_cache.json"
# Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`.COUNTRIES: list[dict[str, Any]] = [ {"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True}, {"slug": "australia", "repo": "endomorphosis/ipfs_australia_laws", "name": "Australia", "indexable": True}, {"slug": "austria", "repo": "endomorphosis/ipfs_austria_laws", "name": "Austria", "indexable": True}, {"slug": "bangladesh", "repo": "endomorphosis/ipfs_bangladesh_laws", "name": "Bangladesh", "indexable": True}, {"slug": "belgium", "repo": "endomorphosis/ipfs_belgium_laws", "name": "Belgium", "indexable": False, "skip_reason": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)"}, {"slug": "brazil", "repo": "endomorphosis/ipfs_brazil_laws", "name": "Brazil", "indexable": True}, {"slug": "canada", "repo": "endomorphosis/ipfs_canada_laws", "name": "Canada", "indexable": True}, {"slug": "chile", "repo": "endomorphosis/ipfs_chile_laws", "name": "Chile", "indexable": True}, {"slug": "china", "repo": "endomorphosis/ipfs_china_laws", "name": "China", "indexable": True}, {"slug": "colombia", "repo": "endomorphosis/ipfs_colombia_laws", "name": "Colombia", "indexable": True}, {"slug": "croatia", "repo": "endomorphosis/ipfs_croatia_laws", "name": "Croatia", "indexable": True}, {"slug": "czechia", "repo": "endomorphosis/ipfs_czechia_laws", "name": "Czechia", "indexable": True}, {"slug": "denmark", "repo": "endomorphosis/ipfs_denmark_laws", "name": "Denmark", "indexable": True}, {"slug": "egypt", "repo": "endomorphosis/ipfs_egypt_laws", "name": "Egypt", "indexable": True}, {"slug": "estonia", "repo": "endomorphosis/ipfs_estonia_laws", "name": "Estonia", "indexable": True}, {"slug": "eu", "repo": "endomorphosis/ipfs_eu_laws", "name": "European Union", "indexable": True}, {"slug": "finland", "repo": "endomorphosis/ipfs_finland_laws", "name": "Finland", "indexable": True}, {"slug": "france", "repo": "endomorphosis/ipfs_france_laws", "name": "France", "indexable": True}, {"slug": "ghana", "repo": "endomorphosis/ipfs_ghana_laws", "name": "Ghana", "indexable": False, "skip_reason": "thin scrape; Act PDF path blocked by robots"}, {"slug": "germany", "repo": "endomorphosis/ipfs_germany_laws", "name": "Germany", "indexable": True}, {"slug": "greece", "repo": "endomorphosis/ipfs_greece_laws", "name": "Greece", "indexable": True}, {"slug": "hongkong", "repo": "endomorphosis/ipfs_hongkong_laws", "name": "Hong Kong", "indexable": True}, {"slug": "iceland", "repo": "endomorphosis/ipfs_iceland_laws", "name": "Iceland", "indexable": True}, {"slug": "hungary", "repo": "endomorphosis/ipfs_hungary_laws", "name": "Hungary", "indexable": True}, {"slug": "india", "repo": "endomorphosis/ipfs_india_laws", "name": "India", "indexable": True}, {"slug": "indonesia", "repo": "endomorphosis/ipfs_indonesia_laws", "name": "Indonesia", "indexable": True}, {"slug": "ireland", "repo": "endomorphosis/ipfs_ireland_laws", "name": "Ireland", "indexable": True}, {"slug": "israel", "repo": "endomorphosis/ipfs_israel_laws", "name": "Israel", "indexable": True}, {"slug": "japan", "repo": "endomorphosis/ipfs_japan_laws", "name": "Japan", "indexable": True}, {"slug": "kenya", "repo": "endomorphosis/ipfs_kenya_laws", "name": "Kenya", "indexable": True}, {"slug": "korea", "repo": "endomorphosis/ipfs_korea_laws", "name": "Korea (ROK)", "indexable": True}, {"slug": "kuwait", "repo": "endomorphosis/ipfs_kuwait_laws", "name": "Kuwait", "indexable": True}, {"slug": "latvia", "repo": "endomorphosis/ipfs_latvia_laws", "name": "Latvia", "indexable": True}, {"slug": "lithuania", "repo": "endomorphosis/ipfs_lithuania_laws", "name": "Lithuania", "indexable": False, "skip_reason": "incomplete Wayback harvest (e-TAR archive shard)"}, {"slug": "luxembourg", "repo": "endomorphosis/ipfs_luxembourg_laws", "name": "Luxembourg", "indexable": True}, {"slug": "malaysia", "repo": "endomorphosis/ipfs_malaysia_laws", "name": "Malaysia", "indexable": True}, {"slug": "malta", "repo": "endomorphosis/ipfs_malta_laws", "name": "Malta", "indexable": True, "pilot": True}, {"slug": "morocco", "repo": "endomorphosis/ipfs_morocco_laws", "name": "Morocco", "indexable": True}, {"slug": "mexico", "repo": "endomorphosis/ipfs_mexico_laws", "name": "Mexico", "indexable": True}, {"slug": "netherlands", "repo": "endomorphosis/ipfs_netherlands_laws", "name": "Netherlands", "indexable": True}, {"slug": "newzealand", "repo": "endomorphosis/ipfs_newzealand_laws", "name": "New Zealand", "indexable": True}, {"slug": "nigeria", "repo": "endomorphosis/ipfs_nigeria_laws", "name": "Nigeria", "indexable": True}, {"slug": "norway", "repo": "endomorphosis/ipfs_norway_laws", "name": "Norway", "indexable": True}, {"slug": "pakistan", "repo": "endomorphosis/ipfs_pakistan_laws", "name": "Pakistan", "indexable": True}, {"slug": "philippines", "repo": "endomorphosis/ipfs_philippines_laws", "name": "Philippines", "indexable": True}, {"slug": "poland", "repo": "endomorphosis/ipfs_poland_laws", "name": "Poland", "indexable": True}, {"slug": "portugal", "repo": "endomorphosis/ipfs_portugal_laws", "name": "Portugal", "indexable": False, "skip_reason": "incomplete Wayback harvest (Diário da República archive shard)"}, {"slug": "qatar", "repo": "endomorphosis/ipfs_qatar_laws", "name": "Qatar", "indexable": True}, {"slug": "russia", "repo": "endomorphosis/ipfs_russia_laws", "name": "Russia", "indexable": True}, {"slug": "saudiarabia", "repo": "endomorphosis/ipfs_saudiarabia_laws", "name": "Saudi Arabia", "indexable": True}, {"slug": "singapore", "repo": "endomorphosis/ipfs_singapore_laws", "name": "Singapore", "indexable": True}, {"slug": "slovakia", "repo": "endomorphosis/ipfs_slovakia_laws", "name": "Slovakia", "indexable": True}, {"slug": "southafrica", "repo": "endomorphosis/ipfs_southafrica_laws", "name": "South Africa", "indexable": True}, {"slug": "spain", "repo": "endomorphosis/ipfs_spain_laws", "name": "Spain", "indexable": True}, {"slug": "sweden", "repo": "endomorphosis/ipfs_sweden_laws", "name": "Sweden", "indexable": True}, {"slug": "switzerland", "repo": "endomorphosis/ipfs_switzerland_laws", "name": "Switzerland", "indexable": True}, {"slug": "taiwan", "repo": "endomorphosis/ipfs_taiwan_laws", "name": "Taiwan", "indexable": True}, {"slug": "thailand", "repo": "endomorphosis/ipfs_thailand_laws", "name": "Thailand", "indexable": True}, {"slug": "turkey", "repo": "endomorphosis/ipfs_turkey_laws", "name": "Turkey", "indexable": True}, {"slug": "uae", "repo": "endomorphosis/ipfs_uae_laws", "name": "United Arab Emirates", "indexable": True}, {"slug": "uk", "repo": "endomorphosis/ipfs_uk_laws", "name": "United Kingdom", "indexable": True}, {"slug": "ukraine", "repo": "endomorphosis/ipfs_ukraine_laws", "name": "Ukraine", "indexable": True}, {"slug": "vietnam", "repo": "endomorphosis/ipfs_vietnam_laws", "name": "Vietnam", "indexable": True}, {"slug": "bulgaria", "repo": "endomorphosis/ipfs_bulgaria_laws", "name": "Bulgaria", "indexable": True}, {"slug": "cyprus", "repo": "endomorphosis/ipfs_cyprus_laws", "name": "Cyprus", "indexable": True}, {"slug": "italy", "repo": "endomorphosis/ipfs_italy_laws", "name": "Italy", "indexable": True}, {"slug": "romania", "repo": "endomorphosis/ipfs_romania_laws", "name": "Romania", "indexable": True}, {"slug": "slovenia", "repo": "endomorphosis/ipfs_slovenia_laws", "name": "Slovenia", "indexable": True},]
def load_cached_countries() -> list[dict[str, Any]]: path = catalog_cache_path() if not path.is_file(): return [] try: payload = json.loads(path.read_text(encoding="utf-8")) except Exception: return [] rows = payload.get("countries") if isinstance(payload, dict) else payload if not isinstance(rows, list): return [] out: list[dict[str, Any]] = [] for row in rows: if isinstance(row, dict) and row.get("slug") and row.get("repo"): out.append(dict(row)) return out
def persist_catalog(countries: list[dict[str, Any]], path: Path | None = None) -> Path: dest = path or catalog_cache_path() dest.parent.mkdir(parents=True, exist_ok=True) payload = { "n": len(countries), "indexable": sum(1 for c in countries if c.get("indexable")), "countries": countries, } dest.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") return dest
def merge_country_rows( baseline: list[dict[str, Any]], extra: list[dict[str, Any]],) -> list[dict[str, Any]]: """Static catalog wins on slug; Hub extras fill gaps.""" by_slug = {str(row["slug"]): dict(row) for row in baseline if row.get("slug")} for row in extra: slug = str(row.get("slug") or "") if not slug or slug in by_slug: continue by_slug[slug] = dict(row) return [by_slug[k] for k in sorted(by_slug)]
def all_countries() -> list[dict[str, Any]]: return merge_country_rows(COUNTRIES, load_cached_countries())
def is_local_law_pack(path: Path) -> bool: """True when a directory already has laws.parquet or text law shards."""
local = Path(path) if not local.is_dir(): return False if (local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file(): return True data = local / "data" if not data.is_dir(): return False return any( shard.name.startswith("laws-") and shard.suffix == ".parquet" and "_html" not in shard.name for shard in data.glob("laws-*.parquet") )
def static_crosswalk_coverage() -> dict[str, Any]: """Compare reviewed crosswalk slugs with the static catalog.
A slug that is only in the crosswalk stays non-indexable. Alias keys fold onto the canonical slug and are not a second country. """
from ipfs_datasets_py.processors.legal_data.iso_slug_crosswalk import ( codes_in_crosswalk, national_slug, ) from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.coverage import ( ALIAS_TO_CANONICAL, canonical_slug, )
slugs: set[str] = set() for code in codes_in_crosswalk(): slug = national_slug(code) if slug: slugs.add(canonical_slug(slug)) known = {str(row["slug"]) for row in COUNTRIES if row.get("slug")} return { "crosswalk_slugs": sorted(slugs), "in_static_catalog": sorted(slugs & known), "not_in_static_catalog": sorted(slugs - known), "missing_indexable": False, "alias_keys_are_not_extra_countries": sorted(ALIAS_TO_CANONICAL), }
def get_country(source: str) -> dict[str, Any]: source = source.strip() # Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json) from pathlib import Path as _Path import json as _json
local = _Path(source) if is_local_law_pack(local): pack_meta: dict[str, Any] = {} meta_path = local / "pack_meta.json" if meta_path.is_file(): try: pack_meta = _json.loads(meta_path.read_text(encoding="utf-8")) except Exception: pack_meta = {} slug = str(pack_meta.get("slug") or local.name) # strip common cache prefixes like oman_filtered_c72f142a if slug.startswith("oman"): slug = "oman" for prefix in ("ipfs_",): if slug.startswith(prefix): slug = slug[len(prefix):] for suffix in ("_laws", "_filtered", "-ir"): if slug.endswith(suffix): slug = slug[: -len(suffix)] # e.g. oman_filtered_c72f142a -> oman if "_filtered" in slug: slug = slug.split("_filtered", 1)[0] repo = str(pack_meta.get("repo") or pack_meta.get("source_dataset") or f"endomorphosis/ipfs_{slug}_laws") return { "slug": slug, "repo": repo, "name": str(pack_meta.get("name") or slug.replace("_", " ").title()), "indexable": bool(pack_meta.get("indexable", slug not in EXCLUDED_SLUGS)), "skip_reason": pack_meta.get("skip_reason"), "local_source_dir": str(local.resolve()), "source_revision": pack_meta.get("source_revision"), }
slug = source if "/" in source: slug = source.rsplit("/", 1)[-1] slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir") from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.coverage import ( canonical_slug, )
slug = canonical_slug(slug) for row in all_countries(): if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source): return dict(row) if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"): inferred = source.split("ipfs_", 1)[1].removesuffix("_laws") return { "slug": inferred, "repo": source, "name": inferred.replace("_", " ").title(), "indexable": inferred not in EXCLUDED_SLUGS, "skip_reason": _SKIP_REASONS.get(inferred), } raise KeyError(f"Unknown country-law source: {source}")
def indexable_countries() -> list[dict[str, Any]]: return [c for c in all_countries() if c.get("indexable")]
def target_repo(slug: str) -> str: return f"justicedao/ipfs_{slug}_laws_ir"
def refresh_from_hub(*, persist: bool = True) -> list[dict[str, Any]]: """Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets.""" from huggingface_hub import HfApi
from .auth import configure_hf, public_token
configure_hf() api = HfApi(token=public_token()) found: list[dict[str, Any]] = [] for ds in api.list_datasets(author="endomorphosis"): ds_id = ds.id if not ds_id.startswith("endomorphosis/ipfs_") or not ds_id.endswith("_laws"): continue slug = ds_id.split("ipfs_", 1)[1].removesuffix("_laws") found.append({ "slug": slug, "repo": ds_id, "name": slug.replace("_", " ").title(), "indexable": slug not in EXCLUDED_SLUGS, "skip_reason": _SKIP_REASONS.get(slug), }) found.sort(key=lambda r: r["slug"]) merged = merge_country_rows(COUNTRIES, found) if persist: persist_catalog(merged) return merged123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102"""CIDv1 (raw + sha2-256) helpers. Produces bafkrei... identifiers.
Payload format (deterministic): json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
Codec: CIDv1 version=0x01, multicodec raw=0x55, multihash sha2-256=0x12, length=0x20,then 32-byte digest. Multibase prefix `b` + RFC 4648 base32 (lowercase, no padding).Same payload bytes always yield the same CID."""
from __future__ import annotations
import hashlibimport jsonfrom pathlib import Pathfrom typing import Any
_B32 = "abcdefghijklmnopqrstuvwxyz234567"
def sha256_hex(data: bytes) -> str: return hashlib.sha256(data).hexdigest()
def sha256_file(path: Path) -> str: h = hashlib.sha256() with path.open("rb") as f: while True: chunk = f.read(1024 * 1024) if not chunk: break h.update(chunk) return h.hexdigest()
def canonical_json_bytes(obj: Any) -> bytes: return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
def _b32encode(data: bytes) -> str: bits = 0 value = 0 out = [] for byte in data: value = (value << 8) | byte bits += 8 while bits >= 5: bits -= 5 out.append(_B32[(value >> bits) & 31]) if bits: out.append(_B32[(value << (5 - bits)) & 31]) return "".join(out)
def cid_v1_raw_sha256(data: bytes) -> str: digest = hashlib.sha256(data).digest() cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest return "b" + _b32encode(cid_bytes)
def sha256_key_to_cidv1(value: str) -> str: """Turn a bare/prefixed SHA-256 routing key into ``bafkrei…`` CIDv1.
GraphRAG locators must not use hex digests as ``entry_cid`` / ``node_cid``. """
text = str(value or "").strip() if text.startswith("bafkrei"): return text hex_part = text[7:71] if text.lower().startswith("sha256:") else text[:64] rest = text[71:] if text.lower().startswith("sha256:") else text[64:] if len(hex_part) != 64: return text try: digest = bytes.fromhex(hex_part) except ValueError: return text cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest return "b" + _b32encode(cid_bytes) + rest
def cid_of_json(obj: Any) -> str: return cid_v1_raw_sha256(canonical_json_bytes(obj))
def cid_of_text(*parts: str) -> str: blob = "\n".join("" if p is None else str(p) for p in parts).encode("utf-8") return cid_v1_raw_sha256(blob)
def file_descriptor(path: Path, relative_path: str, extra: dict | None = None) -> dict: data = path.read_bytes() desc = { "cid": cid_v1_raw_sha256(data), "sha256": sha256_hex(data), "size_bytes": len(data), "relative_path": relative_path, } if extra: desc.update(extra) return desc123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139"""Official and Bluebook citations for country-law corpus rows.
Bluebook T2/T10 abbreviations are used only when this table has a row.Unknown jurisdictions get ``official_citation`` only — never a inventedBluebook form. Query keys are normalized so ``ORS 1.010`` and``Or. Rev. Stat. § 1.010`` can hit the same row later."""
from __future__ import annotations
from dataclasses import dataclassimport reimport unicodedatafrom typing import Any
from pathlib import Pathimport json as _json
_TABLE_PATH = Path(__file__).resolve().parent / "data" / "bluebook_t2.json"
def _load_t2() -> dict[str, dict[str, Any]]: if not _TABLE_PATH.is_file(): return {} payload = _json.loads(_TABLE_PATH.read_text(encoding="utf-8")) return payload if isinstance(payload, dict) else {}
_BLUEBOOK_T2 = _load_t2()
@dataclass(frozen=True)class Citation: official_citation: str bluebook_citation: str cite_key: str citation_status: str # bluebook | official_only | unknown pinpoint: str
def normalize_cite_key(value: str) -> str: if not value: return "" text = unicodedata.normalize("NFKC", value).lower() text = text.replace("§", " s ") text = text.replace("¶", " ") text = re.sub(r"\bart(?:icle|\.)?\b", "art", text) text = re.sub(r"\bsec(?:tion|\.)?\b", "s", text) text = re.sub(r"[^a-z0-9]+", " ", text) return re.sub(r"\s+", " ", text).strip()
def _pinpoint(article_number: str, section_number: str, record_type: str) -> str: if record_type == "section" and section_number: return f"§ {section_number}" if article_number: return f"art. {article_number}" if section_number: return f"§ {section_number}" return ""
def _t2_row(jurisdiction: str, country: str, slug: str = "") -> dict[str, Any]: for key in (slug, country, jurisdiction): hit = _BLUEBOOK_T2.get(str(key or "").strip().lower().replace("_", " ")) if isinstance(hit, dict): return hit return {}
def assign_citation( *, eli: str = "", official_identifier: str = "", identifier: str = "", instrument_title: str = "", article_number: str = "", section_number: str = "", record_type: str = "law", jurisdiction: str = "", country: str = "", slug: str = "", year: str = "",) -> Citation: pinpoint = _pinpoint(article_number, section_number, record_type) official = ( (eli or "").strip() or (official_identifier or "").strip() or (identifier or "").strip() or (instrument_title or "").strip() ) if official and pinpoint and pinpoint.lower() not in official.lower(): official_cite = f"{official}, {pinpoint}" else: official_cite = official
t2 = _t2_row(jurisdiction, country, slug) abbrev = str(t2.get("abbrev") or "") emit = str(t2.get("emit") or "official_only") required = list(t2.get("required") or []) have = { "year": bool(year), "section": bool(section_number or (record_type == "section" and article_number)), "article": bool(article_number), "title": bool(instrument_title), } missing = [k for k in required if not have.get(k)] bluebook = "" if emit == "bluebook" and abbrev and not missing: if pinpoint: bluebook = f"{abbrev} {pinpoint}" + (f" ({year})" if year else "") elif have.get("section"): bluebook = f"{abbrev} § {section_number}" + (f" ({year})" if year else "")
if bluebook: status = "bluebook" elif official_cite: status = "official_only" else: status = "unknown"
key_src = bluebook or official_cite return Citation( official_citation=official_cite, bluebook_citation=bluebook, cite_key=normalize_cite_key(key_src), citation_status=status, pinpoint=pinpoint, )
def citation_fields(cite: Citation) -> dict[str, Any]: return { "official_citation": cite.official_citation, "bluebook_citation": cite.bluebook_citation, "cite_key": cite.cite_key, "citation_status": cite.citation_status, "pinpoint": cite.pinpoint, }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455"""Compare endomorphosis raw sources against justicedao GraphRAG releases.
Gap kinds---------* missing — no JusticeDAO IR (and no local pack)* unpublished — local IR exists, Hub IR does not* stale — Hub/local IR source revision does not match current endomorphosis SHA* incomplete — missing corpus/BM25/graph, empty corpus, or source has no laws* stub_vectors — IR is otherwise current but embeddings were stubbed"""
from __future__ import annotations
import jsonimport timefrom concurrent.futures import ThreadPoolExecutor, as_completedfrom pathlib import Pathfrom typing import Any, Mapping
from .catalog import EXCLUDED_SLUGS, all_countries, static_crosswalk_coverage, target_repo
ALIAS_TO_CANONICAL = { "dominican_republic": "dominicanrepublic", "el_salvador": "elsalvador", "north_korea": "northkorea", "papua_new_guinea": "papuanewguinea", "san_marino": "sanmarino", "trinidad_and_tobago": "trinidad",}
def _slug_from_source(dataset_id: str) -> str | None: if not dataset_id.startswith("endomorphosis/ipfs_") or not dataset_id.endswith("_laws"): return None return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws")
def _slug_from_ir(dataset_id: str) -> str | None: if not dataset_id.startswith("justicedao/ipfs_") or not dataset_id.endswith("_laws_ir"): return None return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws_ir")
def canonical_slug(slug: str) -> str: return ALIAS_TO_CANONICAL.get(slug, slug)
def list_hub_slugs(*, author: str, kind: str) -> list[str]: from huggingface_hub import HfApi
from .auth import configure_hf, operator_token, public_token
configure_hf() token = operator_token() or public_token() api = HfApi(token=token) out: list[str] = [] for ds in api.list_datasets(author=author): slug = _slug_from_source(ds.id) if kind == "source" else _slug_from_ir(ds.id) if slug: out.append(slug) return sorted(set(out))
def local_release_slugs(releases_dir: Path) -> list[str]: if not releases_dir.is_dir(): return [] found: list[str] = [] for path in sorted(releases_dir.glob("ipfs_*_laws_ir")): if (path / "manifest.json").is_file(): slug = path.name.removeprefix("ipfs_").removesuffix("_laws_ir") found.append(slug) return found
IR_FAMILY_PREFIXES = ( ("data/corpus/", "ir_missing_corpus"), ("data/bm25/", "ir_missing_bm25"), ("data/graph/", "ir_missing_graph"),)STUB_VECTOR_STATUSES = {"stub", "stub_missing_encoder", "incomplete"}TINY_LAWS_BYTES = 1024
def classify_gap( *, excluded: bool = False, alias: bool = False, source_has_laws: bool = True, source_laws_bytes: int | None = None, source_revision: str | None = None, ir_files: list[str] | None = None, ir_source_revision: str | None = None, ir_corpus_rows: int | None = None, vector_status: str | None = None, local_only: bool = False, local_source_revision: str | None = None,) -> dict[str, Any]: """Pure classifier for missing / stale / incomplete country IR.""" issues: list[str] = [] if alias: return {"status": "alias", "issues": issues, "rebuild": False, "publish": False} if excluded: return {"status": "excluded", "issues": issues, "rebuild": False, "publish": False}
if not source_has_laws: issues.append("source_missing_laws") if ( source_laws_bytes is not None and source_laws_bytes >= 0 and source_laws_bytes < TINY_LAWS_BYTES ): issues.append("source_laws_tiny")
if ir_files is None: issues.append("missing_ir") else: names = set(ir_files) if "manifest.json" not in names: issues.append("ir_missing_manifest") for prefix, issue in IR_FAMILY_PREFIXES: if not any(name.startswith(prefix) for name in names): issues.append(issue) if ir_corpus_rows is not None and int(ir_corpus_rows) <= 0: issues.append("ir_empty_corpus") if ( source_revision and ir_source_revision and str(source_revision) != str(ir_source_revision) ): issues.append("stale_source_revision") if vector_status in STUB_VECTOR_STATUSES: issues.append("ir_stub_vectors")
structural = { "source_missing_laws", "source_laws_tiny", "ir_missing_manifest", "ir_missing_corpus", "ir_missing_bm25", "ir_missing_graph", "ir_empty_corpus", } issue_set = set(issues) if "missing_ir" in issue_set: status = "unpublished" if local_only else "missing" elif "stale_source_revision" in issue_set: status = "stale" elif issue_set & structural: status = "incomplete" elif issue_set == {"ir_stub_vectors"}: status = "stub_vectors" elif not issues: status = "current" else: status = "incomplete"
local_current = bool( source_revision and local_source_revision and str(source_revision) == str(local_source_revision) ) rebuild = ( status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (not local_current or status == "stub_vectors") ) publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and ( "source_missing_laws" not in issues ) return { "status": status, "issues": issues, "rebuild": rebuild, "publish": publish, }
def _ir_source_revision(manifest: Mapping[str, Any] | None) -> str | None: if not manifest: return None pinned = manifest.get("dataset_revision") or (manifest.get("source") or {}).get( "source_revision" ) text = str(pinned or "").strip() return text or None
def _vector_status(manifest: Mapping[str, Any] | None) -> str | None: if not manifest: return None vector = manifest.get("vector") or {} if isinstance(vector, dict) and vector.get("status"): return str(vector.get("status")) incremental = manifest.get("incremental") or {} nested = incremental.get("vectors") if isinstance(incremental, dict) else None if isinstance(nested, dict) and nested.get("status"): return str(nested.get("status")) if isinstance(vector, dict) and vector.get("stub"): return "stub" return None
def load_local_manifest(release_dir: Path) -> dict[str, Any]: path = Path(release_dir) / "manifest.json" if not path.is_file(): return {} try: data = json.loads(path.read_text(encoding="utf-8")) except Exception: return {} return data if isinstance(data, dict) else {}
def _sibling_map(info: Any) -> dict[str, int | None]: out: dict[str, int | None] = {} for sib in getattr(info, "siblings", None) or []: name = str(getattr(sib, "rfilename", "") or "") if not name: continue size = getattr(sib, "size", None) try: out[name] = int(size) if size is not None else None # type: ignore[assignment] except (TypeError, ValueError): out[name] = None # type: ignore[assignment] return out
def _inspect_source(slug: str, cache_dir: Path | None = None) -> dict[str, Any]: from huggingface_hub import dataset_info
from .auth import configure_hf, operator_token, public_token
repo = f"endomorphosis/ipfs_{slug}_laws" configure_hf() info = dataset_info(repo, token=operator_token() or public_token()) files = _sibling_map(info) laws_file = next( (name for name in ("data/laws.parquet", "laws.parquet") if name in files), None, ) arts_file = next( (name for name in ("data/articles.parquet", "articles.parquet") if name in files), None, ) return { "repo": repo, "revision": getattr(info, "sha", None), "files": sorted(files), "has_laws": laws_file is not None, "has_articles": arts_file is not None, "laws_bytes": files.get(laws_file) if laws_file else None, "articles_bytes": files.get(arts_file) if arts_file else None, }
def _inspect_ir(slug: str, cache_dir: Path) -> dict[str, Any] | None: from huggingface_hub import HfApi, dataset_info, hf_hub_download from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError
from .auth import configure_hf, operator_token, public_token
repo = target_repo(slug) configure_hf() token = operator_token() or public_token() try: info = dataset_info(repo, token=token) except RepositoryNotFoundError: return None files = _sibling_map(info) if len(files) < 8: try: listed = HfApi(token=token).list_repo_files(repo_id=repo, repo_type="dataset") for name in listed: files.setdefault(str(name), None) except Exception: pass manifest: dict[str, Any] = {} if "manifest.json" in files: try: path = hf_hub_download( repo_id=repo, filename="manifest.json", repo_type="dataset", token=token, cache_dir=str(cache_dir / "hf"), ) payload = json.loads(Path(path).read_text(encoding="utf-8")) if isinstance(payload, dict): manifest = payload except (EntryNotFoundError, OSError, json.JSONDecodeError): manifest = {} counts = manifest.get("counts") if isinstance(manifest.get("counts"), dict) else {} return { "repo": repo, "hub_revision": getattr(info, "sha", None), "files": sorted(files), "manifest": manifest, "source_revision": _ir_source_revision(manifest), "corpus_rows": counts.get("corpus_rows"), "vector_status": _vector_status(manifest), }
def gap_report( releases_dir: Path | None = None, *, slugs: list[str] | None = None, workers: int = 8,) -> dict[str, Any]: """Live Hub scan: missing, stale, incomplete, and unpublished country IR.""" from .build import CACHE, RELEASES
# Each spelling is its own scrape and its own justicedao index. # Dropping alias keys hid el_salvador and papua_new_guinea when those # repos moved and the unpunctuated twin did not. sources = slugs or list_hub_slugs(author="endomorphosis", kind="source") hub_ir = set(list_hub_slugs(author="justicedao", kind="ir")) local_dir = Path(releases_dir) if releases_dir else RELEASES local_ir = set(local_release_slugs(local_dir)) cache_dir = CACHE cache_dir.mkdir(parents=True, exist_ok=True)
rows: list[dict[str, Any]] = []
def _one(slug: str) -> dict[str, Any]: last_exc: Exception | None = None for attempt in range(4): try: source = _inspect_source(slug) ir = _inspect_ir(slug, cache_dir) if slug in hub_ir else None break except Exception as exc: last_exc = exc name = type(exc).__name__ msg = str(exc) if "429" in msg or "rate limit" in msg.lower(): time.sleep(min(45, 3 ** attempt * 2)) continue raise else: raise last_exc or RuntimeError(f"scan failed for {slug}") local_manifest = load_local_manifest(local_dir / f"ipfs_{slug}_laws_ir") local_rev = _ir_source_revision(local_manifest) if local_manifest else None classified = classify_gap( excluded=slug in EXCLUDED_SLUGS, alias=False, source_has_laws=bool(source.get("has_laws")), source_laws_bytes=source.get("laws_bytes"), source_revision=source.get("revision"), ir_files=None if ir is None else ir.get("files"), ir_source_revision=(ir or {}).get("source_revision") or local_rev, ir_corpus_rows=(ir or {}).get("corpus_rows") if ir is not None else (local_manifest.get("counts") or {}).get("corpus_rows") if local_manifest else None, vector_status=(ir or {}).get("vector_status") or _vector_status(local_manifest), local_only=slug in local_ir and slug not in hub_ir, local_source_revision=local_rev, ) return { "slug": slug, "source": source.get("repo"), "target": target_repo(slug), "source_revision": source.get("revision"), "ir_source_revision": (ir or {}).get("source_revision"), "local_source_revision": local_rev, "has_hub_ir": ir is not None, "has_local_ir": slug in local_ir, "source_has_articles": source.get("has_articles"), "source_laws_bytes": source.get("laws_bytes"), "corpus_rows": (ir or {}).get("corpus_rows") if ir is not None else (local_manifest.get("counts") or {}).get("corpus_rows") if local_manifest else None, "vector_status": (ir or {}).get("vector_status") or _vector_status(local_manifest), **classified, }
workers = max(1, min(int(workers), 16)) with ThreadPoolExecutor(max_workers=workers) as pool: futs = {pool.submit(_one, slug): slug for slug in sources} for fut in as_completed(futs): slug = futs[fut] try: rows.append(fut.result()) except Exception as exc: rows.append( { "slug": slug, "source": f"endomorphosis/ipfs_{slug}_laws", "target": target_repo(slug), "status": "incomplete", "issues": [f"scan_error:{type(exc).__name__}"], "rebuild": False, "publish": False, "error": str(exc), } ) rows.sort(key=lambda r: str(r.get("slug"))) by_status: dict[str, list[str]] = {} for row in rows: by_status.setdefault(str(row.get("status")), []).append(str(row.get("slug"))) return { "n": len(rows), "by_status": {k: sorted(v) for k, v in sorted(by_status.items())}, "counts": {k: len(v) for k, v in sorted(by_status.items())}, "rebuild": [r["slug"] for r in rows if r.get("rebuild")], "publish": [r["slug"] for r in rows if r.get("publish")], "countries": rows, }
def coverage_report(releases_dir: Path | None = None) -> dict[str, Any]: from .build import RELEASES
sources = list_hub_slugs(author="endomorphosis", kind="source") hub_ir = list_hub_slugs(author="justicedao", kind="ir") local_ir = local_release_slugs(Path(releases_dir) if releases_dir else RELEASES) hub_ir_canon = {canonical_slug(s) for s in hub_ir} local_ir_canon = {canonical_slug(s) for s in local_ir} missing_hub: list[dict[str, Any]] = [] missing_local: list[dict[str, Any]] = [] excluded: list[str] = [] aliases: list[str] = [] for slug in sources: if slug in ALIAS_TO_CANONICAL: aliases.append(slug) continue if slug in EXCLUDED_SLUGS: excluded.append(slug) continue row = { "slug": slug, "source": f"endomorphosis/ipfs_{slug}_laws", "target": target_repo(slug), } if slug not in hub_ir_canon: missing_hub.append(row) if slug not in local_ir_canon and slug not in hub_ir_canon: missing_local.append(row) return { "n_sources": len(sources), "n_hub_ir": len(hub_ir), "n_local_ir": len(local_ir), "n_catalog": len(all_countries()), "excluded": excluded, "alias_sources": aliases, "crosswalk": static_crosswalk_coverage(), "missing_justicedao": missing_hub, "missing_local_and_hub": missing_local, "local_only": sorted(local_ir_canon - hub_ir_canon), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475"""DuckDB views over country-laws sparse GraphRAG parquet shards.
Published artifacts are ZSTD parquet (SkillCenter / publicus-ir family).Query and large-corpus neighbor generation read those shards through DuckDBinstead of loading them into pandas or SQLite."""
from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Any
import pandas as pd
K1 = 1.2B = 0.75TITLE_WEIGHT = 5.0BODY_WEIGHT = 1.0MAX_QUERY_TERMS = 64
VIEWS = ( ("corpus", "data/corpus/*.parquet"), ("bm25_documents", "data/bm25/documents/*.parquet"), ("bm25_postings", "data/bm25/postings/*.parquet"), ("graph_nodes", "data/graph/nodes/*.parquet"), ("graph_edges", "data/graph/edges/*.parquet"), # Shared hf_graphrag layout (US Code / state laws / FR). ("graph_in", "data/graph/adjacency/in/*.parquet"), ("graph_out", "data/graph/adjacency/out/*.parquet"), # Legacy country-laws-ir layout still on some Hub packs. ("graph_incoming", "data/graph/adjacency/incoming/*.parquet"), ("graph_outgoing", "data/graph/adjacency/outgoing/*.parquet"), ("vectors", "data/vectors/*.parquet"),)
class DuckDBStoreError(RuntimeError): """Raised when a parquet/DuckDB sparse index cannot be opened."""
def _require_duckdb(): try: import duckdb # type: ignore except ImportError as exc: raise DuckDBStoreError("duckdb is required for parquet sparse GraphRAG query") from exc return duckdb
def parquet_glob(root: Path, pattern: str) -> str: return str(Path(root) / pattern)
def connect_release(root: Path, *, database: str = ":memory:"): """Open a DuckDB connection with views over parquet shards.""" duckdb = _require_duckdb() root = Path(root) if not (root / "manifest.json").is_file(): raise DuckDBStoreError(f"release missing manifest.json: {root}") con = duckdb.connect(database) for name, pattern in VIEWS: glob = parquet_glob(root, pattern) if list(root.glob(pattern)): escaped = glob.replace("'", "''") con.execute( f"CREATE OR REPLACE VIEW {name} AS SELECT * FROM read_parquet('{escaped}')" ) return con
def load_manifest(root: Path) -> dict[str, Any]: return json.loads((Path(root) / "manifest.json").read_text(encoding="utf-8"))
def tokenize(text: str) -> list[str]: import re import unicodedata
if not text: return [] nfkd = unicodedata.normalize("NFKD", text) folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower() return re.findall(r"[0-9A-Za-z]+", folded)
def bm25_search(root: Path, query: str, top_k: int = 10) -> list[dict[str, Any]]: """Okapi BM25 over parquet posting shards via DuckDB UNNEST.""" terms = tokenize(query)[:MAX_QUERY_TERMS] if not terms: return [] manifest = load_manifest(root) avgdl = float((manifest.get("bm25") or {}).get("average_document_length") or 1.0) or 1.0 con = connect_release(root) try: tables = { r[0] for r in con.execute( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'" ).fetchall() } if "bm25_postings" not in tables or "bm25_documents" not in tables: raise DuckDBStoreError("release is missing BM25 parquet shards") placeholders = ", ".join(["?"] * len(terms)) sql = f""" WITH exploded AS ( SELECT unnest(document_indices) AS document_index, unnest(title_frequencies) AS title_tf, unnest(body_frequencies) AS body_tf, unnest(document_lengths) AS dl, idf FROM bm25_postings WHERE term IN ({placeholders}) ), scored AS ( SELECT document_index, SUM( idf * ( ( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf ) * ({K1} + 1.0) ) / ( ( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf ) + {K1} * (1.0 - {B} + {B} * (dl / {avgdl})) ) ) AS score FROM exploded GROUP BY document_index ) SELECT s.document_index, s.score, d.entry_cid, d.title, d.record_type FROM scored s JOIN bm25_documents d USING (document_index) ORDER BY s.score DESC, s.document_index LIMIT ? """ rows = con.execute(sql, [*terms, int(top_k)]).fetchall() cols = [ "document_index", "score", "entry_cid", "title", "record_type", ] return [dict(zip(cols, row)) for row in rows] finally: con.close()
def cite_search( root: Path, citation: str, *, cite_format: str = "any", limit: int = 25,) -> list[dict[str, Any]]: """Look up corpus rows by Bluebook, official cite, or normalized cite_key.""" from .citations import normalize_cite_key
needle = (citation or "").strip() if not needle: return [] key = normalize_cite_key(needle) con = connect_release(root) try: tables = { r[0] for r in con.execute( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'" ).fetchall() } if "corpus" not in tables: raise DuckDBStoreError("release is missing corpus parquet shards") cols = [ r[1] for r in con.execute( "SELECT table_schema, column_name FROM information_schema.columns " "WHERE table_schema = 'main' AND table_name = 'corpus'" ).fetchall() ] wanted = [ "entry_cid", "record_type", "title", "instrument_title", "article_number", "official_citation", "bluebook_citation", "cite_key", "citation_status", "source_url", ] select = ", ".join(c for c in wanted if c in cols) or "*" clauses = [] params: list[Any] = [] fmt = (cite_format or "any").strip().lower() if fmt in {"any", "bluebook"} and "bluebook_citation" in cols: clauses.append("lower(coalesce(bluebook_citation, '')) = lower(?)") params.append(needle) if fmt in {"any", "official"} and "official_citation" in cols: clauses.append("lower(coalesce(official_citation, '')) = lower(?)") params.append(needle) if "cite_key" in cols and key: clauses.append("cite_key = ?") params.append(key) if not clauses: return [] sql = f"SELECT {select} FROM corpus WHERE {' OR '.join(clauses)} LIMIT ?" params.append(int(limit)) rows = con.execute(sql, params).fetchall() names = [c for c in wanted if c in cols] if select != "*" else list(cols) return [dict(zip(names, row)) for row in rows] finally: con.close()
def graph_neighbors( root: Path, node_cid: str, *, direction: str = "both", limit: int = 25,) -> list[dict[str, Any]]: """Adjacency lookup over parquet shards via DuckDB.""" aliases = { "both": ("in", "out", "incoming", "outgoing"), "in": ("in", "incoming"), "out": ("out", "outgoing"), "incoming": ("in", "incoming"), "outgoing": ("out", "outgoing"), } dirs = aliases.get(direction, (direction,)) con = connect_release(root) try: tables = { r[0] for r in con.execute( "SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'" ).fetchall() } hits: list[dict[str, Any]] = [] for d in dirs: view = { "in": "graph_in", "out": "graph_out", "incoming": "graph_incoming", "outgoing": "graph_outgoing", }.get(d, d) if view not in tables: continue rows = con.execute( f""" SELECT node_cid, neighbor_cids, edge_types, scores FROM {view} WHERE node_cid = ? """, [node_cid], ).fetchall() for node, neighs, types, scores in rows: neighs = list(neighs or []) types = list(types or []) scores = list(scores or []) for i, neigh in enumerate(neighs): hits.append( { "direction": d, "node_cid": node, "neighbor_cid": neigh, "edge_type": types[i] if i < len(types) else "", "score": scores[i] if i < len(scores) else None, } ) hits.sort(key=lambda r: (-(r["score"] or 0), str(r["neighbor_cid"]))) return hits[: int(limit)] finally: con.close()
def build_fts_index( corpus_parquet: Path, duckdb_path: Path, expected: int, *, log: Any | None = None,) -> Path: """Load corpus parquet into DuckDB and create an FTS index (no SQLite).""" duckdb = _require_duckdb() duckdb_path = Path(duckdb_path) duckdb_path.parent.mkdir(parents=True, exist_ok=True) if duckdb_path.exists(): duckdb_path.unlink() escaped = str(Path(corpus_parquet).resolve()).replace("'", "''") con = duckdb.connect(str(duckdb_path)) try: con.execute( f""" CREATE TABLE documents AS SELECT CAST(document_index AS INTEGER) AS document_index, CAST(entry_cid AS VARCHAR) AS entry_cid, CAST(COALESCE(title, '') AS VARCHAR) AS title, CAST(COALESCE(body, '') AS VARCHAR) AS body FROM read_parquet('{escaped}') """ ) n = int(con.execute("SELECT COUNT(*) FROM documents").fetchone()[0]) if n != int(expected): raise DuckDBStoreError(f"DuckDB corpus rows {n} != expected {expected}") con.execute("INSTALL fts") con.execute("LOAD fts") con.execute( "PRAGMA create_fts_index('documents', 'document_index', 'title', 'body', " "stemmer='porter', stopwords='english', ignore='(\\.+)', strip_accents=1, lower=1)" ) if log: log(f"duckdb fts ready n={n} path={duckdb_path}") finally: con.close() return duckdb_path
def stream_neighbors_to_parquet( duckdb_path: Path, spill: Path, n_docs: int, *, k: int = 8, shard: int = 5000, batch: int = 256, resume: bool = True, log: Any | None = None,) -> list[Path]: """Stream DuckDB FTS neighbors into flattened neighbor_*.parquet shards.""" duckdb = _require_duckdb() spill = Path(spill) spill.mkdir(parents=True, exist_ok=True) existing = sorted(spill.glob("neighbors_*.parquet")) buf_start = 0 shard_paths: list[Path] = [] if resume and existing: covered = 0 for path in existing: parts = path.stem.split("_") try: start_i, end_i = int(parts[1]), int(parts[2]) except (IndexError, ValueError): continue if start_i != covered: break shard_paths.append(path) covered = end_i buf_start = covered if buf_start >= n_docs: if log: log(f"neighbors resume complete {buf_start}/{n_docs}") return shard_paths for path in existing: if path not in shard_paths: path.unlink(missing_ok=True) else: for path in existing: path.unlink(missing_ok=True)
con = duckdb.connect(str(duckdb_path), read_only=True) con.execute("LOAD fts") rows_buf: list[dict[str, Any]] = [] shard_start = buf_start last_idx = buf_start - 1 done = buf_start try: while True: batch_rows = con.execute( "SELECT document_index, title, body FROM documents " "WHERE document_index > ? ORDER BY document_index LIMIT ?", [last_idx, batch], ).fetchall() if not batch_rows: break for di, title, body in batch_rows: di = int(di) query = (str(title or "").strip() or str(body or "")[:800]).strip() hits: list[tuple[int, float]] = [] if query: hits = con.execute( "SELECT document_index, " "fts_main_documents.match_bm25(document_index, ?) AS score " "FROM documents " "WHERE document_index != ? AND score IS NOT NULL " "ORDER BY score DESC, document_index " "LIMIT ?", [query, di, int(k)], ).fetchall() for neigh_i, score in hits: rows_buf.append( { "source_index": di, "neighbor_index": int(neigh_i), "score": float(score or 0.0), } ) last_idx = di done += 1 if (di + 1 - shard_start) >= shard: end = di + 1 path = spill / f"neighbors_{shard_start:06d}_{end:06d}.parquet" pd.DataFrame(rows_buf).to_parquet(path, index=False) shard_paths.append(path) rows_buf = [] shard_start = end if log: log(f"neighbors parquet shard {path.name}") if done % 5_000 == 0 and log: log(f"duckdb neighbors {done}/{n_docs}") if shard_start < n_docs: path = spill / f"neighbors_{shard_start:06d}_{n_docs:06d}.parquet" pd.DataFrame(rows_buf).to_parquet(path, index=False) shard_paths.append(path) if log: log(f"duckdb neighbors done={done} shards={len(shard_paths)}") return shard_paths finally: con.close()
def iter_neighbor_parquet_shards(spill: Path) -> Any: """Yield (start_index, list-of-neighbor-lists) from parquet shards.""" import pandas as pd
paths = sorted(Path(spill).glob("neighbors_*.parquet")) for path in paths: parts = path.stem.split("_") start_i = int(parts[1]) end_i = int(parts[2]) frame = pd.read_parquet(path) part: list[list] = [[] for _ in range(max(0, end_i - start_i))] if not frame.empty: for rec in frame.itertuples(index=False): src = int(rec.source_index) offset = src - start_i if 0 <= offset < len(part): part[offset].append( (int(rec.neighbor_index), float(rec.score), []) ) yield start_i, part
def materialize_corpus_duckdb(corpus_parquet: Path, duckdb_path: Path) -> Path: """Load a corpus parquet file into a persistent DuckDB database.""" duckdb = _require_duckdb() duckdb_path = Path(duckdb_path) duckdb_path.parent.mkdir(parents=True, exist_ok=True) if duckdb_path.exists(): duckdb_path.unlink() con = duckdb.connect(str(duckdb_path)) try: con.execute( """ CREATE TABLE documents AS SELECT CAST(document_index AS INTEGER) AS document_index, CAST(entry_cid AS VARCHAR) AS entry_cid, CAST(title AS VARCHAR) AS title, CAST(body AS VARCHAR) AS body FROM read_parquet(?) """, [str(corpus_parquet)], ) con.execute("CREATE INDEX documents_idx ON documents(document_index)") finally: con.close() return duckdb_path123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350"""Property graph: entry nodes, facet nodes, BM25_NEIGHBOR_OF k=8, ARTICLE_OF, ELI."""
from __future__ import annotations
from collections import defaultdictfrom typing import Any
import pandas as pd
from . import EDGE_IDENTITY_SCHEMA, FACET_IDENTITY_SCHEMA, SCHEMA_VERSIONfrom .cidutil import cid_of_json
# Facet kinds requested by the SkillCenter-style country-laws graph:# jurisdiction, language, instrument/law, source, status.FACET_FIELDS = ( ("jurisdiction", "HAS_JURISDICTION", "jurisdiction"), ("language", "HAS_LANGUAGE", "language"), ("instrument", "HAS_INSTRUMENT", "instrument_id"), ("source", "HAS_SOURCE", "source_type"), ("status", "HAS_STATUS", "law_status"),)ADJ_POINTERS_PER_ROW = 4096ADJ_POINTERS_PER_SHARD = 8192_LABEL_MAX = 4096
def _graph_label(text: str, fallback: str) -> str: """Node labels are capped at 4096 characters. The full value stays in properties.""" cleaned = str(text or "").replace("\x00", "").strip() or fallback if len(cleaned) > _LABEL_MAX: return cleaned[: _LABEL_MAX - 3] + "..." return cleaned
def _facet_cid(kind: str, value: str) -> str: """CIDv1 raw sha2-256 of sorted JSON {kind, schema, value}.""" return cid_of_json( { "kind": kind, "schema": FACET_IDENTITY_SCHEMA, "value": value, } )
def _edge_cid(source: str, edge_type: str, target: str) -> str: return cid_of_json( { "edge_type": edge_type, "schema": EDGE_IDENTITY_SCHEMA, "source": source, "target": target, } )
def build_graph( corpus: pd.DataFrame, neighbors: list[list[tuple]],) -> dict[str, Any]: nodes: list[dict[str, Any]] = [] edges: list[dict[str, Any]] = [] seen_facets: set[str] = set() cid_by_idx = corpus["entry_cid"].tolist()
# Law identity nodes (targets of ARTICLE_OF when the parent is not a corpus entry). law_nodes: dict[str, dict[str, Any]] = {} entry_by_instrument: dict[str, str] = {} for rec in corpus.itertuples(index=False): law_cid = str(getattr(rec, "law_cid", "") or "") instrument_id = str(getattr(rec, "instrument_id", "") or "") if getattr(rec, "record_type", "") == "law" and instrument_id and rec.entry_cid: entry_by_instrument.setdefault(instrument_id, rec.entry_cid) if not law_cid or law_cid in law_nodes: continue law_nodes[law_cid] = { "node_cid": law_cid, "node_type": "law", "entry_cid": "", "label": _graph_label(getattr(rec, "instrument_title", None) or instrument_id, instrument_id), "properties_json": _json( { "instrument_id": instrument_id, "instrument_title": str(getattr(rec, "instrument_title", "") or ""), "jurisdiction": str(getattr(rec, "jurisdiction", "") or ""), "language": str(getattr(rec, "language", "") or ""), "law_cid": law_cid, } ), "schema_version": SCHEMA_VERSION, }
for law_node in law_nodes.values(): nodes.append(law_node)
for rec in corpus.itertuples(index=False): if rec.record_type == "law": node_type = "law_entry" elif rec.record_type == "notice": node_type = "notice" else: node_type = "article" title = getattr(rec, "title", None) or getattr(rec, "instrument_title", None) or rec.source_id nodes.append( { "node_cid": rec.entry_cid, "node_type": node_type, "entry_cid": rec.entry_cid, "label": _graph_label(title or rec.source_id, str(rec.source_id)), "properties_json": _props_tuple(rec), "schema_version": SCHEMA_VERSION, } ) src = rec.entry_cid row_map = rec._asdict() if hasattr(rec, "_asdict") else {}
for kind, edge_type, col in FACET_FIELDS: value = str(row_map.get(col) or "").strip() if not value: continue fc = _facet_cid(kind, value) if fc not in seen_facets: seen_facets.add(fc) nodes.append( { "node_cid": fc, "node_type": f"facet_{kind}", "entry_cid": "", "label": _graph_label(f"{kind}:{value}", kind), "properties_json": _json({"kind": kind, "value": value}), "schema_version": SCHEMA_VERSION, } ) edges.append(_edge(src, edge_type, fc, "facet", 1.0, {"facet": kind, "value": value}))
# ELI / identifier links — only values present in the source, never invented. eli = str(row_map.get("eli") or "").strip() if eli: fc = _facet_cid("eli", eli) if fc not in seen_facets: seen_facets.add(fc) nodes.append( { "node_cid": fc, "node_type": "facet_eli", "entry_cid": "", "label": _graph_label(f"eli:{eli}", "eli"), "properties_json": _json({"kind": "eli", "value": eli}), "schema_version": SCHEMA_VERSION, } ) edges.append(_edge(src, "IDENTIFIED_BY_ELI", fc, "identifier", 1.0, {"eli": eli})) ident = str(row_map.get("official_identifier") or row_map.get("identifier") or "").strip() if ident and ident != eli: fc = _facet_cid("identifier", ident) if fc not in seen_facets: seen_facets.add(fc) nodes.append( { "node_cid": fc, "node_type": "facet_identifier", "entry_cid": "", "label": _graph_label(f"identifier:{ident}", "identifier"), "properties_json": _json({"kind": "identifier", "value": ident}), "schema_version": SCHEMA_VERSION, } ) edges.append( _edge(src, "IDENTIFIED_BY", fc, "identifier", 1.0, {"identifier": ident}) )
law_cid = str(row_map.get("law_cid") or "") instrument_id = str(row_map.get("instrument_id") or "") if rec.record_type in {"article", "section"}: parent = entry_by_instrument.get(instrument_id) or law_cid if parent and parent != rec.entry_cid: edges.append( _edge( rec.entry_cid, "ARTICLE_OF", parent, "structural", 1.0, { "instrument_id": instrument_id, "article_number": row_map.get("article_number"), }, ) ) elif law_cid and rec.entry_cid != law_cid: # Law-level corpus unit still points at its instrument identity node. edges.append( _edge( rec.entry_cid, "HAS_INSTRUMENT", law_cid, "structural", 1.0, {"instrument_id": instrument_id}, ) )
for i, neigh in enumerate(neighbors): src = cid_by_idx[i] for item in neigh: if len(item) == 3: j, score, terms = item else: j, score = item[0], item[1] terms = [] tgt = cid_by_idx[int(j)] edges.append( _edge( src, "BM25_NEIGHBOR_OF", tgt, "bm25-okapi", float(score), {"k": 8, "neighbor_index": int(j)}, matched_terms=list(terms), ) )
nodes_df = pd.DataFrame(nodes).drop_duplicates("node_cid").reset_index(drop=True) nodes_df = nodes_df.sort_values(["node_type", "node_cid"]).reset_index(drop=True) edges_df = pd.DataFrame(edges) if not edges_df.empty: edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True) edges_df = edges_df.sort_values(["edge_type", "source_cid", "target_cid"]).reset_index(drop=True)
node_type = {r["node_cid"]: r["node_type"] for r in nodes_df.to_dict("records")} incoming, outgoing = _adjacency(edges_df, node_type) return { "nodes": nodes_df, "edges": edges_df, "incoming": incoming, "outgoing": outgoing, "stats": { "n_nodes": int(len(nodes_df)), "n_edges": int(len(edges_df)), "n_doc_nodes": int(nodes_df["node_type"].isin(["law_entry", "article", "law"]).sum()), "n_facet_nodes": int(nodes_df["node_type"].astype(str).str.startswith("facet_").sum()), "edge_types": sorted(edges_df["edge_type"].unique().tolist()) if not edges_df.empty else [], }, }
def _json(obj: dict) -> str: import json
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
def _props_tuple(rec: Any) -> str: keys = [ "record_type", "instrument_id", "instrument_title", "law_cid", "article_number", "article_title", "jurisdiction", "language", "source_url", "snapshot_date", "coverage", "license", "collector", "source_id", "eli", "law_status", "source_type", ] d = rec._asdict() if hasattr(rec, "_asdict") else {} out = {} for k in keys: v = d.get(k, "") if v is None or (isinstance(v, float) and pd.isna(v)): v = "" out[k] = str(v) return _json(out)
def _edge( src: str, etype: str, tgt: str, method: str, score: float, props: dict, matched_terms: list[str] | None = None,) -> dict[str, Any]: import json
terms = matched_terms or [] return { "edge_cid": _edge_cid(src, etype, tgt), "edge_type": etype, "source_cid": src, "target_cid": tgt, "retrieval_method": method, "score": float(score), "query_terms_json": json.dumps(terms, ensure_ascii=False, separators=(",", ":")), "matched_terms": terms, "properties_json": _json({k: v for k, v in props.items() if v is not None}), "schema_version": SCHEMA_VERSION, }
def _adjacency(edges: pd.DataFrame, node_type: dict[str, str]) -> tuple[pd.DataFrame, pd.DataFrame]: out_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list) in_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list) if edges is None or edges.empty: return pd.DataFrame(), pd.DataFrame() for rec in edges.itertuples(index=False): score = float(rec.score) if rec.score == rec.score else float("-inf") out_map[rec.source_cid].append((score, rec.target_cid, rec.edge_type, rec.edge_cid)) in_map[rec.target_cid].append((score, rec.source_cid, rec.edge_type, rec.edge_cid))
def pages(mapping: dict[str, list], direction: str) -> pd.DataFrame: rows = [] for node, items in mapping.items(): items = sorted(items, key=lambda t: (-t[0] if t[0] == t[0] else float("inf"), t[1])) total = len(items) page_size = ADJ_POINTERS_PER_ROW n_pages = max(1, (total + page_size - 1) // page_size) for p in range(n_pages): chunk = items[p * page_size : (p + 1) * page_size] rows.append( { "direction": direction, "node_cid": node, "page_index": p, "page_count": n_pages, "neighbor_count": len(chunk), "total_neighbor_count": total, "neighbor_cids": [t[1] for t in chunk], "neighbor_node_types": [node_type.get(t[1], "") for t in chunk], "edge_types": [t[2] for t in chunk], "edge_cids": [t[3] for t in chunk], "retrieval_methods": ["graph"] * len(chunk), "scores": [t[0] if t[0] != float("-inf") else None for t in chunk], "schema_version": SCHEMA_VERSION, } ) if not rows: return pd.DataFrame() return pd.DataFrame(rows).sort_values(["node_cid", "page_index"]).reset_index(drop=True)
return pages(in_map, "incoming"), pages(out_map, "outgoing")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213"""Pull operative legal text out of municipal HTML chunks.
The scrapers store a page as ``<div class="chunk-content">``. The flattened``text`` column still starts with letterhead, attendance rolls, and coversheets, and the embedder only reads the first 4,000 characters of the body.This keeps the operative text and leaves a page unchanged when the cut woulddrop most of it."""
from __future__ import annotations
import refrom html.parser import HTMLParser
_LEGAL = re.compile( r"(?i)(" r"§|" r"\bart\.?\s*\d|" r"\barticles?\s+\d|" r"\bartikel\b|" r"\bpasal\b|" r"\bayat\b|" r"\bmenimbang\b|" r"\bmemutuskan\b|" r"\bmenetapkan\b|" r"\bperaturan\b|" r"\bconsidérant\b|" r"\bdécide\b|" r"\bdélibère\b|" r"\bvu (?:le|la|les|l['’])|" r"\brundschreiben\b|" r"\bverordnung\b|" r"\bdecreto\b|" r"\bdelibera\b|" r"\brèglement\b|" r"\barrêté\b|" r"\brésumé\s*:" r")")_EMAIL = re.compile(r"\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b")_URL = re.compile(r"(?i)\b(?:https?://|www\.)\S+")_PHONE = re.compile( r"(?i)\b(?:tel\.?|telefon|téléphone|telephone|cellulaire|télécopieur|telefax|fax)\b")_TAX = re.compile( r"(?i)\b(?:steuernr|mwst\.?|codice fiscale|partita iva|npwp|momsnr)\b")_POSTAL = re.compile( r"(?i)\b(?:straße|strasse|via |rue |väg|gatan|landhaus|palazzo)\b")_TOC = re.compile(r"\.{4,}\s*\d{1,4}\s*$")_PAGE = re.compile(r"^\d{1,4}$")_PAGE_PREFIX = re.compile(r"^(\d{1,3})\s+(?=[A-ZÀ-ÖØ-Þ]{4,}\b)")_LABEL = re.compile( r"(?i)^(?:" r"dokumentnamn|gäller\s+fr.*|gäller\s+t.*|diarienummer|fastställd(?:\s+av)?|" r"dokumentansvar\w*|handläggare|dokumenthistorik|version|tidigare beslut|" r"innehållsförteckning|rapporteur|secrétaire|commission|avis" r")\s*:?\s*$")_ATTEND = re.compile( r"(?i)\b(?:étaient présents|etaient présents|étaient absents|etaient absents|" r"procurations de vote|secrétaire\s*:)")_START = re.compile( r"(?i)(" r"résumé\s*:|" r"\ble présent\b|" r"\bvu (?:le|la|les|l['’])|" r"\bconsidérant\b|" r"\barticles?\s+\d|" r"\bdécide\b|" r"\brundschreiben\b|" r"\bperaturan\b|" r"\bmenimbang\b" r")")_ROLL = re.compile( r"(?i)\b(?:étaient présents|etaient présents|présidence de|" r"conseillers municipaux en exercice|procurations de vote)\b")_ROLE = re.compile( r"(?i)\b(?:kommundirektör|handläggare|utredare|föreningssamordnare|dokumentansvar)\b")_IDLINE = re.compile( r"^(?:[A-Z]{1,6}/\d{4}:\d+|\d{8}-\d+(?:\.\d+)?|\d{4}-\d{2}-\d{2})$")_EMAIL_ONLY = re.compile(r"(?i)(?:nur mittels|solo via)\s+e-?mail")
class _Paragraphs(HTMLParser): def __init__(self) -> None: super().__init__(convert_charrefs=True) self.parts: list[str] = [] self._buf: list[str] = [] self._skip = 0
def handle_starttag(self, tag, attrs): if tag in {"script", "style", "noscript"}: self._skip += 1 if tag in {"p", "br", "div", "li", "h1", "h2", "h3", "tr"} and self._skip == 0: self._flush()
def handle_endtag(self, tag): if tag in {"script", "style", "noscript"} and self._skip: self._skip -= 1 if tag in {"p", "div", "li", "tr", "h1", "h2", "h3"} and self._skip == 0: self._flush()
def handle_data(self, data): if self._skip == 0 and data: self._buf.append(data)
def _flush(self) -> None: text = re.sub(r"\s+", " ", "".join(self._buf)).strip() self._buf.clear() if text: self.parts.append(text)
def close(self): super().close() self._flush()
def _paragraphs(html: str, fallback: str) -> list[str]: if html and "<" in html: parser = _Paragraphs() try: parser.feed(html) parser.close() except Exception: parser.parts = [] if parser.parts: return parser.parts raw = fallback or html or "" parts = [re.sub(r"\s+", " ", line).strip() for line in raw.splitlines()] return [part for part in parts if part]
def _is_chrome(text: str) -> bool: if not text: return True if _PAGE.fullmatch(text) or _TOC.search(text) or _LABEL.fullmatch(text): return True if _EMAIL_ONLY.search(text) and len(text) < 80: return True if _IDLINE.fullmatch(text): return True if _ROLE.search(text) and len(text) < 140 and _LEGAL.search(text) is None: return True if _ATTEND.search(text) and _START.search(text) is None and _LEGAL.search(text) is None: return True if _LEGAL.search(text): return False if len(text) > 280: return False if _EMAIL.search(text) or _URL.search(text) or _PHONE.search(text) or _TAX.search(text): return True if _POSTAL.search(text) and len(text) < 140: return True return False
def _leading_cover(text: str) -> bool: """Short cover-sheet line with no operative marker.""" if _LEGAL.search(text) or _is_chrome(text): return False if len(text) > 90: return False words = text.split() return len(words) <= 14
def _trim_blob(text: str) -> str: match = _START.search(text) if match is None or match.start() < 60: return text head = text[: match.start()] if _ROLL.search(head) or _ATTEND.search(head) or re.search(r"(?i)\b(?:mairie|rapporteur)\b", head): return text[match.start() :].strip() return text
def _strip_page_prefix(text: str) -> str: match = _PAGE_PREFIX.match(text) if match is None or int(match.group(1)) > 40: return text return text[match.end() :].strip()
def extract_municipal_legal_text(html: str, fallback: str = "") -> str: """Return operative text. ``fallback`` is the flattened page text.""" base = re.sub(r"\s+", " ", (fallback or "")).strip() paragraphs = [_trim_blob(part) for part in _paragraphs(html or "", fallback or "")] start = 0 while start < len(paragraphs) and ( _is_chrome(paragraphs[start]) or _leading_cover(paragraphs[start]) ): start += 1 kept: list[str] = [] for part in paragraphs[start:]: if _is_chrome(part): continue part = _strip_page_prefix(part) if part: kept.append(part) cleaned = "\n".join(kept).strip() plain = (fallback or "").strip() if not cleaned: return plain if plain and len(plain) > 400 and len(cleaned) < int(0.2 * len(plain)): return plain return cleaned123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562"""CID-keyed incremental GraphRAG rebuild for country-laws IR.
Follows the US Code / patent persistent-index pattern:
* ``entry_cid`` is the durable identity (not positional ``document_index``).* A matching source revision + parquet digest is a no-op.* Unchanged CIDs reuse embeddings; BM25/graph are rebuilt from the current corpus because ``document_index`` is a shard pointer, not an identity.* Delta refresh is never labeled equivalent to a full rebuild.
Public Hub reads stay anonymous. Publication to ``justicedao/*`` is a separategated upload step."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom enum import Enumimport jsonfrom pathlib import Pathfrom typing import Any, Iterable, Mapping
import pandas as pd
from . import SCHEMA_VERSION
class RebuildKind(str, Enum): UNCHANGED = "unchanged" DELTA_REFRESH = "delta_refresh" FULL_REBUILD = "full_rebuild"
@classmethod def coerce(cls, value: Any) -> "RebuildKind": if isinstance(value, RebuildKind): return value text = str(value or "").strip().lower().replace("-", "_") aliases = { "skip": cls.UNCHANGED, "noop": cls.UNCHANGED, "none": cls.UNCHANGED, "delta": cls.DELTA_REFRESH, "incremental": cls.DELTA_REFRESH, "partial": cls.DELTA_REFRESH, "full": cls.FULL_REBUILD, "rebuild": cls.FULL_REBUILD, "force": cls.FULL_REBUILD, } if text in aliases: return aliases[text] for kind in cls: if kind.value == text or kind.name.lower() == text: return kind raise ValueError(f"unknown rebuild kind: {value!r}")
class BuildMode(str, Enum): AUTO = "auto" FULL = "full" DELTA = "delta"
@classmethod def coerce(cls, value: Any) -> "BuildMode": if isinstance(value, BuildMode): return value text = str(value or "").strip().lower().replace("-", "_") aliases = { "incremental": cls.DELTA, "diff": cls.DELTA, "rebuild": cls.FULL, "complete": cls.FULL, } if text in aliases: return aliases[text] for mode in cls: if mode.value == text or mode.name.lower() == text: return mode raise ValueError(f"unknown build mode: {value!r}")
@dataclass(frozen=True)class CorpusDelta: added_cids: tuple[str, ...] = () removed_cids: tuple[str, ...] = () unchanged_cids: tuple[str, ...] = () prior_count: int = 0 current_count: int = 0 changed_ratio: float = 1.0 equivalent_to_full: bool = False
@property def n_added(self) -> int: return len(self.added_cids)
@property def n_removed(self) -> int: return len(self.removed_cids)
@property def n_unchanged(self) -> int: return len(self.unchanged_cids)
def to_dict(self, *, include_cids: bool = False, cid_sample: int = 8) -> dict[str, Any]: payload = { "n_added": self.n_added, "n_removed": self.n_removed, "n_unchanged": self.n_unchanged, "prior_count": self.prior_count, "current_count": self.current_count, "changed_ratio": self.changed_ratio, "equivalent_to_full": self.equivalent_to_full, } if include_cids: payload["added_cids"] = list(self.added_cids) payload["removed_cids"] = list(self.removed_cids) payload["unchanged_cids"] = list(self.unchanged_cids) else: payload["added_cids_sample"] = list(self.added_cids[:cid_sample]) payload["removed_cids_sample"] = list(self.removed_cids[:cid_sample]) return payload
@dataclass(frozen=True)class RebuildPlan: kind: RebuildKind mode: BuildMode reason: str source_revision: str prior_revision: str | None = None source_fingerprint: str = "" prior_fingerprint: str | None = None delta: CorpusDelta | None = None reuse_embeddings: bool = False skip_build: bool = False equivalent_to_full: bool = False
def to_dict(self) -> dict[str, Any]: return { "kind": self.kind.value, "mode": self.mode.value, "reason": self.reason, "source_revision": self.source_revision, "prior_revision": self.prior_revision, "source_fingerprint": self.source_fingerprint, "prior_fingerprint": self.prior_fingerprint, "delta": None if self.delta is None else self.delta.to_dict(include_cids=False), "reuse_embeddings": self.reuse_embeddings, "skip_build": self.skip_build, "equivalent_to_full": self.equivalent_to_full, "schema_version": SCHEMA_VERSION, }
@dataclassclass PriorRelease: directory: Path manifest: dict[str, Any] = field(default_factory=dict) corpus: pd.DataFrame | None = None vectors_by_cid: dict[str, list[float]] | None = None
@property def source_revision(self) -> str | None: return ( self.manifest.get("dataset_revision") or (self.manifest.get("source") or {}).get("source_revision") )
@property def fingerprint(self) -> str: return source_fingerprint_from_manifest(self.manifest)
def stamp_source_revision(manifest: dict[str, Any], new_revision: str) -> bool: """Record a new raw SHA on an unchanged release.
Entry rows can match while the endomorphosis commit moved. The gap scan compares ``dataset_revision``, so an unchanged corpus still needs that field updated or the pack stays stale forever. """
new = str(new_revision or "").strip().lower() if len(new) != 40 or any(ch not in "0123456789abcdef" for ch in new): return False old = str(manifest.get("dataset_revision") or "").strip().lower() if not old or old == new: return False manifest["dataset_revision"] = new for key in ("source", "normalization"): block = manifest.get(key) if isinstance(block, dict) and block.get("source_revision"): block["source_revision"] = new incremental = manifest.get("incremental") if isinstance(incremental, dict): incremental["source_revision"] = new fingerprint = str(incremental.get("source_fingerprint") or "") if fingerprint.startswith(old + "|"): incremental["source_fingerprint"] = new + fingerprint[len(old):] return True
def source_fingerprint(source_meta: Mapping[str, Any]) -> str: """Stable skip key: Hub SHA plus parquet digests when present.""" revision = str(source_meta.get("source_revision") or "") laws = str(source_meta.get("laws_sha256") or "") articles = str(source_meta.get("articles_sha256") or "") return f"{revision}|{laws}|{articles}"
def source_fingerprint_from_manifest(manifest: Mapping[str, Any]) -> str: revision = str( manifest.get("dataset_revision") or (manifest.get("source") or {}).get("source_revision") or "" ) sha = manifest.get("input_sha256") or {} laws = str(sha.get("laws.parquet") or "") articles = str(sha.get("articles.parquet") or "") if not laws and not articles: src = manifest.get("source") or {} laws = str(src.get("laws_sha256") or "") articles = str(src.get("articles_sha256") or "") return f"{revision}|{laws}|{articles}"
def _cid_set(frame: pd.DataFrame | None) -> set[str]: if frame is None or frame.empty or "entry_cid" not in frame.columns: return set() return {str(x) for x in frame["entry_cid"].dropna().astype(str) if str(x).strip()}
def diff_corpus( prior: pd.DataFrame | None, current: pd.DataFrame,) -> CorpusDelta: """Diff two CID-keyed corpora. Same ``entry_cid`` implies same body.""" current_cids = _cid_set(current) prior_cids = _cid_set(prior) added = tuple(sorted(current_cids - prior_cids)) removed = tuple(sorted(prior_cids - current_cids)) unchanged = tuple(sorted(current_cids & prior_cids)) current_count = int(len(current_cids)) prior_count = int(len(prior_cids)) if current_count == 0: ratio = 1.0 if prior_count else 0.0 else: ratio = 1.0 - (len(unchanged) / float(current_count)) equivalent = prior_count == 0 or (not unchanged and current_count > 0) return CorpusDelta( added_cids=added, removed_cids=removed, unchanged_cids=unchanged, prior_count=prior_count, current_count=current_count, changed_ratio=float(ratio), equivalent_to_full=equivalent, )
def plan_rebuild( *, mode: BuildMode | str, source_meta: Mapping[str, Any], prior: PriorRelease | None, current_corpus: pd.DataFrame | None = None, force: bool = False, rebuild_stub_vectors: bool = True, compare_normalized: bool = False,) -> RebuildPlan: """Decide skip / delta / full from source fingerprints and CID overlap.""" mode = BuildMode.coerce(mode) revision = str(source_meta.get("source_revision") or "") fingerprint = source_fingerprint(source_meta) prior_revision = prior.source_revision if prior is not None else None prior_fp = prior.fingerprint if prior is not None else None
if force or mode is BuildMode.FULL: delta = None if current_corpus is not None and prior is not None: delta = diff_corpus(prior.corpus, current_corpus) return RebuildPlan( kind=RebuildKind.FULL_REBUILD, mode=mode, reason="operator forced full rebuild" if force else "build mode is full", source_revision=revision, prior_revision=prior_revision, source_fingerprint=fingerprint, prior_fingerprint=prior_fp, delta=delta, reuse_embeddings=False, skip_build=False, equivalent_to_full=True, )
if prior is None: return RebuildPlan( kind=RebuildKind.FULL_REBUILD, mode=mode, reason="no prior release", source_revision=revision, prior_revision=None, source_fingerprint=fingerprint, prior_fingerprint=None, delta=None, reuse_embeddings=False, skip_build=False, equivalent_to_full=True, )
prior_vector_status = str( ((prior.manifest.get("vector") or {}) if prior.manifest else {}).get("status") or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status") or "" ).strip().lower() stub_vectors = rebuild_stub_vectors and prior_vector_status in { "stub", "stub_missing_encoder", "incomplete", "partial", }
fingerprint_match = bool(prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors) if fingerprint_match and not (compare_normalized and current_corpus is not None): return RebuildPlan( kind=RebuildKind.UNCHANGED, mode=mode, reason="source revision and parquet digests match prior release", source_revision=revision, prior_revision=prior_revision, source_fingerprint=fingerprint, prior_fingerprint=prior_fp, delta=CorpusDelta( unchanged_cids=tuple(sorted(_cid_set(prior.corpus))), prior_count=int(len(_cid_set(prior.corpus))), current_count=int(len(_cid_set(prior.corpus))), changed_ratio=0.0, equivalent_to_full=False, ), reuse_embeddings=True, skip_build=True, equivalent_to_full=False, )
delta = None if current_corpus is not None: delta = diff_corpus(prior.corpus, current_corpus) if delta.n_added == 0 and delta.n_removed == 0 and not stub_vectors: return RebuildPlan( kind=RebuildKind.UNCHANGED, mode=mode, reason="normalized entry_cids match the prior release", source_revision=revision, prior_revision=prior_revision, source_fingerprint=fingerprint, prior_fingerprint=prior_fp, delta=delta, reuse_embeddings=True, skip_build=True, equivalent_to_full=False, ) if delta.equivalent_to_full: return RebuildPlan( kind=RebuildKind.FULL_REBUILD, mode=mode, reason="CID overlap is empty; delta equals a full rebuild", source_revision=revision, prior_revision=prior_revision, source_fingerprint=fingerprint, prior_fingerprint=prior_fp, delta=delta, reuse_embeddings=False, skip_build=False, equivalent_to_full=True, )
reason = ( "source fingerprint matches but vectors are stub/incomplete; encode missing CIDs" if stub_vectors and prior_fp == fingerprint else "source changed; reuse embeddings for unchanged entry_cids" ) return RebuildPlan( kind=RebuildKind.DELTA_REFRESH, mode=mode, reason=reason, source_revision=revision, prior_revision=prior_revision, source_fingerprint=fingerprint, prior_fingerprint=prior_fp, delta=delta, reuse_embeddings=True, skip_build=False, equivalent_to_full=False, )
def _read_sharded_parquet(directory: Path) -> pd.DataFrame | None: if not directory.is_dir(): return None parts = sorted(directory.glob("part-*.parquet")) if not parts: parts = sorted(p for p in directory.rglob("*.parquet") if p.is_file()) if not parts: return None frames = [pd.read_parquet(p) for p in parts] return pd.concat(frames, ignore_index=True) if frames else None
def load_release_manifest(release_dir: Path) -> dict[str, Any]: path = Path(release_dir) / "manifest.json" if not path.is_file(): return {} try: data = json.loads(path.read_text(encoding="utf-8")) except Exception: return {} return data if isinstance(data, dict) else {}
def load_release_corpus(release_dir: Path) -> pd.DataFrame | None: release_dir = Path(release_dir) corpus = _read_sharded_parquet(release_dir / "data" / "corpus") if corpus is not None: return corpus checkpoint = release_dir / "corpus.parquet" if checkpoint.is_file(): return pd.read_parquet(checkpoint) return None
def embeddings_from_vector_table(frame: pd.DataFrame) -> dict[str, list[float]]: out: dict[str, list[float]] = {} if frame is None or frame.empty: return out if "entry_cid" not in frame.columns or "embedding" not in frame.columns: return out for rec in frame.itertuples(index=False): cid = str(getattr(rec, "entry_cid", "") or "") emb = getattr(rec, "embedding", None) if not cid or emb is None: continue if isinstance(emb, float) and pd.isna(emb): continue try: values = [float(x) for x in list(emb)] except Exception: continue if not values: continue out[cid] = values return out
def load_release_vectors_by_cid(release_dir: Path) -> dict[str, list[float]]: frame = _read_sharded_parquet(Path(release_dir) / "data" / "vectors") if frame is None: return {} return embeddings_from_vector_table(frame)
def load_prior_release(release_dir: Path | None) -> PriorRelease | None: if release_dir is None: return None directory = Path(release_dir) if not directory.is_dir(): return None manifest = load_release_manifest(directory) if not manifest and not (directory / "data").is_dir(): return None return PriorRelease( directory=directory, manifest=manifest, corpus=load_release_corpus(directory), vectors_by_cid=None, )
def load_embedding_cache(path: Path) -> dict[str, list[float]]: if not path.is_file(): return {} try: frame = pd.read_parquet(path) except Exception: return {} return embeddings_from_vector_table(frame)
def save_embedding_cache( path: Path, by_cid: Mapping[str, Iterable[float]], *, model_name: str, dimension: int,) -> None: path.parent.mkdir(parents=True, exist_ok=True) rows = [ { "entry_cid": cid, "embedding": list(vec), "model_name": model_name, "dimension": int(dimension), } for cid, vec in sorted(by_cid.items()) ] frame = pd.DataFrame(rows) tmp = path.with_suffix(path.suffix + ".tmp") frame.to_parquet(tmp, index=False) tmp.replace(path)
def merge_embedding_maps( *maps: Mapping[str, list[float]] | None,) -> dict[str, list[float]]: merged: dict[str, list[float]] = {} for mapping in maps: if not mapping: continue merged.update(mapping) return merged
def fetch_hub_prior( slug: str, dest: Path | None = None, *, cache_root: Path | None = None,) -> Path | None: """Download JusticeDAO corpus+vector shards to use as an incremental parent.
Missing Hub IR is not an error: first-time countries return ``None``. """ from huggingface_hub import snapshot_download from huggingface_hub.errors import RepositoryNotFoundError
from .auth import operator_token, public_token from .catalog import target_repo
root = Path(cache_root) if cache_root is not None else ( Path.home() / ".ipfs_datasets" / "country-laws-ir" / "cache" / "hub-ir" ) dest = Path(dest) if dest is not None else (root / slug) dest.mkdir(parents=True, exist_ok=True) repo = target_repo(slug) try: snapshot_download( repo_id=repo, repo_type="dataset", local_dir=str(dest), allow_patterns=[ "manifest.json", "data/vectors/**", "data/corpus/**", "indexes/vector_chunks.parquet", ], token=operator_token() or public_token(), ) except RepositoryNotFoundError: return None except Exception: if not (dest / "manifest.json").is_file(): return None raise if not (dest / "manifest.json").is_file(): return None return dest123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442"""Copy one code name onto sibling rows of the same source law.
A whole-line code name is inherited only when that law contains exactly onesuch name. A title that already names a loi or an ordonnance is left as itis. Hierarchy numbers are copied only into empty locator fields, and onlyfrom a heading that appears once in that law. Statute text is not rewritten.Nothing is invented, downloaded, or uploaded, and the assembled corpus isonly read."""
from __future__ import annotations
import jsonimport refrom pathlib import Pathfrom typing import Iterable, Mapping
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.national_directory import ( _HEADING_KIND, _HEADING_LINE, _ROMAN, _TITLE_LOI, _fold,)from ipfs_datasets_py.processors.legal_scrapers.world_law.schema import LEGAL_RECORD_FIELDS
INHERIT_VERSION = "instrument-inherit/v1"_MAX_ATOMS = 250_000_NORMALIZER = "country-source-admit/v1"_HEADING_KEYS = ("book", "title", "chapter", "part", "section")_CODE_LINE = re.compile( r"(?m)^CODE [A-ZÀÂÉÈÊËÎÏÔÙÛÜÇŒ][A-ZÀÂÉÈÊËÎÏÔÙÛÜÇŒ '&-]{4,}$")_CODE_CAPTION = re.compile(r"(?i)^(code\b(?:[^\n>]{0,160}?))\s*>\s*article\b")_CAPTION_TITLE = re.compile( r"(?i)^(?:" r"article|art\.?|section|sec\.?|livre|titre|titulo|título|chapitre|chapter|partie|part|title" r")" r"(?:[ \t]*[-–—.]?[ \t]*(?:" r"[0-9]{1,4}(?:[.\-][0-9]{1,4})?[A-Za-z]?|[IVXLCDM]{1,12}|1er" r"))?" r"[ \t]*(?:[.:\-–—]+)?[ \t]*$")
def inheritance_plan( rows: Iterable[Mapping[str, object]],) -> dict[str, tuple[str, dict[str, str]]]: """Map each law id to its single code name and its unique headings."""
codes: dict[str, set[str]] = {} headings: dict[str, dict[str, set[str]]] = {} for row in rows: law = row.get("law_id") if not isinstance(law, str) or not law.strip(): continue text = _source_text(row) names = codes.setdefault(law, set()) names.update(_CODE_LINE.findall(text)) bucket = headings.setdefault(law, {}) for line in [item.strip() for item in text.splitlines() if item.strip()][:80]: heading = _HEADING_LINE.match(line) if heading is None: continue kind = _HEADING_KIND[heading.group(1).casefold()] number = heading.group(2) number = number if number.isdigit() else number.upper() if not number.isdigit() and _ROMAN.fullmatch(number) is None: continue bucket.setdefault(kind, set()).add(number) plan: dict[str, tuple[str, dict[str, str]]] = {} for law, names in codes.items(): if len(names) != 1: continue sole = { kind: next(iter(values)) for kind, values in headings.get(law, {}).items() if len(values) == 1 and kind in _HEADING_KEYS } plan[law] = (next(iter(names)), sole) return plan
def replacement_title(title: str, text: str, law_code: str | None) -> str | None: """Return the code name to store as the record title, or None to keep it."""
if not law_code: return None label = title.strip() if _names_other_instrument(label, text): return None if not label or _CAPTION_TITLE.fullmatch(label): return law_code caption = _CODE_CAPTION.match(label) if caption and _fold(caption.group(1)) == _fold(law_code): return law_code return None
def refine_atom( record: Mapping[str, object], *, law_code: str | None, headings: Mapping[str, str],) -> dict[str, object]: """Fill a blank instrument title and empty hierarchy fields.
The returned text is the input text. A loi or ordonnance title is not replaced by the parent code. """
updated = dict(record) text = updated.get("text") if isinstance(updated.get("text"), str) else "" current = updated.get("title") if isinstance(updated.get("title"), str) else "" new_title = replacement_title(current, text, law_code) if new_title == current: new_title = None provenance, encoded = _copy_provenance(updated.get("provenance")) added: dict[str, str] = {} if provenance is not None and _accepts_hierarchy(current, text, law_code): for key in _HEADING_KEYS: value = headings.get(key, "") if not value: continue already = provenance.get(key) if isinstance(already, str) and already.strip(): continue provenance[key] = value added[key] = value _note_jsonld(provenance, new_title, added) elif provenance is not None and new_title: _note_jsonld(provenance, new_title, {}) if new_title: updated["title"] = new_title if provenance is not None and (new_title or added): updated["provenance"] = _store_provenance(provenance, encoded) if updated.get("text") != record.get("text"): raise ValueError("text") return updated
def refine_assembled_corpus( source_paths: Iterable[Path | str], assembled_dir: Path | str, dest_dir: Path | str, *, source_dataset: str, source_revision: str,) -> dict[str, object]: """Write a sibling corpus whose titles carry a same-law code name.
``assembled_dir`` must already be a finished country fill. This function does not modify it, does not download, and does not upload. """
assembled = Path(assembled_dir) destination = Path(dest_dir) _separate(assembled, destination) if not _is_sha(source_revision): raise ValueError("source_revision") report = _assembled_report(assembled) parts = sorted(assembled.glob("part-*.parquet")) if not parts: raise ValueError("assembled") total = _row_count(parts) if total < 1 or total > _MAX_ATOMS: raise ValueError("assembled") sources = [Path(path) for path in source_paths] if not sources or any(not path.is_file() for path in sources): raise ValueError("source") rows = _read_source_rows(sources) plan = inheritance_plan(rows) if not plan: return { "version": INHERIT_VERSION, "written": False, "titles_filled": 0, "headings_filled": 0, "reason": "no_sole_code", "normalizer_version": report.get("normalizer_version"), } law_by_cid = _law_by_entry_cid( rows, source_dataset=source_dataset, source_revision=source_revision, ) destination.mkdir(parents=True, exist_ok=True) for stale in destination.glob("part-*.parquet"): stale.unlink() stale_report = destination / "refine_report.json" if stale_report.exists(): stale_report.unlink() titles = 0 heading_rows = 0 unmatched = 0 written: list[str] = [] for index, part in enumerate(parts): refined: list[dict[str, object]] = [] for record in _iter_part(part): cid = record.get("entry_cid") if isinstance(record.get("entry_cid"), str) else "" law = law_by_cid.get(cid, "") code, headings = plan.get(law, (None, {})) if not law: unmatched += 1 before_title = record.get("title") before_provenance = record.get("provenance") atom = refine_atom(record, law_code=code, headings=headings if code else {}) if atom.get("text") != record.get("text") or atom.get("entry_cid") != record.get("entry_cid"): raise ValueError("text") if atom.get("content_sha256") != record.get("content_sha256"): raise ValueError("text") if atom.get("title") != before_title: titles += 1 if atom.get("provenance") != before_provenance and atom.get("title") == before_title: heading_rows += 1 elif atom.get("provenance") != before_provenance and _gained_heading(before_provenance, atom.get("provenance")): heading_rows += 1 refined.append(atom) written.append(_write_part(destination, index, refined)) summary = { "version": INHERIT_VERSION, "written": True, "source_dataset": source_dataset, "source_revision": source_revision, "atoms": total, "titles_filled": titles, "headings_filled": heading_rows, "unmatched": unmatched, "laws": len(plan), "files": [Path(path).name for path in written], "normalizer_version": report.get("normalizer_version"), } stale_report.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8") return summary
def _names_other_instrument(title: str, text: str) -> bool: if _TITLE_LOI.match(title): return True for line in text.splitlines(): if line.strip(): return _TITLE_LOI.match(line.strip()) is not None return False
def _accepts_hierarchy(title: str, text: str, law_code: str | None) -> bool: if not law_code: return False if _fold(title) == _fold(law_code): return True return replacement_title(title, text, law_code) is not None
def _source_text(row: Mapping[str, object]) -> str: body = row.get("body") if isinstance(body, str) and body: return body text = row.get("text") return text if isinstance(text, str) else ""
def _copy_provenance(value: object) -> tuple[dict[str, object] | None, bool]: if isinstance(value, str) and value.strip().startswith("{"): try: loaded = json.loads(value) except json.JSONDecodeError: return None, True if isinstance(loaded, dict): return loaded, True return None, True if isinstance(value, dict): loaded = json.loads(json.dumps(value)) if isinstance(loaded, dict): return loaded, False return None, False
def _store_provenance(provenance: Mapping[str, object], encoded: bool) -> str | dict[str, object]: if encoded: return json.dumps(provenance, sort_keys=True, ensure_ascii=False) copied = json.loads(json.dumps(provenance)) return copied if isinstance(copied, dict) else {}
def _note_jsonld(provenance: dict[str, object], name: str | None, added: Mapping[str, str]) -> None: document = provenance.get("jsonld") if not isinstance(document, dict): return before = document.get("text") if name: document["name"] = name if added: properties = document.get("additionalProperty") if not isinstance(properties, list): properties = [] document["additionalProperty"] = properties present = { item.get("propertyID") for item in properties if isinstance(item, dict) and isinstance(item.get("propertyID"), str) } for key, value in added.items(): if key in present: continue properties.append({"@type": "PropertyValue", "propertyID": key, "value": value}) if document.get("text") != before: raise ValueError("text")
def _gained_heading(before: object, after: object) -> bool: old, _old_encoded = _copy_provenance(before) new, _new_encoded = _copy_provenance(after) if old is None or new is None: return False for key in _HEADING_KEYS: previous = old.get(key) current = new.get(key) if (not isinstance(previous, str) or not previous.strip()) and isinstance(current, str) and current.strip(): return True return False
def _separate(assembled: Path, destination: Path) -> None: source = assembled.resolve() target = destination.resolve() if source == target or target.is_relative_to(source) or source.is_relative_to(target): raise ValueError("dest")
def _assembled_report(assembled: Path) -> dict[str, object]: path = assembled / "report.json" if not path.is_file(): raise ValueError("assembled") try: loaded = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as exc: raise ValueError("assembled") from exc if not isinstance(loaded, dict): raise ValueError("assembled") if loaded.get("corpus_complete") is not True: raise ValueError("assembled") if loaded.get("normalizer_version") != _NORMALIZER: raise ValueError("assembled") return loaded
def _row_count(parts: list[Path]) -> int: import pyarrow.parquet as pq
return sum(pq.ParquetFile(path).metadata.num_rows for path in parts)
def _read_source_rows(paths: list[Path]) -> list[dict[str, object]]: import pyarrow.parquet as pq
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.admit import _FILL_COLUMNS
rows: list[dict[str, object]] = [] wanted = ("law_id", *_FILL_COLUMNS) for path in paths: present = [name for name in wanted if name in pq.read_schema(path).names] if "law_id" not in present: continue parquet = pq.ParquetFile(path) for batch in parquet.iter_batches(batch_size=256, columns=present): rows.extend(batch.to_pylist()) return rows
def _law_by_entry_cid( rows: Iterable[Mapping[str, object]], *, source_dataset: str, source_revision: str,) -> dict[str, str]: from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.admit import ( _fill_row, _is_sha, admit_source_law, )
found: dict[str, str] = {} blocked: set[str] = set() for row in rows: law = row.get("law_id") if not isinstance(law, str) or not law.strip(): continue revision = row.get("source_revision") pin = revision if _is_sha(revision) else source_revision decision = admit_source_law( _fill_row(row), source_dataset=source_dataset, source_revision=pin, ) if not decision.admitted: continue for atom in decision.records: cid = atom.get("entry_cid") if not isinstance(cid, str) or not cid: continue previous = found.get(cid) if previous is None: found[cid] = law elif previous != law: blocked.add(cid) for cid in blocked: found.pop(cid, None) return found
def _iter_part(path: Path) -> Iterable[dict[str, object]]: import pyarrow.parquet as pq
parquet = pq.ParquetFile(path) present = [name for name in LEGAL_RECORD_FIELDS if name in pq.read_schema(path).names] for batch in parquet.iter_batches(batch_size=256, columns=present): yield from batch.to_pylist()
def _write_part(destination: Path, index: int, records: list[dict[str, object]]) -> str: import pyarrow as pa import pyarrow.parquet as pq
schema = pa.schema([pa.field(name, pa.string()) for name in LEGAL_RECORD_FIELDS]) columns = { name: [ record.get(name) if isinstance(record.get(name), str) else None for record in records ] for name in LEGAL_RECORD_FIELDS } part = destination / f"part-{index:06d}.parquet" pq.write_table(pa.table(columns, schema=schema), part, compression="zstd") return str(part)
def _is_sha(value: object) -> bool: return ( isinstance(value, str) and len(value) == 40 and all(char in "0123456789abcdef" for char in value) )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301"""Process / host memory watchdog for large IR builds (DO OOM lesson).
Env overrides: IR_MEM_WARN_GIB MemAvailable threshold to shed collectors (default 3.5) IR_MEM_ABORT_GIB MemAvailable abort floor (default 2.5) IR_RSS_ABORT_GIB process RSS hard abort (default 12.0) IR_MEM_LOG_EVERY rows between mem logs when callers pass every_n (default 5000)
Admission may treat ZFS ARC above arc_c_min as schedulable. Warn, shed, andMemAbort keep reading raw MemAvailable: the ARC does not shrink instantly,and counting it in the abort floor lets a build grow until the OOM killer."""from __future__ import annotations
import gcimport osimport signalfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable
DEFAULT_WARN_GIB = 3.5DEFAULT_ABORT_AVAIL_GIB = 2.5DEFAULT_ABORT_RSS_GIB = 12.0DEFAULT_LOG_EVERY = 5000_GIB = 1024**3ARCSTATS_PATH = Path("/proc/spl/kstat/zfs/arcstats")
# Prefer shedding zero-article / lean collectors first; protect AT+DK until last.DEFAULT_SHED_ORDER: list[tuple[str, tuple[str, ...]]] = [ ("mm", ("collect_mm", "run_collector_cc.sh collect_mm")), ("th", ("collect_th", "run_collector_cc.sh collect_th")), ("is-reg", ("collect_is", "is-reg", "run_collector_cc.sh collect_is")), ("lt", ("collect_lt", "run_collector_cc.sh collect_lt")), ("kw", ("collect_kw", "run_collector_cc.sh collect_kw")), ("mt", ("collect_mt", "run_collector_cc.sh collect_mt")), ("dk", ("collect_dk", "run_collector_cc.sh collect_dk")), ("at", ("collect_at", "run_collector_cc.sh collect_at", "at_deepen")),]
class MemAbort(RuntimeError): """Raised when MemAvailable or RSS crosses hard abort thresholds."""
def _env_float(name: str, default: float) -> float: raw = os.environ.get(name) if raw is None or raw == "": return default try: return float(raw) except ValueError: return default
def warn_gib() -> float: return _env_float("IR_MEM_WARN_GIB", DEFAULT_WARN_GIB)
def abort_avail_gib() -> float: return _env_float("IR_MEM_ABORT_GIB", DEFAULT_ABORT_AVAIL_GIB)
def abort_rss_gib() -> float: return _env_float("IR_RSS_ABORT_GIB", DEFAULT_ABORT_RSS_GIB)
def log_every() -> int: try: return max(1, int(os.environ.get("IR_MEM_LOG_EVERY", DEFAULT_LOG_EVERY))) except ValueError: return DEFAULT_LOG_EVERY
def mem_available_gib() -> float: """Raw Linux MemAvailable, in GiB.
This figure does not include the ZFS ARC. Keep using it for warn, shed, and MemAbort. Scheduling headroom is ``schedulable_gib``. """
try: for line in Path("/proc/meminfo").read_text().splitlines(): if line.startswith("MemAvailable:"): return int(line.split()[1]) / 1024 / 1024 except Exception: pass return -1.0
def evictable_arc_bytes(size: int, c_min: int) -> int: """ARC bytes the kernel can reclaim by shrinking toward ``c_min``."""
return max(0, int(size) - int(c_min))
def parse_arc_kstat(text: str) -> dict[str, int]: """Parse ``/proc/spl/kstat/zfs/arcstats``. The value is the third field."""
stats: dict[str, int] = {} for line in text.splitlines(): parts = line.split() if len(parts) < 3 or parts[0] == "name": continue try: stats[parts[0]] = int(parts[2]) except ValueError: continue return stats
def evictable_arc_gib(stats_text: str | None = None) -> float: """GiB of ZFS ARC above ``c_min``. Zero when arcstats is missing."""
if stats_text is None: try: stats_text = ARCSTATS_PATH.read_text() except OSError: return 0.0 stats = parse_arc_kstat(stats_text) if "size" not in stats or "c_min" not in stats: return 0.0 return evictable_arc_bytes(stats["size"], stats["c_min"]) / _GIB
def schedulable_gib( available_gib: float | None = None, *, arc_gib: float | None = None,) -> float: """MemAvailable plus ZFS ARC that can shrink to ``c_min``.
Returns -1 when MemAvailable itself cannot be read. Does not replace ``mem_available_gib`` for the abort floor. """
avail = mem_available_gib() if available_gib is None else float(available_gib) if avail < 0: return -1.0 extra = evictable_arc_gib() if arc_gib is None else max(0.0, float(arc_gib)) return avail + extra
def rss_gib(pid: int | None = None) -> float: path = Path(f"/proc/{pid or 'self'}/status") try: for line in path.read_text().splitlines(): if line.startswith("VmRSS:"): return int(line.split()[1]) / 1024 / 1024 except Exception: pass return -1.0
def snapshot(stage: str = "") -> dict[str, Any]: return { "stage": stage, "mem_avail_gib": round(mem_available_gib(), 3), "rss_gib": round(rss_gib(), 3), "ts": datetime.now(timezone.utc).isoformat(), }
def log_mem(stage: str, log: Callable[[str], None] | None = None) -> dict[str, Any]: snap = snapshot(stage) msg = ( f"mem stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G " f"RSS={snap['rss_gib']:.2f}G" ) if log is not None: log(msg) else: print(f"[{snap['ts']}] {msg}", flush=True) return snap
def discover_pids(*patterns: str) -> list[int]: found: list[int] = [] try: for proc in Path("/proc").iterdir(): if not proc.name.isdigit(): continue try: cmd = (proc / "cmdline").read_bytes().replace(b"\x00", b" ").decode( "utf-8", "ignore" ) except Exception: continue if any(p in cmd for p in patterns): found.append(int(proc.name)) except Exception: pass return found
def shed_collectors( stage: str, *, warn: float | None = None, protect: frozenset[str] | None = None, log: Callable[[str], None] | None = None, notes: list[dict[str, Any]] | None = None,) -> list[dict[str, Any]]: """SIGTERM lean collectors when MemAvailable < warn. Protect AT/DK by default until last.""" warn = warn_gib() if warn is None else warn protect = protect if protect is not None else frozenset({"at", "dk"}) g = mem_available_gib() out: list[dict[str, Any]] = [] if g < 0 or g >= warn: return out # First pass: non-protected; second pass: protected if still under warn. for pass_protected in (False, True): for name, pats in DEFAULT_SHED_ORDER: if (name in protect) != pass_protected: continue pids = discover_pids(*pats) for pid in pids: try: os.kill(pid, 0) except ProcessLookupError: continue except PermissionError: continue try: os.kill(pid, signal.SIGTERM) note = { "stage": stage, "name": name, "pid": pid, "mem_before": round(g, 2), "protected_pass": pass_protected, } out.append(note) if notes is not None: notes.append(note) msg = f"SIGTERM collector {name} pid={pid} mem={g:.2f}G stage={stage}" if log: log(msg) else: print(msg, flush=True) except ProcessLookupError: pass except Exception as exc: msg = f"SIGTERM failed {name} pid={pid}: {exc}" if log: log(msg) else: print(msg, flush=True) g = mem_available_gib() if g >= warn: return out return out
def checkpoint( stage: str, *, row: int | None = None, every_n: int | None = None, shed: bool = True, abort: bool = True, log: Callable[[str], None] | None = None, notes: list[dict[str, Any]] | None = None,) -> dict[str, Any]: """Periodic mem log + optional shed + hard abort.
Call every N rows with ``row`` set; always logs when row is None. """ every = every_n if every_n is not None else log_every() if row is not None and row != 0 and row % every != 0: # Still enforce hard abort cheaply on every call. rss = rss_gib() avail = mem_available_gib() if abort and rss >= abort_rss_gib(): raise MemAbort(f"RSS_ABORT stage={stage} rss={rss:.2f}G > {abort_rss_gib()}G") if abort and 0 <= avail < abort_avail_gib(): if shed: shed_collectors(stage, log=log, notes=notes) avail = mem_available_gib() if 0 <= avail < abort_avail_gib(): raise MemAbort( f"MEM_ABORT stage={stage} MemAvailable={avail:.2f}G < {abort_avail_gib()}G" ) return snapshot(stage)
snap = log_mem(stage if row is None else f"{stage}@{row}", log=log) if shed and 0 <= snap["mem_avail_gib"] < warn_gib(): shed_collectors(stage, log=log, notes=notes) snap = log_mem(f"{stage}_after_shed", log=log) gc.collect() if abort: if snap["rss_gib"] >= abort_rss_gib(): raise MemAbort( f"RSS_ABORT stage={stage} rss={snap['rss_gib']:.2f}G > {abort_rss_gib()}G" ) if 0 <= snap["mem_avail_gib"] < abort_avail_gib(): raise MemAbort( f"MEM_ABORT stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G " f"< {abort_avail_gib()}G" ) return snap123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697"""Directory of one nation's assembled laws.
Reads legal-record rows after a corpus is assembled. Each row that fits thenational schema becomes one code listing, with a Bluebook citation where apublished form is known and a Bluebook analog otherwise. A code name or aheading that is still in the text is filed when the record title is only anarticle caption. Rows that do not fit, provisions that cannot be placed, anddense numbering holes are written beside the listing. This module does notrewrite statute text, does not download, and does not upload."""
from __future__ import annotations
import jsonimport reimport unicodedatafrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Iterable, Mapping
from ipfs_datasets_py.processors.legal_data.iso_slug_crosswalk import ( _DEFAULT_NAMES, resolve_jurisdiction,)from ipfs_datasets_py.processors.legal_scrapers.world_law.schema import ( LEGAL_RECORD_FIELDS, _INSTRUMENTS,)
DIRECTORY_VERSION = "national-directory/v1"_SORT_LIMIT = 250_000_GAP_MIN_PRESENT = 4_GAP_MAX_SPAN = 400_GAP_MIN_DENSITY = 0.75_LOCATORS = ("title", "chapter", "part", "article", "section")_NUMBER = re.compile(r"^[0-9]{1,5}$")_SHA = re.compile(r"^[0-9a-f]{64}$")_LABELS = { "US": "United States", "EU": "European Union", "GB": "United Kingdom",}# Published code abbreviations. Anything else stays an analog._CODE_FORMS: tuple[tuple[str, str, str, str], ...] = ( ("US", "united states code", "U.S.C.", "section"), ("US", "code of federal regulations", "C.F.R.", "section"), ("FR", "code civil", "C. civ.", "article"), ("FR", "code penal", "C. pén.", "article"), ("FR", "code de commerce", "C. com.", "article"), ("DE", "burgerliches gesetzbuch", "BGB", "section"), ("DE", "strafgesetzbuch", "StGB", "section"), ("DE", "handelsgesetzbuch", "HGB", "section"), ("DE", "grundgesetz", "GG", "article"),)_TITLE_PREFIX = frozenset({"U.S.C.", "C.F.R."})_EU_ACT = re.compile( r"(?i)\b(regulation|directive|decision)\b[^\n]{0,80}?\b((?:\(EU\)\s*)?\d{4}/\d+)\b")
@dataclassclass DirectoryEntry: jurisdiction: str instrument: str title: str book: str chapter: str part: str article: str section: str citation: str citation_form: str path: str entry_cid: str
def as_dict(self) -> dict[str, str]: return { "jurisdiction": self.jurisdiction, "instrument": self.instrument, "title": self.title, "book": self.book, "chapter": self.chapter, "part": self.part, "article": self.article, "section": self.section, "citation": self.citation, "citation_form": self.citation_form, "path": self.path, "entry_cid": self.entry_cid, }
@dataclassclass DirectoryIndex: entries: list[DirectoryEntry] = field(default_factory=list) schema_problems: list[dict[str, str]] = field(default_factory=list) unplaced: list[dict[str, str]] = field(default_factory=list) gaps: list[dict[str, object]] = field(default_factory=list) duplicates: int = 0 weak_instrument: int = 0
def report(self) -> dict[str, object]: bluebook = sum(1 for entry in self.entries if entry.citation_form == "bluebook") return { "version": DIRECTORY_VERSION, "listed": len(self.entries), "bluebook": bluebook, "bluebook_analog": len(self.entries) - bluebook, "schema_problems": len(self.schema_problems), "unplaced": len(self.unplaced), "gaps": len(self.gaps), "duplicates": self.duplicates, "weak_instrument": self.weak_instrument, }
def index_national_laws(records: Iterable[Mapping[str, object]]) -> DirectoryIndex: """File assembled legal records into a national code listing."""
index = DirectoryIndex() seen: set[tuple[str, ...]] = set() numbers: dict[tuple[str, ...], tuple[str, set[int]]] = {} for record in records: problems = _schema_problems(record) if problems: index.schema_problems.extend(problems) continue entry = _entry(record) if entry is None: index.unplaced.append(_unplaced(record)) continue key = _entry_key(entry) if key in seen: index.duplicates += 1 else: seen.add(key) index.entries.append(entry) if _weak_instrument(entry): index.weak_instrument += 1 _note_number(numbers, entry) index.gaps.extend(_gaps(numbers)) index.entries.sort(key=_sort_key) return index
def write_national_directory(source_dir: Path | str, dest_dir: Path | str) -> dict[str, object]: """Write the listing, schema problems, unplaced rows, and numbering gaps.
``source_dir`` is one finished country folder of legal-record parts. The corpus files are only read. """
source = Path(source_dir) destination = Path(dest_dir) parts = sorted(source.glob("part-*.parquet")) if not parts: raise ValueError("source") destination.mkdir(parents=True, exist_ok=True) rows = _parquet_rows(parts) total = sum(count for _part, count in rows) if total > _SORT_LIMIT: report = _write_streaming(parts, destination, total) else: records = _iter_records(parts) index = index_national_laws(records) report = index.report() report["order"] = "code" _write_jsonl(destination / "directory.jsonl", (entry.as_dict() for entry in index.entries)) _write_jsonl(destination / "schema_problems.jsonl", index.schema_problems) _write_jsonl(destination / "unplaced.jsonl", index.unplaced) _write_jsonl(destination / "gaps.jsonl", index.gaps) report["source_dir"] = str(source) report["source_rows"] = total report["files"] = [path.name for path in parts] (destination / "report.json").write_text( json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) return report
def _write_streaming(parts: list[Path], destination: Path, total: int) -> dict[str, object]: """Stream a corpus that is too large to sort in memory."""
seen: set[tuple[str, ...]] = set() numbers: dict[tuple[str, ...], tuple[str, set[int]]] = {} listed = 0 bluebook = 0 duplicates = 0 weak = 0 schema_count = 0 unplaced_count = 0 with (destination / "directory.jsonl").open("w", encoding="utf-8") as directory, ( destination / "schema_problems.jsonl" ).open("w", encoding="utf-8") as problems, (destination / "unplaced.jsonl").open( "w", encoding="utf-8" ) as unplaced: for record in _iter_records(parts): found = _schema_problems(record) if found: schema_count += len(found) for problem in found: problems.write(json.dumps(problem, sort_keys=True, ensure_ascii=False) + "\n") continue entry = _entry(record) if entry is None: unplaced_count += 1 unplaced.write(json.dumps(_unplaced(record), sort_keys=True, ensure_ascii=False) + "\n") continue key = _entry_key(entry) if key in seen: duplicates += 1 continue seen.add(key) listed += 1 if _weak_instrument(entry): weak += 1 if entry.citation_form == "bluebook": bluebook += 1 _note_number(numbers, entry) directory.write(json.dumps(entry.as_dict(), sort_keys=True, ensure_ascii=False) + "\n") gaps = _gaps(numbers) _write_jsonl(destination / "gaps.jsonl", gaps) return { "version": DIRECTORY_VERSION, "listed": listed, "bluebook": bluebook, "bluebook_analog": listed - bluebook, "schema_problems": schema_count, "unplaced": unplaced_count, "gaps": len(gaps), "duplicates": duplicates, "weak_instrument": weak, "order": "source", "source_rows": total, }
def _schema_problems(record: Mapping[str, object]) -> list[dict[str, str]]: cid = _text(record.get("entry_cid")) or _text(record.get("title")) or "" problems: list[dict[str, str]] = []
def add(reason: str) -> None: problems.append({"entry_cid": cid, "reason": reason})
for name in ("jurisdiction", "admin_level", "instrument_type", "text", "provenance"): if name not in record: add("missing_" + name) if problems: return problems text = record.get("text") if not isinstance(text, str) or not text.strip(): add("empty_text") admin = _text(record.get("admin_level")) if admin != "country": add("not_national") instrument = _text(record.get("instrument_type")) if instrument not in _INSTRUMENTS: add("bad_instrument") resolved = resolve_jurisdiction(_text(record.get("jurisdiction"))) if resolved is None or resolved.admin_level not in {"country", "supranational"}: add("bad_jurisdiction") digest = record.get("content_sha256") if not isinstance(digest, str) or _SHA.fullmatch(digest) is None: add("bad_hash") provenance = _provenance(record.get("provenance")) if provenance is None: add("bad_provenance") elif provenance.get("document_role") != "law": add("not_law") return problems
_HEADING_LINE = re.compile( r"(?i)^(partie|livre|titre|titulo|título|chapitre|chapter|section|part)\s*-\s*" r"(?:partie|livre|titre|chapitre|chapter|section|part(?:ie)?)?\s*" r"([0-9]{1,4}|[IVXLCDM]{1,12})\b")_ARTICLE_DOT = re.compile( r"(?i)^(?:article|art\.?)?\s*" r"((?:[A-Z]-)?[0-9]{1,4}(?:\s*[-.]\s*[0-9]{1,4})?)\s*\.-\s*$")_ARTICLE_ONLY = re.compile( r"(?i)^(?:article|art\.?)\s+" r"((?:[A-Z]-)?[0-9]{1,4}(?:-[0-9]{1,4})?[A-Za-z]?)\s*[.:]?\s*$")_SECTION_ONLY = re.compile(r"(?i)^(?:section|sec\.?)\s+([0-9]{1,4}[A-Za-z]?)\s*[.:]?\s*$")_TITLE_SECTION = re.compile(r"(?i)^(?:section|sec\.?)\s+([0-9]{1,4}[A-Za-z]?)\b")_TITLE_ARTICLE = re.compile( r"(?i)^(?:article|art\.?)\s+([0-9]{1,4}(?:-[0-9]{1,4})?[A-Za-z]?)\b")_TITLE_NUM = re.compile(r"^([0-9]{1,4}[A-Za-z]?)\s*[.)]\s+\S")_TITLE_LOI = re.compile( r"(?i)^article\s+([0-9]{1,4})\b" r"(?:\s*,\s*[^,\n]{1,16})*" r"\s+de\s+(?:la\s+|l['’])?" r"((?:loi|ordonnance)\b.+?)" r"\.?\s*$")_INSTRUMENT_WORD = re.compile( r"(?i)\b(?:code|loi|ordonnance|ordinance|act|treaty|gesetz|constitution|statute|reglement|règlement)\b")_ROMAN = re.compile(r"(?i)^M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})$")_HEADING_KIND = { "partie": "part", "part": "part", "livre": "book", "titre": "title", "titulo": "title", "título": "title", "chapitre": "chapter", "chapter": "chapter", "section": "section",}
def recover_placement(title: str, text: str) -> dict[str, str]: """Read a code name and headings that the record did not already file.
Only a heading line near the start of the text is used. A sentence that mentions another article is left alone. """
found: dict[str, str] = {} label = title.strip() loi = _TITLE_LOI.match(label) if loi: found["article"] = loi.group(1) found["instrument"] = loi.group(2).strip(" .") elif _TITLE_ARTICLE.match(label) and len(label) < 80: found["article"] = _TITLE_ARTICLE.match(label).group(1) # type: ignore[union-attr] elif (section := _TITLE_SECTION.match(label)) is not None: found["section"] = section.group(1) elif (numbered := _TITLE_NUM.match(label)) is not None: found["section"] = numbered.group(1) lines = [item.strip() for item in text.splitlines() if item.strip()][:25] for index, line in enumerate(lines): if index == 0 and "instrument" not in found: named = _TITLE_LOI.match(line) if named: found.setdefault("article", named.group(1)) found["instrument"] = named.group(2).strip(" .") continue if "instrument" not in found and _instrument_line(line): found["instrument"] = line continue heading = _HEADING_LINE.match(line) if heading: kind = _HEADING_KIND[heading.group(1).casefold()] number = heading.group(2) number = number if number.isdigit() else number.upper() if not number.isdigit() and _ROMAN.fullmatch(number) is None: continue found.setdefault(kind, number) continue article = _ARTICLE_DOT.match(line) or _ARTICLE_ONLY.match(line) if article: found.setdefault("article", re.sub(r"\s+", "", article.group(1))) continue section_line = _SECTION_ONLY.match(line) if section_line: found.setdefault("section", section_line.group(1)) return found
def _instrument_line(line: str) -> bool: if len(line) < 8 or len(line) > 160: return False if ( _HEADING_LINE.match(line) or _ARTICLE_DOT.match(line) or _ARTICLE_ONLY.match(line) or _SECTION_ONLY.match(line) ): return False letters = [char for char in line if char.isalpha()] if len(letters) < 6: return False if sum(char.isupper() for char in letters) / len(letters) < 0.75: return False return _INSTRUMENT_WORD.search(line) is not None
def _generic_instrument(title: str) -> bool: folded = _fold(title) if not folded: return True if folded in {"article", "section", "chapter", "chapitre", "titel", "title", "artikel"}: return True if re.match(r"(?i)^(article|art\.?|section|sec\.?)\b", title.strip()): return True if re.match(r"^[0-9]{1,4}[A-Za-z]?\s*[.)]\s+", title.strip()): return True return False
def _weak_instrument(entry: DirectoryEntry) -> bool: return _generic_instrument(entry.instrument) or _fold(entry.instrument) == _fold( _country_label(entry.jurisdiction) )
def _entry(record: Mapping[str, object]) -> DirectoryEntry | None: provenance = _provenance(record.get("provenance")) if provenance is None: return None locators = {name: _text(provenance.get(name)) for name in _LOCATORS} raw_title = _text(record.get("title")) recovered: dict[str, str] = {} if _generic_instrument(raw_title) or not any(locators.values()): recovered = recover_placement(raw_title, _text(record.get("text"))) for name in _LOCATORS: if not locators[name]: locators[name] = recovered.get(name, "") book = _text(provenance.get("book")) or recovered.get("book", "") if not any(locators.values()) and not book: return None jurisdiction = _text(record.get("jurisdiction")).upper() if _generic_instrument(raw_title): instrument = recovered.get("instrument") or _country_label(jurisdiction) else: instrument = raw_title placed = {**locators, "book": book} citation, form = _citation( jurisdiction=jurisdiction, instrument=instrument, locators=placed, existing=_text(record.get("bluebook_citation")), ) return DirectoryEntry( jurisdiction=jurisdiction, instrument=instrument, title=locators["title"], book=book, chapter=locators["chapter"], part=locators["part"], article=locators["article"], section=locators["section"], citation=citation, citation_form=form, path=_path(instrument, placed), entry_cid=_text(record.get("entry_cid")), )
def _citation( *, jurisdiction: str, instrument: str, locators: Mapping[str, str], existing: str,) -> tuple[str, str]: if existing: return existing, "bluebook" form = _known_form(jurisdiction, instrument) if form is not None: abbreviation, pin = form number = locators.get(pin) or "" if not number and pin == "article": number = locators.get("section") or "" if not number and pin == "section": number = locators.get("article") or "" if number: if abbreviation in _TITLE_PREFIX and locators.get("title"): return f"{locators['title']} {abbreviation} § {number}", "bluebook" if abbreviation not in _TITLE_PREFIX: joiner = "art." if pin == "article" else "§" return f"{abbreviation} {joiner} {number}", "bluebook" eu = _EU_ACT.search(instrument) if jurisdiction == "EU" and eu is not None: kind = eu.group(1).casefold() number = eu.group(2).upper().replace("(EU) ", "") pin = locators.get("article") or locators.get("section") if pin: label = {"regulation": "Regulation", "directive": "Directive", "decision": "Decision"}[kind] token = "art." if locators.get("article") else "§" return f"{label} (EU) {number}, {token} {pin}", "bluebook_analog" return _analog(jurisdiction, instrument, locators), "bluebook_analog"
def _analog(jurisdiction: str, instrument: str, locators: Mapping[str, str]) -> str: pieces = [_country_label(jurisdiction)] if _fold(instrument) != _fold(pieces[0]): pieces.append(instrument) pins = _pins(locators) if pins: pieces.append(pins) return ", ".join(pieces)
def _pins(locators: Mapping[str, str]) -> str: labels = ( ("part", "pt."), ("book", "bk."), ("title", "tit."), ("chapter", "ch."), ("section", "§"), ("article", "art."), ) article = locators.get("article") or "" parts: list[str] = [] for name, label in labels: number = locators.get(name) or "" if not number: continue if name == "section" and number == article: continue parts.append(f"{label} {number}") return ", ".join(parts)
def _known_form(jurisdiction: str, instrument: str) -> tuple[str, str] | None: folded = _fold(instrument) for code, name, abbreviation, pin in _CODE_FORMS: if jurisdiction == code and (folded == name or folded.startswith(name + " ")): return abbreviation, pin return None
def _path(instrument: str, locators: Mapping[str, str]) -> str: labels = { "part": "Part", "book": "Book", "title": "Title", "chapter": "Chapter", "section": "Section", "article": "Article", } parts = [instrument] article = locators.get("article") or "" for name in ("part", "book", "title", "chapter", "section", "article"): number = locators.get(name) or "" if not number: continue if name == "section" and number == article: continue parts.append(f"{labels[name]} {number}") return " / ".join(parts)
def _note_number(numbers: dict[tuple[str, ...], tuple[str, set[int]]], entry: DirectoryEntry) -> None: if _weak_instrument(entry): return leaf = entry.article or entry.section if _NUMBER.fullmatch(leaf) is None: return kind = "article" if entry.article else "section" key = ( entry.jurisdiction, _fold(entry.instrument), entry.part, entry.book, entry.title, entry.chapter, kind, ) slot = numbers.get(key) if slot is None: slot = (entry.instrument, set()) numbers[key] = slot slot[1].add(int(leaf))
def _gaps(numbers: Mapping[tuple[str, ...], tuple[str, set[int]]]) -> list[dict[str, object]]: found: list[dict[str, object]] = [] for key, (instrument, present) in numbers.items(): if len(present) < _GAP_MIN_PRESENT: continue start, stop = min(present), max(present) span = stop - start + 1 if span > _GAP_MAX_SPAN or len(present) / span < _GAP_MIN_DENSITY: continue missing = [number for number in range(start, stop + 1) if number not in present] if not missing: continue jurisdiction, _folded, part, book, title, chapter, kind = key found.append( { "jurisdiction": jurisdiction, "instrument": instrument, "part": part, "book": book, "title": title, "chapter": chapter, "unit": kind, "missing": missing, } ) found.sort(key=lambda row: (str(row["instrument"]), str(row["title"]), str(row["chapter"]))) return found
def _unplaced(record: Mapping[str, object]) -> dict[str, str]: return { "entry_cid": _text(record.get("entry_cid")), "jurisdiction": _text(record.get("jurisdiction")), "instrument": _text(record.get("title")), "reason": "no_locator", }
def _entry_key(entry: DirectoryEntry) -> tuple[str, ...]: return ( entry.jurisdiction, _fold(entry.instrument), entry.part, entry.book, entry.title, entry.chapter, entry.article, entry.section, )
def _sort_key(entry: DirectoryEntry) -> tuple[object, ...]: return ( entry.jurisdiction, _fold(entry.instrument), _number_key(entry.part), _number_key(entry.book), _number_key(entry.title), _number_key(entry.chapter), _number_key(entry.article or entry.section), entry.entry_cid, )
def _number_key(value: str) -> tuple[int, int | str]: if value.isdigit(): return (0, int(value)) return (1, value)
def _country_label(code: str) -> str: if code in _LABELS: return _LABELS[code] return _DEFAULT_NAMES.get(code) or code
def _provenance(value: object) -> dict[str, object] | None: if isinstance(value, dict): return value if isinstance(value, str) and value.strip().startswith("{"): try: loaded = json.loads(value) except json.JSONDecodeError: return None if isinstance(loaded, dict): return loaded return None
def _fold(value: str) -> str: normal = unicodedata.normalize("NFKD", value).casefold() letters = "".join(char for char in normal if not unicodedata.combining(char)) return re.sub(r"\s+", " ", letters).strip()
def _text(value: object) -> str: if isinstance(value, str): return value.strip() return ""
def _parquet_rows(parts: list[Path]) -> list[tuple[Path, int]]: import pyarrow.parquet as pq
return [(path, pq.ParquetFile(path).metadata.num_rows) for path in parts]
def _iter_records(parts: list[Path]) -> Iterable[dict[str, object]]: import pyarrow.parquet as pq
wanted = { "jurisdiction", "admin_level", "instrument_type", "citation", "bluebook_citation", "title", "text", "content_sha256", "entry_cid", "provenance", } columns = [name for name in LEGAL_RECORD_FIELDS if name in wanted] for path in parts: present = [name for name in columns if name in pq.read_schema(path).names] parquet = pq.ParquetFile(path) for batch in parquet.iter_batches(batch_size=256, columns=present): yield from batch.to_pylist()
def _write_jsonl(path: Path, rows: Iterable[Mapping[str, object]]) -> None: with path.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272"""Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
Prefer article/section as the retrieval unit; fall back to law-level whenarticles are missing or empty. Strip leftover HTML, then detect multilingualtitle/chapter/article/section headings (Oregon-style) when present. Neverinvent legal text or a hierarchy that is not in the source.
Public Hub reads only (token=False). No Hugging Face token is read or stored."""
from __future__ import annotations
import jsonimport osimport refrom collections import Counterfrom pathlib import Pathfrom typing import Any
import pandas as pdfrom huggingface_hub import dataset_info, hf_hub_downloadfrom huggingface_hub.errors import EntryNotFoundError
from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSIONfrom .auth import configure_hf, public_tokenfrom .cidutil import cid_of_json, sha256_file, sha256_hexfrom .schema import SchemaError, validate_articles, validate_lawsfrom .reconstruct import ( article_sort_key, parent_needs_reconstruct, reconstruct_on, reconstruct_parent,)from .structure import normalize_legal_text, split_structured_units
COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"EMPTY_ARTICLE_COLUMNS = ( "law_id", "id", "title", "text", "source_url", "document_number", "article_number", "record_type", "metadata_json",)
def _empty_articles() -> pd.DataFrame: return pd.DataFrame(columns=list(EMPTY_ARTICLE_COLUMNS))
def normalize_text(value: Any) -> str: if value is None or (isinstance(value, float) and pd.isna(value)): return "" return normalize_legal_text(value)
def _s(value: Any) -> str: return normalize_text(value)
def _download(repo_id: str, filename: str, cache_dir: Path) -> Path: configure_hf() path = hf_hub_download( repo_id=repo_id, filename=filename, repo_type="dataset", token=public_token(), cache_dir=str(cache_dir / "hf"), ) return Path(path)
def _repo_filenames(info: Any) -> set[str]: return {str(getattr(s, "rfilename", "") or "") for s in (getattr(info, "siblings", None) or [])}
def _pick_repo_file(filenames: set[str], name: str) -> str | None: for cand in (f"data/{name}.parquet", f"{name}.parquet"): if cand in filenames: return cand return None
def _resolve_local_parquet(root: Path, name: str, *, required: bool = True) -> Path | None: """Accept either <root>/data/<name>.parquet or <root>/<name>.parquet.""" for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"): if cand.is_file(): return cand if required: raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)") return None
def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: """Load a local country-laws pack (filtered preprocess layout).""" local_dir = Path(local_dir).resolve() laws_path = _resolve_local_parquet(local_dir, "laws") articles_path = _resolve_local_parquet(local_dir, "articles", required=False) laws = pd.read_parquet(laws_path) articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles() validate_laws(laws) validate_articles(articles) pack_meta: dict[str, Any] = {} meta_path = local_dir / "pack_meta.json" if meta_path.is_file(): try: pack_meta = json.loads(meta_path.read_text(encoding="utf-8")) except Exception: pack_meta = {} source_dataset = ( pack_meta.get("source_dataset") or pack_meta.get("repo") or f"local/{local_dir.name}" ) source_revision = str( pack_meta.get("source_revision") or pack_meta.get("revision") or f"local:{local_dir.name}" ) meta = { "source_dataset": source_dataset, "source_revision": source_revision, "laws_path": str(laws_path), "articles_path": str(articles_path) if articles_path is not None else None, "laws_sha256": sha256_file(laws_path), "articles_sha256": sha256_file(articles_path) if articles_path is not None else None, "n_laws_source": int(len(laws)), "n_articles_source": int(len(articles)), "laws_columns": list(map(str, laws.columns)), "articles_columns": list(map(str, articles.columns)), "article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None, "schema_surprises": _schema_surprises(laws, articles), "local_source_dir": str(local_dir), "pack_meta": pack_meta, } return laws, articles, meta
def _law_shards(local: Path) -> list[Path]: data = local / "data" if not data.is_dir(): return [] return [ path for path in sorted(data.glob("laws-*.parquet")) if "_html" not in path.name ]
def _pack_local_shards(local: Path, cache_dir: Path) -> Path: """Concatenate a local shard directory. Does not contact the Hub."""
meta: dict[str, Any] = {} meta_path = local / "pack_meta.json" if meta_path.is_file(): try: loaded = json.loads(meta_path.read_text(encoding="utf-8")) if isinstance(loaded, dict): meta = loaded except Exception: meta = {} from ipfs_datasets_py.processors.legal_scrapers.world_law.load_sharded_laws import ( load_sharded_laws, require_source_revision, )
revision = require_source_revision(local) slug = str(meta.get("slug") or local.name) dataset = str(meta.get("source_dataset") or f"endomorphosis/ipfs_{slug}_laws") dest = Path(cache_dir) / "packed-shards" / slug
load_sharded_laws( local, dest, slug=slug, source_dataset=dataset, source_revision=revision, ) return dest
def preflight_local_shard_source(source: str) -> None: """Reject an unpacked shard directory before ``build_country`` starts.
Hub ids and directories that already contain ``laws.parquet`` return without reading them. A shard directory whose ``source_revision`` is missing or not 40 lowercase hex characters raises ``ValueError``. """
local = Path(source) if not local.is_dir(): return if (local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file(): return if not _law_shards(local): return from ipfs_datasets_py.processors.legal_scrapers.world_law.load_sharded_laws import ( require_source_revision, )
require_source_revision(local)
def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: """Load Hub dataset id OR a local directory with laws/articles parquet.
A local directory of ``data/laws-*.parquet`` is packed with ``load_sharded_laws`` before it is read. That path requires a 40-hex ``source_revision`` in ``pack_meta.json`` and does not call the Hub. """ local = Path(repo_id) if local.is_dir() and ( (local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file() ): return load_local_source(local) if local.is_dir() and _law_shards(local): return load_local_source(_pack_local_shards(local, cache_dir))
configure_hf() os.environ.setdefault("HF_HOME", str(cache_dir / "hf")) info = dataset_info(repo_id, token=public_token()) revision = info.sha filenames = _repo_filenames(info) laws_file = _pick_repo_file(filenames, "laws") or "data/laws.parquet" articles_file = _pick_repo_file(filenames, "articles") laws_path = _download(repo_id, laws_file, cache_dir) articles_path: Path | None = None if articles_file is not None: try: articles_path = _download(repo_id, articles_file, cache_dir) except EntryNotFoundError: articles_path = None laws = pd.read_parquet(laws_path) articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles() validate_laws(laws) validate_articles(articles) meta = { "source_dataset": repo_id, "source_revision": revision, "laws_path": str(laws_path), "articles_path": str(articles_path) if articles_path is not None else None, "laws_sha256": sha256_file(laws_path), "articles_sha256": sha256_file(articles_path) if articles_path is not None else None, "n_laws_source": int(len(laws)), "n_articles_source": int(len(articles)), "laws_columns": list(map(str, laws.columns)), "articles_columns": list(map(str, articles.columns)), "article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None, "schema_surprises": _schema_surprises(laws, articles), } return laws, articles, meta
def _schema_surprises(laws: pd.DataFrame, articles: pd.DataFrame) -> list[str]: notes: list[str] = [] if articles is None or articles.empty: notes.append("articles.parquet has 0 rows; corpus falls back to law-level units") if "article_count" in laws.columns: dtype = str(laws["article_count"].dtype) notes.append(f"laws.article_count dtype={dtype}") try: if int((laws["article_count"].fillna(0) == 0).sum()) == len(laws): notes.append("every law has article_count=0") except Exception: pass for col in ("date", "date_issued"): if col in laws.columns and laws[col].isna().all(): notes.append(f"laws.{col} is entirely null") if "eli" in laws.columns: n_eli = int(laws["eli"].notna().sum()) if hasattr(laws["eli"], "notna") else 0 notes.append(f"laws.eli non-null={n_eli}/{len(laws)}") if "language" in laws.columns: langs = sorted({str(x) for x in laws["language"].dropna().unique()}) notes.append(f"laws.language values={langs}") return notes
def _parse_meta(raw: str) -> dict[str, Any]: if not raw: return {} try: obj = json.loads(raw) return obj if isinstance(obj, dict) else {} except Exception: return {}
def _law_cid(instrument_id: str, instrument_title: str, jurisdiction: str, language: str, source_dataset: str) -> str: identity = { "schema": LAW_IDENTITY_SCHEMA, "source_dataset": source_dataset, "instrument_id": instrument_id, "instrument_title": instrument_title, "jurisdiction": jurisdiction, "language": language, } return cid_of_json(identity)
def _entry_cid(record: dict[str, Any]) -> str: identity = { "schema": ENTRY_IDENTITY_SCHEMA, "record_type": record["record_type"], "source_dataset": record["source_dataset"], "instrument_id": record["instrument_id"], "article_number": record.get("article_number") or "", "article_title": record.get("article_title") or "", "body_sha256": record["body_sha256"], "language": record.get("language") or "", "jurisdiction": record.get("jurisdiction") or "", "source_url": record.get("source_url") or "", } return cid_of_json(identity)
def _row_get(row: pd.Series, col: str, default: str = "") -> str: if col not in row.index: return default return _s(row[col])
def _coverage_from( row: pd.Series, meta: dict[str, Any], articles_empty: bool, sparse_fallback: bool = False,) -> str: for key in ("coverage", "coverage_note"): if key in meta and meta[key]: return normalize_text(meta[key]) status = normalize_text(meta.get("article_extraction_status") or "") if sparse_fallback: note = "law-level (article coverage below 10% of laws; sparse articles table)" if status: return f"{note}; extraction_status={status}" return note if articles_empty: if status: return f"law-level (articles empty or unavailable in source snapshot); extraction_status={status}" return "law-level (articles empty or unavailable in source snapshot)" if status: return f"article-level; extraction_status={status}" return "article-level"
def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, Any]) -> str: for col in ("retrieved_at", "date_issued", "date"): val = _row_get(row, col) if val: return val[:10] if len(val) >= 10 and val[4] == "-" else val for key in ("snapshot_date", "retrieved_at"): if key in meta and meta[key]: return normalize_text(str(meta[key]))[:10] nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for key in ("snapshot_date", "retrieved_at"): if nested.get(key): return normalize_text(str(nested[key]))[:10] return ""
def _hierarchy_fields( title: str, body: str, article_number: str, *, language: str = "") -> dict[str, Any]: """Best-effort hierarchy from a single already-split article/section body.""" units = split_structured_units( f"{title}\n{body}" if title else body, language=language ) if not units: return { "hierarchy_kind": "article" if article_number else "law", "hierarchy_path": "", "title_number": "", "chapter_number": "", "part_number": "", "section_number": "", "subsections": [], } unit = units[0] return { "hierarchy_kind": unit.kind, "hierarchy_path": unit.hierarchy_path, "title_number": unit.title_number, "chapter_number": unit.chapter_number, "part_number": unit.part_number, "section_number": unit.section_number, "subsections": list(unit.subsections), }
def _compact_line(text: str) -> str: return re.sub(r"\s+", " ", text or "").strip().casefold()
def _is_title_shell(body: str, title: str) -> bool: """True when the article row is only its heading, repeated once.""" folded_body = _compact_line(body) folded_title = _compact_line(title) if len(folded_title) < 24 or not folded_body: return False return folded_body == folded_title or folded_body == f"{folded_title} {folded_title}"
_NOTICE_RE = re.compile( r"(?i)(\bnewsletter\b|\bblog\b|press release|communiqu[eé]|" r"\bnews item\b|\bnotice board\b)")
def _instrument_record_type( metadata: dict[str, Any], title: str, *, text: str = "", source_url: str = "", language: str = "",) -> str: """A normative instrument is a law, even when its title says Article.
Newsletters, blogs, press notices, title-only cards, and informative website pages are not laws. A provision inside a law stays an article; this label is only for the instrument itself. """ meta = metadata or {} document_type = str(meta.get("document_type") or "").strip().casefold() meta_type = str(meta.get("record_type") or "").strip().casefold() if _NOTICE_RE.search(title or "") or document_type in { "newsletter", "blog", "press", "press_release", "notice", }: return "notice" if document_type in {"gazette", "gazette_pdf"} and meta_type not in { "law", "statute", "constitution", }: return "notice" from ipfs_datasets_py.processors.legal_scrapers.world_law.document_role import ( classify_document_role, )
role, _reason = classify_document_role( { "title": title, "text": text, "source_url": source_url, "language": language, "doc_type": document_type, } ) if role in {"metadata", "informative"}: return "notice" return "law"
def _unit_record_type(unit: Any, instrument_type: str, *, n_units: int, parent_body: str) -> str: """One unit that is the whole instrument keeps the instrument label.""" if instrument_type == "notice": return "notice" if ( n_units == 1 and parent_body and len(getattr(unit, "body", "") or "") >= int(0.8 * len(parent_body)) ): return "law" kind = getattr(unit, "kind", "") or "" if kind in {"article", "section"}: return kind return "article"
def _children_are_rich(kids: list[dict[str, Any]], parent_body: str) -> bool: """True when the article rows already carry the statute, not just headings.""" if not kids: return False total = sum(len((kid.get("body") or "").strip()) for kid in kids) if total >= max(int(len(parent_body) * 0.5), 200): return True return any( len((kid.get("body") or "").strip()) >= 80 and not _is_title_shell(kid.get("body") or "", kid.get("title") or "") for kid in kids )
def _needs_parent_split(kids: list[dict[str, Any]], parent_body: str) -> bool: """Split the parent when it holds the text and the article rows do not.""" if len(parent_body) < 250 or len(parent_body) > 1_200_000: return False return not _children_are_rich(kids, parent_body)
def _expand_title_shell(parent: str, title: str, sibling_titles: set[str]) -> str | None: """Copy the parent span from this heading to the next sibling heading.
The span is taken only from lines already in the parent. A short heading such as "Article 1" is left alone, because it matches too many lines. """ key = _compact_line(title) peers = {item for item in sibling_titles if item and item != key and len(item) >= 24} if len(key) < 24 or not peers or not parent: return None lines = [ln.strip() for ln in parent.splitlines() if ln.strip()] compact = [_compact_line(ln) for ln in lines] best = "" for index, folded in enumerate(compact): if folded != key: continue chunk = [lines[index]] for later, later_folded in zip(lines[index + 1 :], compact[index + 1 :]): if later_folded in peers: break chunk.append(later) text = "\n".join(chunk).strip() if len(text) > len(best): best = text # The heading alone is not enough. Require a following sentence from the parent. if len(best) < len(key) + 40: return None return best
def _collector(meta: dict[str, Any], source_dataset: str) -> str: nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {} for blob in (meta, nested): for key in ("collector", "collector_id", "harvester"): if blob.get(key): return normalize_text(blob[key]) return f"{COLLECTOR_DEFAULT} ({source_dataset})"
def laws_index(laws: pd.DataFrame, source_dataset: str) -> dict[str, dict[str, Any]]: """Map instrument_id -> law facet fields (always computed; not always corpus units).""" out: dict[str, dict[str, Any]] = {} for _, row in laws.iterrows(): instrument_id = _row_get(row, "id") instrument_title = _row_get(row, "title") jurisdiction = _row_get(row, "jurisdiction") or _row_get(row, "country") language = _row_get(row, "language") law_cid = _law_cid(instrument_id, instrument_title, jurisdiction, language, source_dataset) meta = _parse_meta(_row_get(row, "metadata_json")) out[instrument_id] = { "instrument_id": instrument_id, "instrument_title": instrument_title, "law_cid": law_cid, "jurisdiction": jurisdiction, "language": language, "source_url": _row_get(row, "source_url"), "license": _row_get(row, "license"), "eli": _row_get(row, "eli"), "identifier": _row_get(row, "identifier") or instrument_id, "official_identifier": _row_get(row, "official_identifier"), "source_type": _row_get(row, "source_type"), "country": _row_get(row, "country"), "law_status": _row_get(row, "law_status"), "body": _row_get(row, "text"), "metadata": meta, "row": row, } return out
def _base_record( *, record_type: str, source_dataset: str, source_revision: str, instrument_id: str, instrument_title: str, law_cid: str, article_number: str, article_title: str, body: str, jurisdiction: str, language: str, source_url: str, snapshot_date: str, coverage: str, license_expr: str, collector: str, source_id: str, extra: dict[str, Any] | None = None,) -> dict[str, Any]: title_for_bm25 = article_title if record_type == "article" and article_title else instrument_title rec: dict[str, Any] = { "record_type": record_type, "source_dataset": source_dataset, "source_revision": source_revision, "source_id": source_id, "instrument_id": instrument_id, "instrument_title": instrument_title, "law_id": instrument_id, "law_cid": law_cid, "article_number": article_number, "article_title": article_title, "title": title_for_bm25, "body": body, "body_sha256": sha256_hex(body.encode("utf-8")), "jurisdiction": jurisdiction, "language": language, "source_url": source_url, "snapshot_date": snapshot_date, "coverage": coverage, "license": license_expr, "collector": collector, "schema_version": SCHEMA_VERSION, "entry_identity_schema_version": ENTRY_IDENTITY_SCHEMA, } if extra: rec.update(extra) from .citations import assign_citation, citation_fields
slug = "" if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"): slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws") year = "" if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit(): year = snapshot_date[:4] extra = extra or {} rec.update( citation_fields( assign_citation( eli=str(rec.get("eli") or extra.get("eli") or ""), official_identifier=str( rec.get("official_identifier") or extra.get("official_identifier") or "" ), identifier=str(rec.get("identifier") or extra.get("identifier") or ""), instrument_title=instrument_title, article_number=article_number, section_number=str(extra.get("section_number") or ""), record_type=record_type, jurisdiction=jurisdiction, country=str(extra.get("country") or ""), slug=slug, year=year, ) ) ) rec["entry_cid"] = _entry_cid(rec) rec["title_length"] = len(title_for_bm25) rec["body_length"] = len(body) rec["document_length"] = len(title_for_bm25) + len(body) return rec
def _cid_worker_count(n_articles: int, requested: int | None) -> int: """Cores for a CID-set check. Small corpora stay on one core.""" if requested is not None: return max(1, int(requested)) if n_articles < 8000: return 1 cpus = os.cpu_count() or 2 return max(2, min(12, cpus // 4, max(2, n_articles // 20000)))
def _article_outcome( row: pd.Series, *, law_map: dict[str, dict[str, Any]], promoted: dict[str, list[Any]], sibling_titles: dict[str, set[str]], source_meta: dict[str, Any], source_dataset: str, source_revision: str,) -> tuple[dict[str, Any] | None, str, Any]: """One article row as a corpus record, or a drop reason.
``("", promoted skip)`` is ``(None, "", None)`` and is not a drop. """ source_id = _row_get(row, "id") instrument_id = _row_get(row, "law_id") body = _row_get(row, "text") article_title = _row_get(row, "title") article_number = _row_get(row, "article_number") if not body: return None, "empty_body", source_id if instrument_id in promoted: return None, "", None parent = law_map.get(instrument_id) if parent and _is_title_shell(body, article_title): expanded = _expand_title_shell( parent["body"], article_title, sibling_titles.get(instrument_id) or set(), ) if expanded: body = expanded if not parent: return None, "missing_instrument", {"article_id": source_id, "law_id": instrument_id} meta = parent["metadata"] art_meta = _parse_meta(_row_get(row, "metadata_json")) merged_meta = {**meta, **art_meta} record = _base_record( record_type="article", source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, instrument_title=parent["instrument_title"], law_cid=parent["law_cid"], article_number=article_number, article_title=article_title, body=body, jurisdiction=parent["jurisdiction"], language=parent["language"] or _row_get(row, "language"), source_url=_row_get(row, "source_url") or parent["source_url"], snapshot_date=_snapshot_date(parent["row"], merged_meta, source_meta), coverage=_coverage_from(parent["row"], merged_meta, articles_empty=False), license_expr=parent["license"], collector=_collector(merged_meta, source_dataset), source_id=source_id, extra={ "eli": parent["eli"], "identifier": parent["identifier"], "official_identifier": parent["official_identifier"], "source_type": parent["source_type"], "country": parent["country"], "law_status": parent["law_status"], "parent_law_id": instrument_id, "article_id": source_id, **_hierarchy_fields( article_title, body, article_number, language=parent["language"] ), }, ) return record, "", None
# Forked CID workers read this. It is set only for the duration of a pool._CID_JOB: dict[str, Any] = {}
def _cid_article_span(span: tuple[int, int]) -> list[tuple[str, str, Any]]: start, end = span job = _CID_JOB articles = job["articles"] out: list[tuple[str, str, Any]] = [] for i in range(start, end): record, drop, sample = _article_outcome( articles.iloc[i], law_map=job["law_map"], promoted=job["promoted"], sibling_titles=job["sibling_titles"], source_meta=job["source_meta"], source_dataset=job["source_dataset"], source_revision=job["source_revision"], ) if record is None: out.append(("", drop, sample)) else: out.append((str(record["entry_cid"]), "", record.get("source_id"))) return out
def build_corpus( laws: pd.DataFrame, articles: pd.DataFrame, source_meta: dict[str, Any], *, cid_only: bool = False, cid_workers: int | None = None,) -> tuple[pd.DataFrame, dict[str, Any]]: source_dataset = source_meta["source_dataset"] source_revision = source_meta["source_revision"] law_map = laws_index(laws, source_dataset) articles_empty = articles is None or articles.empty n_laws = int(len(laws)) n_arts = int(len(articles) if articles is not None else 0) article_law_coverage = (n_arts / n_laws) if n_laws else 0.0 # Empty articles.parquet already falls back. Also fall back when the table is # present but covers under ~10% as many rows as laws (Estonia: 2 vs 3484). sparse_fallback = (not articles_empty) and article_law_coverage < 0.10 use_articles = (not articles_empty) and not sparse_fallback
extraction_statuses: Counter[str] = Counter() for parent in law_map.values(): st = normalize_text(parent["metadata"].get("article_extraction_status") or "") if st: extraction_statuses[st] += 1
report: dict[str, Any] = { "source_dataset": source_dataset, "source_revision": source_revision, "laws_sha256": source_meta.get("laws_sha256"), "articles_sha256": source_meta.get("articles_sha256"), "n_laws_in": int(len(laws)), "n_articles_in": int(len(articles) if articles is not None else 0), "unit": "article" if use_articles else "law", "article_law_coverage": article_law_coverage, "sparse_article_fallback": sparse_fallback, "drops": { "empty_body": 0, "missing_instrument": 0, "duplicate_cid": 0, "duplicate_source_kept_first": 0, }, "drop_samples": { "empty_body": [], "missing_instrument": [], "duplicate_cid": [], }, "language_breakdown": {}, "quality_flags": {}, "schema_surprises": list(source_meta.get("schema_surprises") or []), "n_out": 0, "never_invented_legal_text": True, "n_reconstructed_parents": 0, "n_reconstructed_truncated": 0, "n_reconstructed_stubs": 0, "n_empty_parents_with_articles_not_reconstructed": 0, "n_thin_instruments_replaced": 0, }
entries: list[dict[str, Any]] = [] cid_seen: set[str] = set() n_emitted = 0
def _keep(rec: dict[str, Any]) -> None: nonlocal n_emitted if not cid_only: entries.append(rec) return n_emitted += 1 cid = str(rec.get("entry_cid") or "") if not cid: return if cid in cid_seen: report["drops"]["duplicate_cid"] += 1 report["drops"]["duplicate_source_kept_first"] += 1 if len(report["drop_samples"]["duplicate_cid"]) < 20: report["drop_samples"]["duplicate_cid"].append(rec.get("source_id")) return cid_seen.add(cid)
slug = "" if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"): slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
children_by_law: dict[str, list[dict[str, Any]]] = {} if not articles_empty: for _, row in articles.iterrows(): lid = _row_get(row, "law_id") if not lid: continue children_by_law.setdefault(lid, []).append( { "id": _row_get(row, "id"), "title": _row_get(row, "title"), "article_number": _row_get(row, "article_number"), "body": _row_get(row, "text"), "row": row, } )
reconstructed_ids: set[str] = set() running_extra_bytes = 0
def _append_law_row( instrument_id: str, parent: dict[str, Any], recon=None, ) -> None: body = parent["body"] recon_extra: dict[str, Any] = {} coverage = _coverage_from( parent["row"], parent["metadata"], articles_empty=articles_empty, sparse_fallback=sparse_fallback, ) if recon is not None and recon.reconstructed_from_articles: body = recon.body recon_extra = recon.extra_fields() coverage = f"{coverage}; reconstructed_from_articles" if not body: kids = children_by_law.get(instrument_id) or [] # Article rows that normalize to nothing are not recoverable text. if any(str(kid.get("body") or "").strip() for kid in kids): report["n_empty_parents_with_articles_not_reconstructed"] += 1 report["drops"]["empty_body"] += 1 if len(report["drop_samples"]["empty_body"]) < 20: report["drop_samples"]["empty_body"].append(instrument_id) return meta = parent["metadata"] _keep( _base_record( record_type=_instrument_record_type( meta, parent["instrument_title"], text=body, source_url=str(parent.get("source_url") or ""), language=str(parent.get("language") or ""), ), source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, instrument_title=parent["instrument_title"], law_cid=parent["law_cid"], article_number="", article_title="", body=body, jurisdiction=parent["jurisdiction"], language=parent["language"], source_url=parent["source_url"], snapshot_date=_snapshot_date(parent["row"], meta, source_meta), coverage=coverage, license_expr=parent["license"], collector=_collector(meta, source_dataset), source_id=instrument_id, extra={ "eli": parent["eli"], "identifier": parent["identifier"], "official_identifier": parent["official_identifier"], "source_type": parent["source_type"], "country": parent["country"], "law_status": parent["law_status"], "parent_law_id": "", "article_id": "", "reconstructed_from_articles": False, **_hierarchy_fields( parent["instrument_title"], body, "", language=parent["language"] ), **recon_extra, }, ) )
if sparse_fallback: report["schema_surprises"].append( f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units" )
for instrument_id, parent in law_map.items(): kids = children_by_law.get(instrument_id) or [] recon = None if reconstruct_on() and parent_needs_reconstruct(parent["body"], len(kids)): recon = reconstruct_parent( slug=slug, parent_body=parent["body"], parent_title=parent["instrument_title"], children=[ { "id": k["id"], "title": k["title"], "article_number": k["article_number"], "body": k["body"], } for k in kids ], running_extra_bytes=running_extra_bytes, sha256_hex=sha256_hex, ) running_extra_bytes += recon.extra_bytes reconstructed_ids.add(instrument_id) report["n_reconstructed_parents"] += 1 if recon.reconstruction_truncated: report["n_reconstructed_truncated"] += 1 if recon.is_stub: report["n_reconstructed_stubs"] += 1 _append_law_row(instrument_id, parent, recon)
emit_articles = use_articles or bool(reconstructed_ids) skip_body_split = emit_articles sibling_titles = { instrument_id: {_compact_line(kid["title"]) for kid in kids} for instrument_id, kids in children_by_law.items() } promoted: dict[str, list[Any]] = {} if emit_articles: for instrument_id, parent in law_map.items(): kids = children_by_law.get(instrument_id) or [] if not _needs_parent_split(kids, parent["body"]): continue units = split_structured_units(parent["body"], language=parent["language"]) covered = sum(len(unit.body) for unit in units) if len(units) >= 2 and covered >= int(0.35 * len(parent["body"])): promoted[instrument_id] = units if promoted: report["n_thin_instruments_replaced"] = len(promoted) report["schema_surprises"].append( "parent headings used for " f"{len(promoted)} instruments whose article rows were missing or thin" )
workers = 1 if emit_articles: def _note_drop(drop: str, sample: Any) -> None: if not drop: return report["drops"][drop] += 1 if sample is not None and len(report["drop_samples"][drop]) < 20: report["drop_samples"][drop].append(sample)
def _take(record: dict[str, Any] | None, drop: str, sample: Any) -> None: if drop: _note_drop(drop, sample) return if record is not None: _keep(record)
outcome_kwargs = { "law_map": law_map, "promoted": promoted, "sibling_titles": sibling_titles, "source_meta": source_meta, "source_dataset": source_dataset, "source_revision": source_revision, } workers = _cid_worker_count(int(len(articles)), cid_workers) if cid_only else 1 if workers > 1 and len(articles): import multiprocessing as mp
_CID_JOB.clear() _CID_JOB.update({"articles": articles, **outcome_kwargs}) span = 4000 spans = [ (start, min(start + span, int(len(articles)))) for start in range(0, int(len(articles)), span) ] ctx = mp.get_context("fork") with ctx.Pool(workers) as pool: for batch in pool.imap_unordered(_cid_article_span, spans, chunksize=1): for cid, drop, sample in batch: if drop: _note_drop(drop, sample) elif cid: _keep({"entry_cid": cid, "source_id": sample}) _CID_JOB.clear() else: for _, row in articles.iterrows(): _take(*_article_outcome(row, **outcome_kwargs)) for instrument_id, units in promoted.items(): parent = law_map[instrument_id] meta = parent["metadata"] report["unit"] = "structured" instrument_type = _instrument_record_type( meta, parent["instrument_title"], text=str(parent.get("body") or ""), source_url=str(parent.get("source_url") or ""), language=str(parent.get("language") or ""), ) for unit in units: _keep( _base_record( record_type=_unit_record_type( unit, instrument_type, n_units=len(units), parent_body=parent["body"], ), source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, instrument_title=parent["instrument_title"], law_cid=parent["law_cid"], article_number=unit.article_number or unit.number, article_title=unit.heading, body=unit.body, jurisdiction=parent["jurisdiction"], language=parent["language"], source_url=parent["source_url"], snapshot_date=_snapshot_date(parent["row"], meta, source_meta), coverage="structured (thin article rows replaced from the parent law)", license_expr=parent["license"], collector=_collector(meta, source_dataset), source_id=f"{instrument_id}-{unit.kind}-{unit.number}", extra={ "eli": parent["eli"], "identifier": parent["identifier"], "official_identifier": parent["official_identifier"], "source_type": parent["source_type"], "country": parent["country"], "law_status": parent["law_status"], "parent_law_id": instrument_id, "article_id": "", "hierarchy_kind": unit.kind, "hierarchy_path": unit.hierarchy_path, "title_number": unit.title_number, "chapter_number": unit.chapter_number, "part_number": unit.part_number, "section_number": unit.section_number, "subsections": list(unit.subsections), }, ) ) elif not skip_body_split: for instrument_id, parent in law_map.items(): body = parent["body"] if not body: continue meta = parent["metadata"] units = split_structured_units(body, language=parent["language"]) if units: report["unit"] = "structured" instrument_type = _instrument_record_type( meta, parent["instrument_title"], text=body, source_url=str(parent.get("source_url") or ""), language=str(parent.get("language") or ""), ) for unit in units: _keep( _base_record( record_type=_unit_record_type( unit, instrument_type, n_units=len(units), parent_body=body, ), source_dataset=source_dataset, source_revision=source_revision, instrument_id=instrument_id, instrument_title=parent["instrument_title"], law_cid=parent["law_cid"], article_number=unit.article_number or unit.number, article_title=unit.heading, body=unit.body, jurisdiction=parent["jurisdiction"], language=parent["language"], source_url=parent["source_url"], snapshot_date=_snapshot_date(parent["row"], meta, source_meta), coverage="structured (headings detected in law body)", license_expr=parent["license"], collector=_collector(meta, source_dataset), source_id=f"{instrument_id}-{unit.kind}-{unit.number}", extra={ "eli": parent["eli"], "identifier": parent["identifier"], "official_identifier": parent["official_identifier"], "source_type": parent["source_type"], "country": parent["country"], "law_status": parent["law_status"], "parent_law_id": instrument_id, "article_id": "", "hierarchy_kind": unit.kind, "hierarchy_path": unit.hierarchy_path, "title_number": unit.title_number, "chapter_number": unit.chapter_number, "part_number": unit.part_number, "section_number": unit.section_number, "subsections": list(unit.subsections), }, ) )
if cid_only: # The set comparison only needs entry_cid. Bodies stay in the source # frame and are not copied into a second corpus of Python dicts. report["cid_only"] = True report["cid_workers"] = workers report["n_before_dedupe"] = n_emitted report["n_out"] = len(cid_seen) report["n_dropped_total"] = ( report["drops"]["empty_body"] + report["drops"]["missing_instrument"] + report["drops"]["duplicate_cid"] ) frame = pd.DataFrame({"entry_cid": sorted(cid_seen)}) frame.attrs["normalization_report"] = report return frame, report
entries.sort( key=lambda r: ( r["instrument_id"], article_sort_key(r.get("article_number") or "", r["source_id"]), ) ) n_before = len(entries) seen: set[str] = set() deduped: list[dict[str, Any]] = [] for rec in entries: cid = rec["entry_cid"] if cid in seen: report["drops"]["duplicate_cid"] += 1 report["drops"]["duplicate_source_kept_first"] += 1 if len(report["drop_samples"]["duplicate_cid"]) < 20: report["drop_samples"]["duplicate_cid"].append(rec["source_id"]) continue seen.add(cid) deduped.append(rec) for i, rec in enumerate(deduped): rec["document_index"] = i rec["corpus_index"] = i
df = pd.DataFrame(deduped) if not df.empty and df["entry_cid"].duplicated().any(): raise SchemaError("Duplicate entry_cid remained after dedupe") report["n_before_dedupe"] = n_before report["n_out"] = int(len(df)) if not df.empty and "record_type" in df.columns: n_law_rows = int((df["record_type"] == "law").sum()) n_child_rows = int(df["record_type"].isin(["article", "section"]).sum()) report["n_law_rows"] = n_law_rows report["n_child_rows"] = n_child_rows report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows if n_law_rows and n_child_rows: report["unit"] = ( "law+structured" if report.get("unit") == "structured" else "law+article" ) elif n_law_rows: report["unit"] = "law" elif n_child_rows: report["unit"] = "article" report["n_dropped_total"] = ( report["drops"]["empty_body"] + report["drops"]["missing_instrument"] + report["drops"]["duplicate_cid"] ) if not df.empty: report["language_breakdown"] = { str(k): int(v) for k, v in df["language"].fillna("").value_counts().items() } report["record_type_breakdown"] = { str(k): int(v) for k, v in df["record_type"].value_counts().items() } report["jurisdiction_breakdown"] = { str(k): int(v) for k, v in df["jurisdiction"].fillna("").value_counts().items() } snapshot_dates = sorted({str(x) for x in df["snapshot_date"].fillna("") if str(x)}) report["snapshot_dates"] = snapshot_dates else: report["language_breakdown"] = {} report["record_type_breakdown"] = {} report["jurisdiction_breakdown"] = {} report["snapshot_dates"] = []
all_article_count_zero = False if "article_count" in laws.columns and len(laws): try: all_article_count_zero = int((laws["article_count"].fillna(0) == 0).sum()) == len(laws) except Exception: all_article_count_zero = False
report["quality_flags"] = { "articles_table_empty": bool(articles_empty), "sparse_article_fallback": bool(sparse_fallback), "article_law_coverage": article_law_coverage, "all_source_article_counts_zero": all_article_count_zero, "article_extraction_status_counts": dict(extraction_statuses), "missing_date": bool("date" in laws.columns and laws["date"].isna().all()) if len(laws) else False, "missing_date_issued": bool("date_issued" in laws.columns and laws["date_issued"].isna().all()) if len(laws) else False, "eli_present": bool("eli" in laws.columns and laws["eli"].notna().any()) if len(laws) else False, "never_invented_legal_text": True, "empty_bodies_dropped": report["drops"]["empty_body"], "duplicate_cids_dropped": report["drops"]["duplicate_cid"], } from .profiles import majority_language, score_heading_languages
sample_text = "" if not df.empty and "body" in df.columns: sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist()) if "title" in df.columns: sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text heading_langs = score_heading_languages(sample_text) report["heading_language_counts"] = dict(heading_langs) report["heading_language_majority"] = majority_language(heading_langs) report["document_language_majority"] = None if report.get("language_breakdown"): report["document_language_majority"] = max( report["language_breakdown"].items(), key=lambda kv: kv[1] )[0] from .verify import verify_normalized_corpus
report["verification"] = verify_normalized_corpus(df, report) df.attrs["normalization_report"] = report return df, report123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621"""Improve the row normalizer, then let that script normalize every row.
``scan`` and ``apply`` only call ``normalize_legal_text``. They do not importthe LLM router, so one subprocess per country does not boot a model.
``improve`` imports ``llm_router`` once. Each pass sends a short batch oflines the current script still leaves in place. The model proposes whole-linepatterns. A pattern is stored only when it matches one of those lines, missesevery held-out legal sentence, and the script then actually drops the line.Accepted patterns live in ``data/learned_line_patterns.json`` and are appliedby the same script that normalizes the rows. The model never rewrites a row."""
from __future__ import annotations
import hashlibimport jsonimport osimport refrom collections import Counterfrom concurrent.futures import ProcessPoolExecutor, as_completedfrom pathlib import Pathfrom typing import Any, Callable, Sequence
from .catalog import EXCLUDED_SLUGSfrom .structure import learned_patterns_path, normalize_legal_text
GenerateText = Callable[[str], str]
# Sentences the learned rules must not delete. Whole-line patterns that# full-match any of these are discarded.KEEP_LINES = ( "Article 1 The present Act applies throughout the territory and binds every person.", "The court in Malawi shall apply the Public Roads Act throughout the territory.", "2. Amendment of section 5 of Cap. 122A", "publié au Journal Officiel et entre en vigueur sur tout le territoire.", "10 dicembre 1948", "Quarta-Feira de Cinzas continua a ser feriado nacional.", "Phone: +1 202 555 0100 is the number appointed under this section.", "Troubleshoot faulty system.", "100 GENERAL PROVISIONS", "applicable rule applies throughout the territory.", "The register is published at www.example.com for public inspection under this Act.", "بسم الله الرحمن الرحيم", "Done at Brussels, 25 June 1999.", "2", "10", "published in the Gazette.", "Gazetted 1 October 2009", "Lycée : séries ES, L et S", "au Journal Officiel", "Subs. ibid., for “local official Gazette”.", "(a) books (excluding printed music and periodicals) ;", "Act 19 Copyright and Neighbouring Rights Act 2006",)
# One local-model window is 1024 tokens. Keep the prompt well under that.PROMPT_CHAR_BUDGET = 1600_PROMPT_PREFIX = ( "These lines survived legal-text normalization. " 'Propose JSON only: {"line_patterns": ["^...$"]}. ' "Each pattern must match one whole chrome line (page header, site footer, " "printer stamp) and must not match a legal sentence. Do not write legal text. " 'If none are safe, return {"line_patterns": []}.\n')
def cache_packs(cache_dir: Path, slug: str | None = None) -> list[tuple[str, Path]]: packs: list[tuple[str, Path]] = [] for path in sorted(cache_dir.glob("*_corpus.parquet")): name = path.name[: -len("_corpus.parquet")] if name in EXCLUDED_SLUGS or not name: continue if slug is not None and name != slug: continue packs.append((name, path)) return packs
_HEADING_LINE = re.compile( r"(?i)^(article|art\.|section|chapter|part|subtopic|§)\b")_CHROME_HINT = re.compile( r"(?i)(translated|serial number|copyright|gazette|https?://|www\.|" r"\bpage\b|printed|journal officiel|série|series\b)")# Repeated lines that are still the law, not a banner. The router must not see them._PROVISION_LINE = re.compile( r"(?i)(publi[eé]|lycée|lycee|newspaper|days after|série cei|série en |" r"\bshall\b|\bmust\b|inserted sig|the gazette\.$|in the gazette\.$|" r"\bgazetted\b|\bau journal officiel\b|subs\.\s*ibid|" r"excluding printed|whether or not printed|neighbouring rights|" r"série de classe|note de bas de page|communaut[eé]s europ)")
def scan_pack(path: Path, *, sample_lines: int = 40) -> dict[str, Any]: """Count rows and keep the repeated short lines the script did not remove.""" import pyarrow.parquet as pq
pf = pq.ParquetFile(path) if "body" not in set(pf.schema_arrow.names): raise ValueError(f"{path.name} has no body column") short: Counter[str] = Counter() n = 0 n_changed = 0 n_unstable = 0 for batch in pf.iter_batches(batch_size=512, columns=["body"]): for body in batch.column("body").to_pylist(): if body is None: continue original = body if isinstance(body, str) else str(body) n += 1 normalized = normalize_legal_text(original) if normalized != original: n_changed += 1 if normalize_legal_text(normalized) != normalized: n_unstable += 1 for line in normalized.splitlines(): stripped = line.strip() if not stripped or len(stripped) > 60 or _HEADING_LINE.match(stripped): continue if not _CHROME_HINT.search(stripped): continue if stripped in short or len(short) < 20000: short[stripped] += 1 leftovers = [ {"line": line, "count": count} for line, count in short.most_common(sample_lines) if count >= 3 ] return { "n": n, "n_changed": n_changed, "n_unstable": n_unstable, "leftovers": leftovers, }
def apply_pack(path: Path, out_path: Path) -> dict[str, Any]: """Rewrite every body with the current script. No model is loaded.""" import pyarrow as pa import pyarrow.parquet as pq
pf = pq.ParquetFile(path) if "body" not in set(pf.schema_arrow.names): raise ValueError(f"{path.name} has no body column") out_path.parent.mkdir(parents=True, exist_ok=True) tmp = out_path.with_suffix(out_path.suffix + ".partial") writer = pq.ParquetWriter(tmp, pf.schema_arrow) n = 0 n_changed = 0 try: for batch in pf.iter_batches(batch_size=256): bodies = batch.column("body").to_pylist() rewritten: list[Any] = [] for body in bodies: if body is None: rewritten.append(None) continue original = body if isinstance(body, str) else str(body) n += 1 normalized = normalize_legal_text(original) if normalized != original: n_changed += 1 rewritten.append(normalized) index = batch.schema.get_field_index("body") arrays = [batch.column(i) for i in range(batch.num_columns)] arrays[index] = pa.array(rewritten, type=batch.schema.field("body").type) writer.write_batch(pa.record_batch(arrays, schema=batch.schema)) except Exception: writer.close() tmp.unlink(missing_ok=True) raise writer.close() tmp.replace(out_path) return {"n": n, "n_changed": n_changed}
def _safe_pattern(pattern: str) -> bool: if not isinstance(pattern, str) or not pattern.startswith("^") or not pattern.endswith("$"): return False if not 4 <= len(pattern) <= 180: return False if len(re.findall(r"\.\*|\.\+", pattern)) > 2: return False if re.search(r"\([^)]*[+*][^)]*\)[+*{]", pattern): return False try: re.compile(pattern, re.IGNORECASE) except re.error: return False return True
def _blocked_candidate(line: str) -> bool: """Publication sentences, headings, and mid-sentence fragments stay in the row.""" if _PROVISION_LINE.search(line) or _HEADING_LINE.match(line): return True if len(line) <= 3: return True return line.endswith((",", ";", " or", " and"))
def accept_line_patterns( proposals: Sequence[str], leftovers: Sequence[str], existing: Sequence[str] = (), *, must_hit: Sequence[str] | None = None,) -> list[str]: """Keep a proposal only when it hits a leftover and misses every held-out sentence.""" accepted: list[str] = [] seen = set(existing) pool = [line.strip() for line in leftovers if line and str(line).strip()] required = pool if must_hit is None else [line.strip() for line in must_hit if line and str(line).strip()] for pattern in proposals: if pattern in seen or not _safe_pattern(pattern): continue compiled = re.compile(pattern, re.IGNORECASE) if any(compiled.fullmatch(line.strip()) for line in KEEP_LINES): continue if compiled.fullmatch("2") or compiled.fullmatch("10"): continue hits = [line for line in pool if compiled.fullmatch(line)] if not hits: continue if required and not any(compiled.fullmatch(line) for line in required): continue if any(_blocked_candidate(line) for line in hits): continue accepted.append(pattern) seen.add(pattern) return accepted
def line_still_present(line: str) -> bool: """True when the current script still leaves this exact line in place.""" probe = ( line + "\nArticle 1 The present Act applies throughout the territory and binds every person." ) normalized = normalize_legal_text(probe) return line in normalized.splitlines()
def router_candidates( leftovers: Sequence[dict[str, Any]], limit: int = 40, *, skip: set[str] | None = None, presence: dict[str, bool] | None = None,) -> list[dict[str, Any]]: """Banners the script still keeps, in leftover order, excluding provision lines.""" chosen: list[dict[str, Any]] = [] seen: set[str] = set() held = skip or set() known = presence if presence is not None else {} for item in leftovers: line = str(item.get("line") or "").strip() if not line or line in seen or line in held: continue if line not in known: known[line] = line_still_present(line) if not known[line] or _blocked_candidate(line): continue seen.add(line) chosen.append({"line": line, "count": int(item.get("count") or 0)}) if len(chosen) >= limit: break return chosen
def _cluster_key(line: str) -> str: shape = re.sub(r"\d+", "0", line.casefold()) shape = re.sub(r"[^\w\s]+", " ", shape, flags=re.UNICODE) shape = re.sub(r"\s+", " ", shape).strip() return " ".join(shape.split()[:4])
def largest_cluster(candidates: Sequence[dict[str, Any]], limit: int) -> list[dict[str, Any]]: """The repeated family with the highest total count, capped to one prompt.""" groups: dict[str, list[dict[str, Any]]] = {} for item in candidates: groups.setdefault(_cluster_key(str(item["line"])), []).append(item) best = max(groups.values(), key=lambda group: sum(int(item["count"]) for item in group)) best.sort(key=lambda item: int(item["count"]), reverse=True) return best[:limit]
_BARE_PATTERN = re.compile(r"\^[^\n]{1,180}\$")
def _patterns_from_model_text(raw: str) -> list[str]: """Read whole-line patterns from JSON, or from a model that skipped the JSON.""" start, end = raw.find("{"), raw.rfind("}") if start >= 0 and end > start: try: payload = json.loads(raw[start : end + 1]) except json.JSONDecodeError: payload = None found = payload.get("line_patterns") if isinstance(payload, dict) else None if isinstance(found, list): return [item for item in found if isinstance(item, str)] seen: set[str] = set() bare: list[str] = [] for item in _BARE_PATTERN.findall(raw): if item not in seen and item != "^...$": seen.add(item) bare.append(item) return bare
def propose_line_patterns( leftovers: Sequence[dict[str, Any]], generate_text: GenerateText, *, char_budget: int = PROMPT_CHAR_BUDGET,) -> list[str]: """One router call. The model proposes whole-line patterns, not statute text.""" if not leftovers: return [] body: list[str] = [] used = len(_PROMPT_PREFIX) for item in leftovers: row = f"- {item['count']}× {item['line']}\n" if used + len(row) > char_budget: break body.append(row) used += len(row) if not body: room = max(0, char_budget - len(_PROMPT_PREFIX) - 16) snippet = str(leftovers[0]["line"])[:room] body.append(f"- {leftovers[0]['count']}× {snippet}\n") raw = str(generate_text(_PROMPT_PREFIX + "".join(body))) return _patterns_from_model_text(raw)
def load_learned_patterns() -> list[str]: path = learned_patterns_path() if not path.is_file(): return [] try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return [] return [item for item in payload.get("patterns") or [] if isinstance(item, str)]
def save_learned_patterns(patterns: Sequence[str]) -> None: path = learned_patterns_path() path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps({"patterns": list(patterns)}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", ) # The structure cache keys on mtime; the write updates it.
def unresolved_path(report_dir: Path) -> Path: return report_dir / "_unresolved.json"
def load_unresolved(report_dir: Path) -> set[str]: path = unresolved_path(report_dir) if not path.is_file(): return set() try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return set() return {item.strip() for item in payload.get("lines") or [] if isinstance(item, str) and item.strip()}
def save_unresolved(report_dir: Path, lines: set[str]) -> None: path = unresolved_path(report_dir) path.parent.mkdir(parents=True, exist_ok=True) path.write_text( json.dumps({"lines": sorted(lines)}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8", )
def collect_leftovers(report_dir: Path) -> list[dict[str, Any]]: """Merge per-country residual lines. Counts for the same line are summed.""" counts: Counter[str] = Counter() if not report_dir.is_dir(): return [] for path in sorted(report_dir.glob("*.json")): if path.name.startswith("_"): continue try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): continue for item in payload.get("leftovers") or []: if isinstance(item, dict) and isinstance(item.get("line"), str): line = item["line"].strip() if line: counts[line] += int(item.get("count") or 0) return [{"line": line, "count": count} for line, count in counts.most_common()]
def improve_from_reports( report_dir: Path, generate_text: GenerateText, *, max_passes: int = 40, batch_size: int = 12, char_budget: int = PROMPT_CHAR_BUDGET, on_pass: Callable[[dict[str, Any]], None] | None = None, reset_unresolved: bool = False,) -> dict[str, Any]: """Ask the router, one short batch at a time, for rules the script can apply.
A batch is one repeated family. Patterns that do not remove a line, or that also match a publication sentence, are not stored. Families the model cannot safely pattern are remembered so the next batch is a different family. """ merged = collect_leftovers(report_dir) pool_lines = [str(item["line"]) for item in merged] presence: dict[str, bool] = {} skip = set() if reset_unresolved else load_unresolved(report_dir) existing = load_learned_patterns() accepted_all: list[str] = [] removed_lines: list[str] = [] proposed = 0 passes = 0
def _emit(row: dict[str, Any]) -> None: if on_pass is not None: on_pass(row)
for pass_no in range(1, max(1, max_passes) + 1): pending = router_candidates(merged, limit=100_000, skip=skip, presence=presence) if not pending: break batch = largest_cluster(pending, batch_size) cluster = _cluster_key(str(batch[0]["line"])) _emit({ "event": "prompt", "pass": pass_no, "cluster": cluster, "batch_id": hashlib.sha256(cluster.encode("utf-8")).hexdigest()[:8], "candidates": len(batch), "lines": [str(item["line"]) for item in batch], }) try: proposals = propose_line_patterns(batch, generate_text, char_budget=char_budget) except Exception as exc: passes += 1 _emit({"event": "pass", "pass": pass_no, "cluster": cluster, "error": str(exc)}) break proposed += len(proposals) accepted = accept_line_patterns(proposals, pool_lines, existing, must_hit=[str(item["line"]) for item in batch]) before = list(existing) kept: list[str] = [] removed_now: list[str] = [] if accepted: save_learned_patterns([*before, *accepted]) for pattern in accepted: compiled = re.compile(pattern, re.IGNORECASE) hits = [line for line in pool_lines if compiled.fullmatch(line)] dropped = [line for line in hits if not line_still_present(line)] if not dropped: continue kept.append(pattern) removed_now.extend(dropped) if kept != accepted: save_learned_patterns([*before, *kept]) if not kept: skip.update(str(item["line"]) for item in batch) else: for line in removed_now: presence[line] = False skip.discard(line) if line not in removed_lines: removed_lines.append(line) existing = [*before, *kept] accepted_all.extend(kept) passes += 1 _emit({ "event": "pass", "pass": pass_no, "cluster": cluster, "proposed": len(proposals), "accepted": kept, "removed": len(removed_now), })
save_unresolved(report_dir, skip) withheld = 0 for item in merged: line = str(item["line"]) if line not in presence: presence[line] = line_still_present(line) if presence[line] and _blocked_candidate(line): withheld += 1 remaining = router_candidates(merged, limit=100_000, skip=skip, presence=presence) return { "proposed": proposed, "accepted": accepted_all, "leftover_lines": len(merged), "removed": len(removed_lines), "removed_lines": removed_lines[:40], "unresolved": len(skip), "withheld": withheld, "remaining": len(remaining), "passes": passes, }
def worker_count(requested: int | None) -> int: if requested is not None: return max(1, int(requested)) return max(1, os.cpu_count() or 1)
def _scan_job(job: tuple[str, str, str]) -> dict[str, Any]: slug, path, report_dir = job stats = scan_pack(Path(path)) write_scan(Path(report_dir), slug, stats) return {"slug": slug, "n": stats["n"], "n_changed": stats["n_changed"], "n_unstable": stats["n_unstable"], "leftovers": len(stats["leftovers"])}
def _apply_job(job: tuple[str, str, str]) -> dict[str, Any]: slug, path, out_dir = job out_path = Path(out_dir) / Path(path).name stats = apply_pack(Path(path), out_path) return {"slug": slug, "out": str(out_path), **stats}
def run_parallel( jobs: Sequence[tuple[str, str, str]], worker, workers: int | None, *, progress_path: Path | None = None, on_done: Callable[[dict[str, Any]], None] | None = None,) -> list[dict[str, Any]]: """One process per batch of countries. Each country writes its own file.
Progress is recorded in the parent as each country finishes, so a later run can skip those slugs. """ count = worker_count(workers)
def _finish(row: dict[str, Any]) -> dict[str, Any]: if progress_path is not None: append_progress(progress_path, row) if on_done is not None: on_done(row) return row
if count == 1 or len(jobs) <= 1: return [_finish(worker(job)) for job in jobs] rows: list[dict[str, Any]] = [] with ProcessPoolExecutor(max_workers=min(count, len(jobs))) as pool: futures = {pool.submit(worker, job): job[0] for job in jobs} for future in as_completed(futures): slug = futures[future] try: row = future.result() except Exception as exc: row = {"slug": slug, "error": str(exc)} rows.append(_finish(row)) rows.sort(key=lambda row: str(row.get("slug") or "")) return rows
def write_scan(report_dir: Path, slug: str, stats: dict[str, Any]) -> Path: report_dir.mkdir(parents=True, exist_ok=True) path = report_dir / f"{slug}.json" tmp = path.with_suffix(".json.tmp") tmp.write_text(json.dumps({"slug": slug, **stats}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8") tmp.replace(path) return path
def scan_done(report_dir: Path, slug: str) -> bool: path = report_dir / f"{slug}.json" if not path.is_file(): return False try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): return False return isinstance(payload.get("n"), int)
def apply_done(out_dir: Path, slug: str) -> bool: path = out_dir / f"{slug}_corpus.parquet" if not path.is_file() or path.stat().st_size < 12: return False with path.open("rb") as handle: if handle.read(4) != b"PAR1": return False handle.seek(-4, 2) return handle.read(4) == b"PAR1"
def append_progress(path: Path, row: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(row, ensure_ascii=False) + "\n") handle.flush()
def load_generate_text() -> GenerateText: """Import the router once per process. Scan and apply never call this.""" from ipfs_datasets_py.llm_router import generate_text
return generate_text
def default_paths(root: Path) -> dict[str, Path]: return { "cache": root / "cache", "reports": root / "reports" / "residuals", "out": root / "llm-normalized", }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010"""Write country-laws-ir-graphrag/v1 thin-client layout (SkillCenter / publicus-ir family)."""
from __future__ import annotations
import gcimport jsonimport pickleimport shutilfrom pathlib import Pathfrom typing import Any
import pandas as pd
from . import LAYOUT_FAMILY, MAX_ROWS_PER_FILE, SCHEMA_VERSION, __version__from .catalog import target_repofrom .cidutil import file_descriptorfrom .parquet_io import write_parquet, write_sharded
ADJ_POINTERS_PER_ROW = 4096ADJ_POINTERS_PER_SHARD = 8192
def _index_df(rows: list[dict[str, Any]]) -> pd.DataFrame: return pd.DataFrame(rows)
def package_release( out: Path, corpus: pd.DataFrame, bm25: dict[str, Any], graph: dict[str, Any], vectors: dict[str, Any], source_meta: dict[str, Any], country: dict[str, Any], code_root: Path, normalization_report: dict[str, Any] | None = None, extra_manifest: dict[str, Any] | None = None, wipe: bool = True, skip_bm25_graph: bool = False,) -> dict[str, Any]: if wipe and out.exists(): shutil.rmtree(out) out.mkdir(parents=True, exist_ok=True) indexes_dir = out / "indexes" indexes_dir.mkdir(parents=True, exist_ok=True)
corpus_idx = write_sharded( corpus, out / "data" / "corpus", "data/corpus", kind="corpus", key_col="entry_cid", index_col="document_index", ) write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
if skip_bm25_graph: bm25_doc_idx = [] posting_idx = [] postings = pd.DataFrame() node_idx = [] edge_idx = [] in_idx = [] out_idx = [] incoming = pd.DataFrame() outgoing = pd.DataFrame() bm25 = bm25 or {"documents": pd.DataFrame(), "postings": pd.DataFrame(), "stats": {}} graph = graph or {"nodes": pd.DataFrame(), "edges": pd.DataFrame(), "stats": {}} else: bm25_doc_idx = write_sharded( bm25["documents"], out / "data" / "bm25" / "documents", "data/bm25/documents", kind="bm25_documents", key_col="entry_cid", index_col="document_index", ) write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
postings = bm25["postings"] posting_idx = write_sharded( postings, out / "data" / "bm25" / "postings", "data/bm25/postings", kind="bm25_postings", key_col="term", ) for row, part_start in zip(posting_idx, range(len(posting_idx))): shard_df = postings.iloc[ part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE ] row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0 row["posting_count"] = ( int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0 ) row["token_instance_count"] = row["posting_count"] write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
node_idx = write_sharded( graph["nodes"], out / "data" / "graph" / "nodes", "data/graph/nodes", kind="graph_nodes", key_col="node_cid", ) write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
edge_idx = write_sharded( graph["edges"], out / "data" / "graph" / "edges", "data/graph/edges", kind="graph_edges", key_col="edge_cid", ) write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
incoming = graph["incoming"] outgoing = graph["outgoing"] in_idx = write_sharded( incoming if incoming is not None and not incoming.empty else pd.DataFrame(columns=["node_cid", "page_index", "direction"]), out / "data" / "graph" / "adjacency" / "incoming", "data/graph/adjacency/incoming", kind="graph_incoming_adjacency", key_col="node_cid", ) out_idx = write_sharded( outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame(columns=["node_cid", "page_index", "direction"]), out / "data" / "graph" / "adjacency" / "outgoing", "data/graph/adjacency/outgoing", kind="graph_outgoing_adjacency", key_col="node_cid", ) for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")): for r in rows: r["direction"] = direction r["adjacency_count"] = r.get("row_count", 0) r["node_count"] = r.get("row_count", 0) r["first_page_index"] = 0 r["last_page_index"] = 0 write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx)) write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
vectors_df = vectors["vectors"] # Drop null embeddings for stub releases so parquet stays typed; keep rows when present. if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all(): vectors_write = vectors_df.drop(columns=["embedding"]) vectors_write["embedding_status"] = "stub_missing" else: vectors_write = vectors_df vec_idx = write_sharded( vectors_write, out / "data" / "vectors", "data/vectors", kind="vectors", key_col="entry_cid", index_col="document_index", ) meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]} for r in vec_idx: m = meta_by_cluster.get(r["shard_id"], {}) r["centroid"] = m.get("centroid", []) r["shard_centroid"] = m.get("shard_centroid", []) r["centroid_min_score"] = m.get("centroid_min_score", 0.0) r["centroid_shard_count"] = m.get("centroid_shard_count", 1) r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0) r["cluster_id"] = m.get("cluster_id", r["shard_id"]) r["dimension"] = 384 r["model_name"] = "thenlper/gte-small" if m.get("stub"): r["stub"] = True r["stub_reason"] = m.get("stub_reason", "") write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx))
# Bundle package + scripts into the release pkg_src = Path(__file__).resolve().parent dest_pkg = out / "country_laws_ir" shutil.copytree( pkg_src, dest_pkg, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"), ) scripts_dir = out / "scripts" scripts_dir.mkdir(exist_ok=True) for name in ( "build_country_laws_ir.py", "normalize_country_laws.py", "query_country_laws_hf.py", "query_country_laws_ir.py", "generate_country_laws_ir.py", ): src = code_root / "scripts" / name if src.exists(): shutil.copy2(src, scripts_dir / name) shutil.copy2(pkg_src / "normalize.py", out / "normalize.py") shutil.copy2(pkg_src / "query.py", out / "query.py") shutil.copy2(pkg_src / "build.py", out / "build.py") _write_skill(out, country, hub_id=target_repo(country["slug"]))
reports_dir = out / "reports" reports_dir.mkdir(exist_ok=True) if normalization_report is not None: payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n" (out / "normalization_report.json").write_text(payload, encoding="utf-8") (reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0 n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0 counts = { "bm25_document_chunks": len(bm25_doc_idx), "bm25_documents": int(len(bm25["documents"])), "bm25_keyword_shards": len(posting_idx), "bm25_posting_rows": int(len(postings)), "bm25_postings": int((bm25.get("stats") or {}).get("n_postings") or 0), "bm25_terms": int((bm25.get("stats") or {}).get("n_terms") or 0), "corpus_chunks": len(corpus_idx), "corpus_rows": int(len(corpus)), "graph_edge_chunks": len(edge_idx), "graph_edges": int(len(graph["edges"])), "graph_incoming_adjacency_edges": int(len(graph["edges"])), "graph_incoming_adjacency_rows": int(len(incoming)) if incoming is not None else 0, "graph_incoming_adjacency_shards": len(in_idx), "graph_node_chunks": len(node_idx), "graph_nodes": int(len(graph["nodes"])), "graph_outgoing_adjacency_edges": int(len(graph["edges"])), "graph_outgoing_adjacency_rows": int(len(outgoing)) if outgoing is not None else 0, "graph_outgoing_adjacency_shards": len(out_idx), "vector_chunks": len(vec_idx), "vector_rows": int(len(vectors_df)), "n_laws": n_laws, "n_articles": n_articles, } if skip_bm25_graph and extra_manifest and extra_manifest.get("sparse"): sparse = extra_manifest["sparse"] bm25_counts = (sparse.get("bm25") or {}).get("counts") or {} graph_counts = sparse.get("graph") or {} counts.update( {k: int(v) for k, v in bm25_counts.items() if isinstance(v, (int, float))} ) if graph_counts.get("node_count") is not None: counts["graph_nodes"] = int(graph_counts["node_count"]) if graph_counts.get("edge_count") is not None: counts["graph_edges"] = int(graph_counts["edge_count"])
def idx_desc(name: str) -> dict[str, Any]: path = indexes_dir / name if not path.is_file(): return {"relative_path": f"indexes/{name}", "present": False} return file_descriptor(path, f"indexes/{name}")
hub_id = target_repo(country["slug"]) bm25_stats = bm25.get("stats") if isinstance(bm25.get("stats"), dict) else {} graph_stats = graph.get("stats") if isinstance(graph.get("stats"), dict) else {} edge_types = graph_stats.get("edge_types") or [ "HAS_JURISDICTION", "HAS_LANGUAGE", "BELONGS_TO_LAW", "HAS_ARTICLE", "BM25_NEIGHBOR_OF", ] manifest = { "schema_version": SCHEMA_VERSION, "layout_family": LAYOUT_FAMILY, "packager_version": __version__, "primary_key": "entry_cid", "dataset_id": source_meta["source_dataset"], "dataset_repo_id": hub_id, "dataset_revision": source_meta["source_revision"], "country": country, "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.", "bm25": { k: bm25_stats.get(k) for k in ( "k1", "b", "title_weight", "body_weight", "average_document_length", "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard", ) }, "counts": counts, "parquet": { "compression": "zstd", "compression_level": 6, "max_rows_per_file": MAX_ROWS_PER_FILE, "row_group_size": MAX_ROWS_PER_FILE, "query_engine": "duckdb", }, "graph": { "adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW, "adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD, "directions": ["incoming", "outgoing"], "max_remote_walk_depth": 8, "ordering": "score_desc_nulls_last", "edge_types": edge_types, }, "vector": vectors["stats"], "canonical_fields": [ "entry_cid", "law_cid", "record_type", "jurisdiction", "language", "instrument_id", "instrument_title", "article_number", "article_title", "title", "body", "source_url", "snapshot_date", "coverage", "license", "collector", "source_dataset", "source_revision", ], "input_sha256": { "laws.parquet": source_meta.get("laws_sha256"), "articles.parquet": source_meta.get("articles_sha256"), }, "model_id": (vectors.get("stats") or {}).get("model_name", "thenlper/gte-small"), "cid": { "codec": "raw", "hash": "sha2-256", "multibase": "base32", "payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')", }, "normalization": normalization_report or {}, "schema_mapping": { "laws": { "id": "instrument_id", "title": "instrument_title", "text": "body", "article_count_dtype_source": source_meta.get("article_count_dtype"), }, "articles": { "id": "source_id / article identity", "law_id": "instrument_id", "title": "article_title", "text": "body", }, "unit_policy": "prefer articles; fall back to law-level when articles empty", "required_law_columns": ["id", "title", "text"], "required_article_columns": ["id", "law_id", "title", "text"], "fail_closed": True, "notes": ( "Malta and Germany share the same column names. Drift: Malta article_count " "is int64, Germany article_count is int32; Germany eli is often null. " "Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family." ), }, "indexes": { "bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"), "bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"), "corpus_chunks": idx_desc("corpus_chunks.parquet"), "graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"), "graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"), "graph_node_chunks": idx_desc("graph_node_chunks.parquet"), "graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"), "vector_chunks": idx_desc("vector_chunks.parquet"), }, "source": source_meta, } if extra_manifest: manifest.update(extra_manifest) (out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8") _write_readme( out, country, source_meta, counts, bm25_stats, graph_stats, vectors.get("stats") if isinstance(vectors.get("stats"), dict) else {}, hub_id, normalization_report=normalization_report, ) _write_gitattributes(out) _write_dataset_configs(out) return manifest
def _write_dataset_configs(out: Path) -> None: configs = { "country-laws-ir-graphrag/v1": { "data_files": { "corpus": "data/corpus/*.parquet", "bm25_documents": "data/bm25/documents/*.parquet", "bm25_postings": "data/bm25/postings/*.parquet", "graph_nodes": "data/graph/nodes/*.parquet", "graph_edges": "data/graph/edges/*.parquet", "graph_adjacency_out": "data/graph/adjacency/out/*.parquet", "graph_adjacency_in": "data/graph/adjacency/in/*.parquet", "vectors": "data/vectors/*.parquet", } } } (out / "dataset_configs.json").write_text( json.dumps(configs, indent=2) + "\n", encoding="utf-8" )
def _write_gitattributes(out: Path) -> None: (out / ".gitattributes").write_text( "*.parquet filter=lfs diff=lfs merge=lfs -text\n" "*.bin filter=lfs diff=lfs merge=lfs -text\n", encoding="utf-8", )
def _size_category(n: int) -> str: if n < 1000: return "n<1K" if n < 10_000: return "1K<n<10K" if n < 100_000: return "10K<n<100K" if n < 1_000_000: return "100K<n<1M" if n < 10_000_000: return "1M<n<10M" return "n>10M"
def _card_languages(normalization_report: dict[str, Any] | None) -> list[str]: if not normalization_report: return [] seen: list[str] = [] majority = str(normalization_report.get("document_language_majority") or "").strip() breakdown = normalization_report.get("language_breakdown") or {} ordered = [] if majority: ordered.append(majority) ordered.extend( sorted( (str(k) for k in breakdown if k), key=lambda k: -int(breakdown.get(k) or 0), ) ) for raw in ordered: lang = str(raw).strip().lower().replace("_", "-").split("-")[0] if lang and lang not in seen and lang not in {"und", "none", "null"}: seen.append(lang) if len(seen) >= 8: break return seen
def _adj_glob(out: Path, direction: str) -> str: aliases = { "out": ("out", "outgoing"), "in": ("in", "incoming"), } for name in aliases.get(direction, (direction,)): if (out / "data" / "graph" / "adjacency" / name).is_dir(): return f"data/graph/adjacency/{name}/*.parquet" return f"data/graph/adjacency/{direction}/*.parquet"
def _write_readme( out: Path, country: dict[str, Any], source_meta: dict[str, Any], counts: dict[str, Any], bm25_stats: dict[str, Any], graph_stats: dict[str, Any], vector_stats: dict[str, Any], hub_id: str, normalization_report: dict[str, Any] | None = None,) -> None: slug = country["slug"] name = country.get("name") or slug src = source_meta.get("source_dataset") or "" rev = source_meta.get("source_revision") or "" vec_status = (vector_stats or {}).get("status", "embedded") n_docs = int((counts or {}).get("corpus_rows") or 0) languages = _card_languages(normalization_report) import yaml
card = { "license": "other", "task_categories": ["text-retrieval"], "tags": [ "legal", "law", "graphrag", "bm25", "research", "not-legal-advice", str(slug), ], "pretty_name": f"{name} laws IR (CID-keyed GraphRAG)", "size_categories": [_size_category(n_docs)], "configs": [ {"config_name": "corpus", "data_files": [{"split": "train", "path": "data/corpus/*.parquet"}]}, {"config_name": "bm25_documents", "data_files": [{"split": "train", "path": "data/bm25/documents/*.parquet"}]}, {"config_name": "bm25_postings", "data_files": [{"split": "train", "path": "data/bm25/postings/*.parquet"}]}, {"config_name": "bm25_keyword_index", "data_files": [{"split": "train", "path": "indexes/bm25_keyword_shards.parquet"}]}, {"config_name": "vectors", "data_files": [{"split": "train", "path": "data/vectors/*.parquet"}]}, {"config_name": "vector_meta_index", "data_files": [{"split": "train", "path": "indexes/vector_chunks.parquet"}]}, {"config_name": "graph_nodes", "data_files": [{"split": "train", "path": "data/graph/nodes/*.parquet"}]}, {"config_name": "graph_edges", "data_files": [{"split": "train", "path": "data/graph/edges/*.parquet"}]}, {"config_name": "graph_outgoing_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "out")}]}, {"config_name": "graph_incoming_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "in")}]}, ], } if languages: card["language"] = languages front = yaml.safe_dump(card, sort_keys=False, allow_unicode=True) text = f"""---{front}---
# {name} legislation IR (CID-keyed sparse GraphRAG)
Research retrieval release of `{src}` (revision `{rev}`) packaged as`{SCHEMA_VERSION}` (layout family `{LAYOUT_FAMILY}` / publicus-ir).
**Not legal advice.** This is a research snapshot. The official gazette /authentic source of {name} prevails over this corpus. Retrieved documentsand graph edges are retrieval evidence only. No legal text was invented.
Primary key: `entry_cid` (CIDv1 raw sha2-256 of a canonical identity record).Integer `document_index` values are compact shard pointers, not identities.
Target Hub id (packaging metadata only): `{hub_id}`.
## Counts
| Field | Value || --- | --- || Laws (corpus units) | {(counts or {}).get('n_laws', 0)} || Articles (corpus units) | {(counts or {}).get('n_articles', 0)} || Canonical docs | {(counts or {}).get('corpus_rows', 0)} || BM25 terms | {(counts or {}).get('bm25_terms', 0)} || BM25 postings | {(counts or {}).get('bm25_postings', 0)} || Graph nodes | {(counts or {}).get('graph_nodes', 0)} || Graph edges | {(counts or {}).get('graph_edges', 0)} || Vectors | {(counts or {}).get('vector_rows', 0)} × {(vector_stats or {}).get('dimension', 384)}-d `{(vector_stats or {}).get('model_name', 'thenlper/gte-small')}` ({vec_status}) |
## Canonical fields
`entry_cid`, `law_cid`, `record_type`, `jurisdiction`, `language`,`instrument_id`, `instrument_title`, `article_number`, `article_title`,`title`, `body`, `source_url`, `snapshot_date`, `coverage`, `license`,`collector`, `source_dataset`, `source_revision`.
Unit policy: prefer article/section rows; fall back to law-level when`articles.parquet` is empty.
## Index layout
Zstandard parquet shards with at most 4,096 rows.
- `indexes/bm25_keyword_shards.parquet` — lexical term ranges → BM25 posting shards- `indexes/vector_chunks.parquet` — semantic routing centroids (rows sorted by cosine to shard centroid)- `indexes/corpus_chunks.parquet` — document ranges → corpus shards- `data/graph/nodes` / `data/graph/edges` — property graph- `data/graph/adjacency/{{incoming,outgoing}}` — score-ordered neighbor pages
BM25: Okapi k1=1.2, b=0.75, title_weight=5, body_weight=1 (FTS5 unicode61-style tokenizer).
Graph: one node per `entry_cid` plus facet nodes (`_facet_cid(kind, value)` forjurisdiction, language, instrument, source, status). Neighbor edges`BM25_NEIGHBOR_OF` (k=8) carry score and matched terms. Structural edges:`ARTICLE_OF` (article → parent law) when articles exist, plus `IDENTIFIED_BY_ELI`/ `IDENTIFIED_BY` only when those identifiers are present in the source.
## Query
```python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 10python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 10python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>```
## Publish later (operator)
```export HF_TOKEN=... # never commithf upload-large-folder {hub_id} . \\ --repo-type dataset --no-private --num-workers 8 \\ --exclude "**/__pycache__/**" --exclude "**/*.pyc"```
## Provenance
Packaged by country-laws-ir. Upstream collector and official license remain thoseof `{src}`. CIDs identify local content; they do not prove public IPFS pinning.""" (out / "README.md").write_text(text, encoding="utf-8")
def _write_skill(out: Path, country: dict[str, Any], hub_id: str) -> None: skill_dir = out / "skill" / "query-country-laws-hf" skill_dir.mkdir(parents=True, exist_ok=True) name = country.get("name") or country.get("slug") slug = country.get("slug") text = f"""---name: query-country-laws-hfdescription: Query a local or Hub country-laws-ir GraphRAG release (BM25, vectors, graph neighbors). Research retrieval only — not legal advice.---
# Query country-laws-ir (SkillCenter-style sparse GraphRAG)
Thin client for `{hub_id}` / local release roots that follow`country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3`).
**Not legal advice.** Official gazettes prevail. Retrieved hits are context only.
## Local
```bashpython scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 5python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 5python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>```
Or:
```bashpython -m country_laws_ir query --local-dir /workspace/country-laws-ir/releases/ipfs_{slug}_laws_ir -- bm25 "constitution"```
## Method
- Primary key `entry_cid` (CIDv1 raw sha2-256). `document_index` is a shard pointer.- BM25 Okapi k1=1.2 b=0.75, title_weight=5, body_weight=1, FTS5-style tokenizer.- Vectors `thenlper/gte-small` 384-d, mean-pool, L2, centroid-sorted shards.- Graph: facets + `BM25_NEIGHBOR_OF` (k=8, score + matched terms) + `ARTICLE_OF`.
Do not treat retrieval as proof. Do not invent citations.""" (skill_dir / "SKILL.md").write_text(text, encoding="utf-8")
def package_release_sequential( out: Path, *, corpus_path: Path, bm25_documents_path: Path, bm25_postings_path: Path, bm25_stats: dict[str, Any], graph: dict[str, Any] | Path, vectors: dict[str, Any] | Path, source_meta: dict[str, Any], country: dict[str, Any], code_root: Path, normalization_report: dict[str, Any] | None = None, expected_rows: int | None = None, extra_manifest: dict[str, Any] | None = None,) -> dict[str, Any]: """Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
``graph`` / ``vectors`` may be in-memory dicts or pickle Paths. Loads and frees each artifact before the next. Prefer this for n>=40k. """ from .mem import checkpoint, log_mem
def _load_obj(obj_or_path): if isinstance(obj_or_path, (str, Path)): p = Path(obj_or_path) with p.open("rb") as f: return pickle.load(f) return obj_or_path
if out.exists(): shutil.rmtree(out) out.mkdir(parents=True, exist_ok=True) indexes_dir = out / "indexes" indexes_dir.mkdir(parents=True, exist_ok=True) log_mem("package_seq_start")
# --- corpus --- corpus = pd.read_parquet(corpus_path) if expected_rows is not None and len(corpus) != expected_rows: raise ValueError(f"corpus rows {len(corpus)} != expected {expected_rows}") n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0 n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0 corpus_rows = int(len(corpus)) corpus_idx = write_sharded( corpus, out / "data" / "corpus", "data/corpus", kind="corpus", key_col="entry_cid", index_col="document_index", ) write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx)) del corpus gc.collect() checkpoint("package_corpus_done")
# --- bm25 documents --- documents = pd.read_parquet(bm25_documents_path) bm25_doc_idx = write_sharded( documents, out / "data" / "bm25" / "documents", "data/bm25/documents", kind="bm25_documents", key_col="entry_cid", index_col="document_index", ) write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx)) n_bm25_docs = int(len(documents)) del documents gc.collect()
postings = pd.read_parquet(bm25_postings_path) posting_idx = write_sharded( postings, out / "data" / "bm25" / "postings", "data/bm25/postings", kind="bm25_postings", key_col="term", ) for row, part_start in zip(posting_idx, range(len(posting_idx))): shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE] row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0 row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0 row["token_instance_count"] = row["posting_count"] write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx)) n_posting_rows = int(len(postings)) del postings gc.collect() checkpoint("package_bm25_done")
# --- graph --- graph = _load_obj(graph) node_idx = write_sharded( graph["nodes"], out / "data" / "graph" / "nodes", "data/graph/nodes", kind="graph_nodes", key_col="node_cid", ) write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx)) edge_idx = write_sharded( graph["edges"], out / "data" / "graph" / "edges", "data/graph/edges", kind="graph_edges", key_col="edge_cid", ) write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx)) incoming = graph["incoming"] outgoing = graph["outgoing"] in_idx = write_sharded( incoming if incoming is not None and not incoming.empty else pd.DataFrame( columns=["node_cid", "page_index", "direction"] ), out / "data" / "graph" / "adjacency" / "incoming", "data/graph/adjacency/incoming", kind="graph_incoming_adjacency", key_col="node_cid", ) out_idx = write_sharded( outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame( columns=["node_cid", "page_index", "direction"] ), out / "data" / "graph" / "adjacency" / "outgoing", "data/graph/adjacency/outgoing", kind="graph_outgoing_adjacency", key_col="node_cid", ) for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")): for r in rows: r["direction"] = direction r["adjacency_count"] = r.get("row_count", 0) r["node_count"] = r.get("row_count", 0) r["first_page_index"] = 0 r["last_page_index"] = 0 write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx)) write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx)) gstats = graph["stats"] n_graph_nodes = int(len(graph["nodes"])) n_graph_edges = int(len(graph["edges"])) n_in = int(len(incoming)) if incoming is not None else 0 n_out = int(len(outgoing)) if outgoing is not None else 0 edge_types = gstats.get("edge_types") or [ "HAS_JURISDICTION", "HAS_LANGUAGE", "BELONGS_TO_LAW", "HAS_ARTICLE", "BM25_NEIGHBOR_OF", ] del graph, incoming, outgoing gc.collect() checkpoint("package_graph_done")
# --- vectors --- vectors = _load_obj(vectors) vectors_df = vectors["vectors"] if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all(): vectors_write = vectors_df.drop(columns=["embedding"]) vectors_write["embedding_status"] = "stub_missing" else: vectors_write = vectors_df vec_idx = write_sharded( vectors_write, out / "data" / "vectors", "data/vectors", kind="vectors", key_col="entry_cid", index_col="document_index", ) meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]} for r in vec_idx: m = meta_by_cluster.get(r["shard_id"], {}) r["centroid"] = m.get("centroid", []) r["shard_centroid"] = m.get("shard_centroid", []) r["centroid_min_score"] = m.get("centroid_min_score", 0.0) r["centroid_shard_count"] = m.get("centroid_shard_count", 1) r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0) r["cluster_id"] = m.get("cluster_id", r["shard_id"]) r["dimension"] = 384 r["model_name"] = "thenlper/gte-small" if m.get("stub"): r["stub"] = True r["stub_reason"] = m.get("stub_reason", "") write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx)) vstats = vectors["stats"] n_vectors = int(len(vectors_df)) del vectors, vectors_df, vectors_write gc.collect() checkpoint("package_vectors_done")
# --- bundle code --- pkg_src = Path(__file__).resolve().parent dest_pkg = out / "country_laws_ir" shutil.copytree( pkg_src, dest_pkg, dirs_exist_ok=True, ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"), ) scripts_dir = out / "scripts" scripts_dir.mkdir(exist_ok=True) for name in ( "build_country_laws_ir.py", "normalize_country_laws.py", "query_country_laws_hf.py", "query_country_laws_ir.py", "generate_country_laws_ir.py", ): src = code_root / "scripts" / name if src.exists(): shutil.copy2(src, scripts_dir / name) shutil.copy2(pkg_src / "normalize.py", out / "normalize.py") shutil.copy2(pkg_src / "query.py", out / "query.py") shutil.copy2(pkg_src / "build.py", out / "build.py") hub_id = target_repo(country["slug"]) _write_skill(out, country, hub_id=hub_id)
reports_dir = out / "reports" reports_dir.mkdir(exist_ok=True) if normalization_report is not None: payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n" (out / "normalization_report.json").write_text(payload, encoding="utf-8") (reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
counts = { "bm25_document_chunks": len(bm25_doc_idx), "bm25_documents": n_bm25_docs, "bm25_keyword_shards": len(posting_idx), "bm25_posting_rows": n_posting_rows, "bm25_postings": int(bm25_stats["n_postings"]), "bm25_terms": int(bm25_stats["n_terms"]), "corpus_chunks": len(corpus_idx), "corpus_rows": corpus_rows, "graph_edge_chunks": len(edge_idx), "graph_edges": n_graph_edges, "graph_incoming_adjacency_edges": n_graph_edges, "graph_incoming_adjacency_rows": n_in, "graph_incoming_adjacency_shards": len(in_idx), "graph_node_chunks": len(node_idx), "graph_nodes": n_graph_nodes, "graph_outgoing_adjacency_edges": n_graph_edges, "graph_outgoing_adjacency_rows": n_out, "graph_outgoing_adjacency_shards": len(out_idx), "vector_chunks": len(vec_idx), "vector_rows": n_vectors, "n_laws": n_laws, "n_articles": n_articles, }
def idx_desc(name: str) -> dict[str, Any]: path = indexes_dir / name if not path.is_file(): return {"relative_path": f"indexes/{name}", "present": False} return file_descriptor(path, f"indexes/{name}")
manifest = { "schema_version": SCHEMA_VERSION, "layout_family": LAYOUT_FAMILY, "packager_version": __version__, "primary_key": "entry_cid", "dataset_id": source_meta["source_dataset"], "dataset_repo_id": hub_id, "dataset_revision": source_meta["source_revision"], "country": country, "disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.", "bm25": {k: (bm25_stats or {}).get(k) for k in ( "k1", "b", "title_weight", "body_weight", "average_document_length", "tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard", ) if k in bm25_stats}, "counts": counts, "parquet": { "compression": "zstd", "compression_level": 6, "max_rows_per_file": MAX_ROWS_PER_FILE, "row_group_size": MAX_ROWS_PER_FILE, }, "graph": { "adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW, "adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD, "directions": ["incoming", "outgoing"], "max_remote_walk_depth": 8, "ordering": "score_desc_nulls_last", "edge_types": edge_types, }, "vector": vstats, "canonical_fields": [ "entry_cid", "law_cid", "record_type", "jurisdiction", "language", "instrument_id", "instrument_title", "article_number", "article_title", "title", "body", "source_url", "snapshot_date", "coverage", "license", "collector", "source_dataset", "source_revision", ], "input_sha256": { "laws.parquet": source_meta.get("laws_sha256"), "articles.parquet": source_meta.get("articles_sha256"), }, "model_id": (vstats or {}).get("model_name", "thenlper/gte-small"), "cid": { "codec": "raw", "hash": "sha2-256", "multibase": "base32", "payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')", }, "normalization": normalization_report or {}, "packaging_mode": "sequential_spill", "schema_mapping": { "laws": { "id": "instrument_id", "title": "instrument_title", "text": "body", "article_count_dtype_source": source_meta.get("article_count_dtype"), }, "articles": { "id": "source_id / article identity", "law_id": "instrument_id", "title": "article_title", "text": "body", }, "unit_policy": "prefer articles; fall back to law-level when articles empty", "required_law_columns": ["id", "title", "text"], "required_article_columns": ["id", "law_id", "title", "text"], "fail_closed": True, "notes": ( "Malta and Germany share the same column names. Drift: Malta article_count " "is int64, Germany article_count is int32; Germany eli is often null. " "Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family." ), }, "indexes": { "bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"), "bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"), "corpus_chunks": idx_desc("corpus_chunks.parquet"), "graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"), "graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"), "graph_node_chunks": idx_desc("graph_node_chunks.parquet"), "graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"), "vector_chunks": idx_desc("vector_chunks.parquet"), }, "source": source_meta, } if extra_manifest: manifest.update(extra_manifest) (out / "manifest.json").write_text( json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8" ) _write_readme( out, country, source_meta, counts, bm25_stats, gstats, vstats, hub_id, normalization_report=normalization_report, ) _write_gitattributes(out) _write_dataset_configs(out) checkpoint("package_seq_done") return manifest
def package_from_spill( out: Path, spill: Path, corpus_path: Path, source_meta: dict[str, Any], country: dict[str, Any], code_root: Path, normalization_report: dict[str, Any] | None = None, expected_rows: int | None = None, extra_manifest: dict[str, Any] | None = None,) -> dict[str, Any]: """Package from spill dir artifacts: bm25_*.parquet, bm25_stats.json, graph.pkl, vectors.pkl.""" import json as _json import pickle as _pickle
spill = Path(spill) stats_json = spill / "bm25_stats.json" stats_pkl = spill / "bm25_stats.pkl" if stats_json.is_file(): bm25_stats = _json.loads(stats_json.read_text(encoding="utf-8")) else: with stats_pkl.open("rb") as f: bm25_stats = _pickle.load(f) return package_release_sequential( out, corpus_path=Path(corpus_path), bm25_documents_path=spill / "bm25_documents.parquet", bm25_postings_path=spill / "bm25_postings.parquet", bm25_stats=bm25_stats, graph=spill / "graph.pkl", vectors=spill / "vectors.pkl", source_meta=source_meta, country=country, code_root=Path(code_root), normalization_report=normalization_report, expected_rows=expected_rows, extra_manifest=extra_manifest, )1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283"""ZSTD parquet shard writer matching skillcenter-huggingface-release/v3."""
from __future__ import annotations
import mathfrom pathlib import Pathfrom typing import Any, Iterable
import pandas as pdimport pyarrow as paimport pyarrow.parquet as pq
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSIONfrom .cidutil import file_descriptor
COMPRESSION = "zstd"COMPRESSION_LEVEL = 6
def write_parquet(path: Path, df: pd.DataFrame) -> None: path.parent.mkdir(parents=True, exist_ok=True) table = pa.Table.from_pandas(df, preserve_index=False) pq.write_table( table, path, compression=COMPRESSION, compression_level=COMPRESSION_LEVEL, row_group_size=min(MAX_ROWS_PER_FILE, max(len(df), 1)), use_dictionary=True, )
def shard_frames(df: pd.DataFrame, max_rows: int = MAX_ROWS_PER_FILE) -> list[pd.DataFrame]: if df.empty: return [df.copy()] n = int(math.ceil(len(df) / max_rows)) return [df.iloc[i * max_rows : (i + 1) * max_rows].copy() for i in range(n)]
def write_sharded( df: pd.DataFrame, out_dir: Path, relative_dir: str, kind: str, key_col: str | None = None, index_col: str | None = None, extra_index: dict | None = None,) -> list[dict[str, Any]]: out_dir.mkdir(parents=True, exist_ok=True) shards = shard_frames(df) rows: list[dict[str, Any]] = [] for i, part in enumerate(shards): name = f"part-{i:06d}.parquet" path = out_dir / name write_parquet(path, part) rel = f"{relative_dir}/{name}" first_key = last_key = "" if key_col and key_col in part.columns and not part.empty: keys = part[key_col].astype(str) first_key = keys.iloc[0] last_key = keys.iloc[-1] start_idx = end_idx = 0 if index_col and index_col in part.columns and not part.empty: start_idx = int(part[index_col].iloc[0]) end_idx = int(part[index_col].iloc[-1]) desc = file_descriptor( path, rel, extra={ "shard_id": i, "kind": kind, "row_count": int(len(part)), "first_key": first_key, "last_key": last_key, "start_document_index": start_idx, "end_document_index": end_idx, "schema_version": SCHEMA_VERSION, }, ) if extra_index: desc.update(extra_index) rows.append(desc) return rows123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342"""Per-language legal heading lexicons for country-law structure extraction.
Oregon (ORS) is English title/chapter/section. Other gazettes use their ownwords (Artikel, Titre, Artículo, 条, مادة). This table is how we *score*whether a split used the right language — not a claim that every countryhas a dedicated parser.
Languages with no lexicon (ar, zh, ja, ko, …) must not be force-split onLatin TITLE/ARTICLE markers; collectors may already have article rows."""
from __future__ import annotations
from collections import Counterimport refrom typing import Any
# keyword -> list of (kind, language); some words are shared (article).HEADING_LEXICON: dict[str, list[tuple[str, str]]] = {}
def _add(lang: str, kind: str, *words: str) -> None: for word in words: HEADING_LEXICON.setdefault(word.casefold(), []).append((kind, lang))
_add("en", "title", "title")_add("en", "chapter", "chapter")# The period is part of the token so a bare "ch" is not a heading._add("en", "chapter", "ch.")_add("en", "part", "part", "division")_add("en", "article", "article")_add("en", "section", "section", "sec.", "rule", "regulation", "schedule", "annex", "appendix")# The period is part of the token so a bare "can" is not a heading._add("la", "article", "can.")_add("fr", "section", "annexe")_add("es", "section", "anexo")_add("de", "section", "anlage")_add("nl", "section", "bijlage")_add("it", "section", "allegato")_add("pl", "section", "załącznik")_add("sv", "section", "bilaga")_add("fi", "section", "liite")_add("cs", "section", "příloha")_add("pt", "section", "anexo")
_add("fr", "title", "titre")_add("fr", "chapter", "chapitre")_add("fr", "part", "partie")_add("fr", "article", "article")_add("fr", "section", "section", "paragraphe")
_add("de", "title", "titel")_add("de", "chapter", "kapitel")_add("de", "part", "teil")_add("de", "article", "artikel")_add("de", "section", "abschnitt", "unterabschnitt", "paragraf", "anhang")
_add("nl", "title", "titel")_add("nl", "chapter", "hoofdstuk")_add("nl", "part", "deel")_add("nl", "article", "artikel")_add("nl", "section", "paragraaf", "afdeling", "kerndoel")
_add("es", "title", "título", "titulo")_add("es", "chapter", "capítulo", "capitulo", "subcapítulo", "subcapitulo")_add("es", "part", "parte")_add("es", "article", "artículo", "articulo")# The period is part of the token so a bare "arto" is not a heading._add("es", "article", "arto.")_add("es", "section", "sección", "seccion")_add("es", "article", "disposición", "disposicion")
_add("pt", "title", "título", "titulo")_add("pt", "chapter", "capítulo", "capitulo")_add("pt", "part", "parte")_add("pt", "article", "artigo")_add("pt", "section", "secção", "secao")# Brazil SUBSEÇÃO folds to subsecao. Portugal SUBSECÇÃO folds to subseccao._add("pt", "section", "subseção", "subsecção")
_add("it", "title", "titolo")_add("it", "chapter", "capitolo")_add("it", "part", "parte")_add("it", "article", "articolo")_add("it", "section", "sezione")
_add("el", "article", "άρθρο", "αρθρο")_add("el", "chapter", "κεφάλαιο")_add("el", "section", "τμήμα", "ενότητα")_add("hu", "article", "szakasz", "cikk")_add("cs", "article", "článek")# The period is part of the token so a bare "cl" is not a heading._add("cs", "article", "čl.")_add("cs", "chapter", "kapitola")_add("cs", "section", "odstavec", "odst.")_add("sk", "article", "článok")_add("sl", "article", "člen")_add("nb", "article", "artikkel")_add("sv", "article", "paragraf")_add("fi", "article", "pykälä")_add("fi", "chapter", "luku")_add("is", "article", "grein")_add("lv", "article", "pants")_add("lv", "chapter", "nodaļa")_add("et", "article", "paragrahv")_add("et", "chapter", "peatükk")_add("pl", "article", "artykuł", "artykul")_add("ro", "article", "articolul", "articol")_add("mt", "article", "artikolu")_add("zh", "article", "条", "條")_add("ar", "article", "مادة", "المادة", "الماده", "املادة", "املاده")_add("ar", "chapter", "الباب")_add("ar", "part", "الكتاب")_add("ar", "section", "الفصل", "ملحق", "الفرع", "القسم")_add("fa", "article", "ماده")_add("fa", "section", "تبصره", "بند")_add("ja", "article", "条")_add("ko", "article", "조")_add("he", "article", "סעיף")_add("he", "chapter", "פרק")_add("he", "part", "חלק")_add("he", "section", "סימן", "תוספת", "תקנה")_add("th", "article", "มาตรา")_add("th", "chapter", "หมวด")_add("th", "section", "ข้อ", "วรรค")_add("hi", "article", "धारा")_add("bn", "article", "ধারা")_add("ru", "article", "статья")_add("ru", "chapter", "глава")_add("ru", "title", "раздел")_add("uk", "article", "стаття")_add("bg", "article", "член", "чл")_add("mk", "article", "член")_add("sr", "article", "чла��")_add("hr", "article", "članak")_add("hr", "chapter", "poglavlje")_add("bs", "article", "članak")_add("sq", "article", "neni")_add("tr", "article", "madde")_add("az", "article", "maddə")_add("uz", "article", "модда")_add("mn", "article", "зүйл")_add("lo", "article", "ມາດຕາ")_add("id", "article", "pasal")_add("id", "chapter", "bab")_add("ms", "article", "seksyen")_add("ms", "part", "bahagian")_add("lt", "article", "straipsnis")_add("ta", "article", "பிரிவு")_add("el", "part", "μέρος")_add("el", "section", "παράγραφος")_add("uk", "title", "розділ")_add("zh", "chapter", "章")_add("ja", "chapter", "章")_add("ko", "chapter", "장")_add("vi", "article", "điều")_add("vi", "chapter", "chương")_add("ka", "article", "მუხლი")_add("hy", "article", "հոդված")_add("am", "article", "አንቀጽ")_add("km", "article", "មាត្រា")_add("my", "article", "ပုဒ်မ")_add("ne", "article", "दफा")_add("si", "article", "වගන්තිය")_add("kk", "article", "бап")_add("uz", "article", "modda")_add("be", "article", "артыкул")_add("ky", "article", "берене")_add("ur", "article", "دفعہ")_add("so", "article", "qodob", "qodobka")_add("ga", "article", "airteagal")_add("cy", "article", "erthygl")_add("fil", "article", "artikulo")_add("fil", "section", "seksyon")_add("fil", "chapter", "kabanata")_add("id", "part", "bagian")_add("vi", "part", "mục")_add("sw", "part", "sehemu")_add("ht", "article", "atik")_add("eu", "article", "artikulua")_add("da", "section", "stk")_add("nb", "section", "ledd")_add("de", "section", "absatz")_add("es", "section", "apartado")_add("it", "section", "comma")_add("tr", "section", "fıkra")_add("hr", "section", "stavak")_add("bg", "section", "ал")_add("te", "article", "ప్రకరణము", "ప్రకరణ")_add("kn", "article", "ಪ್ರಕರಣ")_add("gu", "article", "કલમ")_add("pa", "article", "ਧਾਰਾ")_add("ml", "article", "വകുപ്പ്")_add("th", "title", "ลักษณะ")_add("zh", "part", "编")_add("ja", "part", "編")_add("ko", "part", "편")_add("tg", "article", "модда")_add("sw", "article", "kifungu")_add("ca", "article", "article")_add("ca", "chapter", "capítol", "capitol")_add("ca", "title", "títol", "titol")_add("ca", "section", "secció", "seccio")_add("pl", "chapter", "rozdział")_add("pl", "title", "dział")_add("ro", "chapter", "capitolul")_add("ro", "title", "titlul")_add("it", "chapter", "capo")_add("cs", "chapter", "hlava")_add("sk", "chapter", "hlava")_add("es", "part", "libro")_add("sv", "chapter", "kap")_add("km", "chapter", "ជំពូក")_add("lo", "part", "ພາກ")_add("my", "chapter", "အခန်း")_add("ka", "chapter", "თავი")_add("hy", "chapter", "գլուխ")_add("am", "chapter", "ምዕራፍ")_add("sq", "chapter", "kreu")_add("hu", "chapter", "fejezet")_add("tr", "chapter", "bölüm")_add("az", "chapter", "fəsil")_add("lt", "chapter", "skyrius")_add("is", "chapter", "kafli")_add("ga", "chapter", "caibidil")_add("cy", "chapter", "pennod")_add("mt", "chapter", "kapitolu")_add("ht", "chapter", "chapit")_add("sw", "chapter", "sura")_add("nb", "chapter", "kapittel")_add("ha", "chapter", "sashe")_add("mg", "chapter", "andiany")_add("mi", "part", "wāhanga", "wahanga")_add("sm", "part", "vaega")_add("to", "article", "kupu")_add("fj", "chapter", "wase")_add("tpi", "part", "hap")_add("fo", "chapter", "kapittul")_add("bi", "article", "atikol")_add("rw", "article", "ingingo")_add("zu", "chapter", "isigaba")_add("xh", "chapter", "icandelo")_add("st", "part", "karolo")_add("tn", "chapter", "kgaolo")_add("sn", "part", "chikamu")_add("ny", "article", "ndime")_add("ku", "part", "beş")_add("ky", "chapter", "бөлүм")_add("tg", "chapter", "боби")_add("yo", "article", "abala")_add("yo", "chapter", "ori")_add("ig", "article", "nkeji")_add("lg", "part", "ekitundu")_add("om", "chapter", "kutaa")_add("ln", "part", "eténi", "eteni")_add("ti", "article", "ዓንቀጽ")_add("bm", "article", "sariya")_add("wo", "article", "tere")_add("ak", "article", "ahyɛde", "ahyede")_add("ee", "part", "akpa")_add("ff", "part", "faanda")_add("br", "article", "pennad")_add("kri", "section", "sekshon")_add("bo", "article", "དོན་ཚན")_add("ug", "article", "ماددا")_add("kw", "article", "erthygel")_add("tw", "article", "hyɛdeɛ", "hyedee")_add("tet", "article", "artigu")_add("haw", "article", "paukū", "pauku")_add("ty", "article", "irava")_add("ch", "part", "påtte", "patte")_add("es", "section", "numeral")_add("it", "section", "capoverso")_add("de", "section", "nummer")_add("so", "part", "qaybta")_add("vi", "part", "phần")_add("sk", "chapter", "oddiel")_add("el", "title", "τίτλος")_add("bg", "title", "дял")_add("uz", "chapter", "bob")_add("kk", "chapter", "тарау")_add("hi", "chapter", "अध्याय")_add("bn", "chapter", "অধ্যায়")_add("ur", "chapter", "باب")_add("fa", "chapter", "فصل")_add("ne", "chapter", "परिच्छेद")_add("zh", "section", "节")_add("ja", "section", "節")_add("ko", "section", "절")_add("th", "section", "ตอน")_add("sr", "part", "одељак")_add("be", "title", "раздзел")
# Shared abbreviation; language left unknown._add("und", "article", "art.", "član")_add("und", "section", "§")
# Scripts we do not Latin-split:NO_LATIN_SPLIT_LANGS = frozenset( { "ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn", "am", "ru", "uk", "be", "ka", "hy", "km", "lo", "my", "si", })
_TOKEN_RE = re.compile(r"[^\W\d_]+|art\.|sec\.|чл\.|§", re.UNICODE)
def classify_heading_token(token: str) -> list[tuple[str, str]]: return list(HEADING_LEXICON.get(token.casefold()) or ())
def score_heading_languages(text: str) -> Counter[str]: """Count distinctive lexicon hits. Shared words like 'article' do not vote.""" counts: Counter[str] = Counter() if not text: return counts for token in _TOKEN_RE.findall(text): hits = classify_heading_token(token) langs = {lang for _kind, lang in hits if lang != "und"} if len(langs) == 1: counts[next(iter(langs))] += 1 return counts
def majority_language(counts: Counter[str], *, exclude: tuple[str, ...] = ("und",)) -> str | None: filtered = Counter({k: v for k, v in counts.items() if k not in exclude}) if not filtered: return None lang, _n = filtered.most_common(1)[0] return lang
def iso_lang(value: Any) -> str: text = str(value or "").strip().lower().replace("_", "-") if not text: return "" return text.split("-")[0]
def latin_split_allowed(language: str) -> bool: return iso_lang(language) not in NO_LATIN_SPLIT_LANGS123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221#!/usr/bin/env python3"""Thin-client query for country-laws IR releases (local dir)."""
from __future__ import annotations
import argparseimport jsonfrom collections import defaultdictfrom pathlib import Path
import numpy as npimport pandas as pd
K1 = 1.2B = 0.75TITLE_WEIGHT = 5.0BODY_WEIGHT = 1.0MAX_QUERY_TERMS = 64
def tokenize(text: str) -> list[str]: import re import unicodedata
if not text: return [] nfkd = unicodedata.normalize("NFKD", text) folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower() return re.findall(r"[0-9A-Za-z]+", folded)
class Release: def __init__(self, root: Path): self.root = Path(root) self.manifest = json.loads((self.root / "manifest.json").read_text(encoding="utf-8"))
def _read(self, rel: str) -> pd.DataFrame: path = self.root / rel if path.is_dir(): files = sorted(path.glob("*.parquet")) return pd.concat([pd.read_parquet(f) for f in files], ignore_index=True) if files else pd.DataFrame() return pd.read_parquet(path)
def bm25(self, query: str, top_k: int = 10) -> list[dict]: try: from .duckdb_store import bm25_search
return bm25_search(self.root, query, top_k=top_k) except Exception: pass q_terms = tokenize(query)[:MAX_QUERY_TERMS] if not q_terms: return [] shards = pd.read_parquet(self.root / "indexes" / "bm25_keyword_shards.parquet") needed = set() for term in q_terms: hit = shards[(shards["first_key"] <= term) & (shards["last_key"] >= term)] if hit.empty: hit = shards for rel in hit["relative_path"].tolist(): needed.add(rel) postings = pd.concat( [pd.read_parquet(self.root / rel) for rel in sorted(needed)], ignore_index=True, ) postings = postings[postings["term"].isin(q_terms)] docs = self._read("data/bm25/documents") avgdl = float(self.manifest["bm25"]["average_document_length"]) or 1.0 scores: dict[int, float] = defaultdict(float) for rec in postings.itertuples(index=False): idf = float(rec.idf) for di, ttf, btf, dl in zip( rec.document_indices, rec.title_frequencies, rec.body_frequencies, rec.document_lengths ): tf = TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf) denom = tf + K1 * (1.0 - B + B * (int(dl) / avgdl)) if denom: scores[int(di)] += idf * (tf * (K1 + 1.0)) / denom ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:top_k] by_idx = docs.set_index("document_index") out = [] for di, score in ranked: row = by_idx.loc[di] out.append( { "document_index": int(di), "entry_cid": row["entry_cid"], "title": row["title"], "record_type": row["record_type"], "instrument_id": row.get("instrument_id", row.get("law_id", "")), "law_cid": row.get("law_cid", ""), "score": float(score), } ) return out
def vector(self, query: str, top_k: int = 10, candidate_centroids: int = 4, device: str = "cpu") -> list[dict]: status = (self.manifest.get("vector") or {}).get("status") if status == "stub": return [{"error": "vectors are stubbed", "reason": self.manifest["vector"].get("stub_reason")}] from sentence_transformers import SentenceTransformer
model = SentenceTransformer(self.manifest["vector"]["model_name"], device=device) q = model.encode([query], normalize_embeddings=True, convert_to_numpy=True)[0].astype(np.float32) meta = pd.read_parquet(self.root / "indexes" / "vector_chunks.parquet") cents = np.stack(meta["centroid"].map(lambda c: np.asarray(c, dtype=np.float32)).to_numpy()) sims = cents @ q order = np.argsort(-sims)[: max(1, candidate_centroids)] shards = meta.iloc[order] frames = [pd.read_parquet(self.root / rel) for rel in shards["relative_path"].tolist()] vecs = pd.concat(frames, ignore_index=True) if "embedding" not in vecs.columns or vecs["embedding"].isna().all(): return [{"error": "vector shard missing embeddings"}] emb = np.stack(vecs["embedding"].map(lambda e: np.asarray(e, dtype=np.float32)).to_numpy()) scores = emb @ q top = np.argsort(-scores)[:top_k] out = [] for i in top: row = vecs.iloc[int(i)] out.append( { "document_index": int(row["document_index"]), "entry_cid": row["entry_cid"], "title": row["title"], "record_type": row["record_type"], "instrument_id": row.get("instrument_id", row.get("law_id", "")), "score": float(scores[int(i)]), } ) return out
def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]: try: from .duckdb_store import graph_neighbors
return graph_neighbors(self.root, node_cid, direction=direction, limit=limit) except Exception: pass dirs = ["incoming", "outgoing"] if direction == "both" else [direction] hits = [] for d in dirs: path = self.root / "data" / "graph" / "adjacency" / d files = sorted(path.glob("*.parquet")) for f in files: df = pd.read_parquet(f) sub = df[df["node_cid"] == node_cid] for rec in sub.itertuples(index=False): for i, neigh in enumerate(rec.neighbor_cids): hits.append( { "direction": d, "node_cid": node_cid, "neighbor_cid": neigh, "edge_type": rec.edge_types[i] if i < len(rec.edge_types) else "", "score": rec.scores[i] if rec.scores is not None and i < len(rec.scores) else None, } ) hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"])) return hits[:limit]
def cite(self, citation: str, cite_format: str = "any", limit: int = 25) -> list[dict]: from .duckdb_store import cite_search
return cite_search(self.root, citation, cite_format=cite_format, limit=limit)
def _print(rows: list[dict]) -> None: print(json.dumps(rows, indent=2, ensure_ascii=False))
def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description="Query a country-laws IR release") ap.add_argument("--local-dir", required=True, help="Path to local release root") sub = ap.add_subparsers(dest="cmd", required=True)
p_bm = sub.add_parser("bm25") p_bm.add_argument("query") p_bm.add_argument("--top-k", type=int, default=10)
p_vec = sub.add_parser("vector") p_vec.add_argument("query") p_vec.add_argument("--top-k", type=int, default=10) p_vec.add_argument("--candidate-centroids", type=int, default=4) p_vec.add_argument("--device", default="cuda")
p_g = sub.add_parser("graph") g_sub = p_g.add_subparsers(dest="graph_cmd", required=True) p_n = g_sub.add_parser("neighbors") p_n.add_argument("node_cid") p_n.add_argument( "--direction", default="both", choices=["both", "in", "out", "incoming", "outgoing"], ) p_n.add_argument("--limit", type=int, default=25)
p_cite = sub.add_parser("cite") p_cite.add_argument("citation") p_cite.add_argument( "--format", dest="cite_format", default="any", choices=["any", "bluebook", "official"], ) p_cite.add_argument("--limit", type=int, default=25)
args = ap.parse_args(argv) rel = Release(Path(args.local_dir)) if args.cmd == "bm25": _print(rel.bm25(args.query, top_k=args.top_k)) elif args.cmd == "vector": _print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device)) elif args.cmd == "graph" and args.graph_cmd == "neighbors": _print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit)) elif args.cmd == "cite": _print(rel.cite(args.citation, cite_format=args.cite_format, limit=args.limit)) return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324"""Incrementally package raw collector instruments into laws/articles parquet.
Collectors write one JSON instrument per official page under``$LEGAL_CORPORA_ROOT/<iso>/instruments/*.json``. Those files grow as newpages are scraped. This module merges them into the ``endomorphosis/ipfs_*_laws``parquet schema without rewriting unchanged rows, so the GraphRAG builder candelta-rebuild from the resulting pack.
Never invents legal text or identifiers. Empty/short bodies are dropped, notfilled."""
from __future__ import annotations
import jsonimport osfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import pandas as pd
from .cidutil import sha256_filefrom .schema import LAW_FIELD_MAP, REQUIRED_ARTICLE_COLUMNS, REQUIRED_LAW_COLUMNS
LAW_COLS = [ "id", "title", "text", "source_url", "source_type", "jurisdiction", "country", "language", "eli", "date", "date_issued", "retrieved_at", "license", "law_status", "identifier", "official_identifier", "article_count", "json_path", "metadata_json",]ART_COLS = [ "law_id", "id", "title", "text", "source_url", "document_number", "article_number", "record_type", "metadata_json",]
MIN_BODY_CHARS = 80DEFAULT_CORPORA_ROOT = Path( os.environ.get( "LEGAL_CORPORA_ROOT", str(Path.home() / ".ipfs_datasets" / "legal-corpora"), ))
def _s(value: Any) -> str: if value is None: return "" return str(value).strip()
def _meta_json(value: Any) -> str: if isinstance(value, str): return value try: return json.dumps(value or {}, ensure_ascii=False) except Exception: return "{}"
def instruments_to_frames( instruments_dir: Path, *, min_body_chars: int = MIN_BODY_CHARS,) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]: """Read collector JSON instruments into laws/articles dataframes.""" laws: list[dict[str, Any]] = [] arts: list[dict[str, Any]] = [] skipped_short = 0 skipped_bad = 0 root = Path(instruments_dir) files = sorted(root.glob("*.json")) if root.is_dir() else [] for path in files: try: rec = json.loads(path.read_text(encoding="utf-8")) except Exception: skipped_bad += 1 continue if not isinstance(rec, dict): skipped_bad += 1 continue text = _s(rec.get("text")) ident = _s(rec.get("id")) title = _s(rec.get("title")) if not ident or not title or len(text) < min_body_chars: skipped_short += 1 continue meta = rec.get("metadata") or {} laws.append( { "id": ident, "title": title, "text": text, "source_url": _s(rec.get("source_url")), "source_type": _s(rec.get("source_type")), "jurisdiction": _s(rec.get("jurisdiction")), "country": _s(rec.get("country")), "language": _s(rec.get("language")), "eli": _s(rec.get("eli")) or None, "date": _s(rec.get("date")) or None, "date_issued": _s(rec.get("date_issued") or rec.get("date")) or None, "retrieved_at": _s(rec.get("retrieved_at")) or None, "license": _s(rec.get("license")), "law_status": _s(rec.get("law_status")), "identifier": _s(rec.get("identifier")) or ident, "official_identifier": _s(rec.get("official_identifier")), "article_count": rec.get("article_count") or len(rec.get("documents") or []), "json_path": f"instruments/{path.name}", "metadata_json": _meta_json(meta), } ) for doc in rec.get("documents") or []: if not isinstance(doc, dict): continue art_id = _s(doc.get("id")) art_title = _s(doc.get("title")) art_text = _s(doc.get("text")) if not art_id or not art_title or not art_text: continue arts.append( { "law_id": ident, "id": art_id, "title": art_title, "text": art_text, "source_url": _s(doc.get("source_url")) or _s(rec.get("source_url")), "document_number": _s(doc.get("document_number")), "article_number": _s(doc.get("article_number")), "record_type": _s(doc.get("record_type")) or "article", "metadata_json": _meta_json(doc.get("metadata") or {}), } ) report = { "n_instrument_files": len(files), "n_laws": len(laws), "n_articles": len(arts), "skipped_short_or_empty": skipped_short, "skipped_unreadable": skipped_bad, "min_body_chars": min_body_chars, "never_invented_legal_text": True, "required_law_columns": list(REQUIRED_LAW_COLUMNS), "required_article_columns": list(REQUIRED_ARTICLE_COLUMNS), "law_field_map": dict(LAW_FIELD_MAP), } return ( pd.DataFrame(laws, columns=LAW_COLS), pd.DataFrame(arts, columns=ART_COLS), report, )
def _retrieved_key(value: Any) -> str: return _s(value)
def merge_laws(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame: """Upsert laws by ``id``. Newer ``retrieved_at`` wins; otherwise incoming wins.""" if prior is None or prior.empty: return incoming.copy() if incoming is not None else pd.DataFrame(columns=LAW_COLS) if incoming is None or incoming.empty: return prior.copy() by_id: dict[str, dict[str, Any]] = {} for frame, incoming_flag in ((prior, False), (incoming, True)): for rec in frame.to_dict(orient="records"): ident = _s(rec.get("id")) if not ident: continue existing = by_id.get(ident) if existing is None: by_id[ident] = rec continue if incoming_flag: new_ts = _retrieved_key(rec.get("retrieved_at")) old_ts = _retrieved_key(existing.get("retrieved_at")) if not old_ts or new_ts >= old_ts: by_id[ident] = rec rows = [by_id[k] for k in sorted(by_id)] return pd.DataFrame(rows, columns=LAW_COLS)
def merge_articles(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame: """Upsert articles by ``id``. Incoming replaces the same article id.""" if prior is None or prior.empty: return incoming.copy() if incoming is not None else pd.DataFrame(columns=ART_COLS) if incoming is None or incoming.empty: return prior.copy() by_id: dict[str, dict[str, Any]] = {} for frame in (prior, incoming): for rec in frame.to_dict(orient="records"): ident = _s(rec.get("id")) if not ident: continue by_id[ident] = rec rows = [by_id[k] for k in sorted(by_id)] return pd.DataFrame(rows, columns=ART_COLS)
def load_existing_parquet(pack_dir: Path) -> tuple[pd.DataFrame | None, pd.DataFrame | None]: pack_dir = Path(pack_dir) laws_path = None arts_path = None for cand in (pack_dir / "data" / "laws.parquet", pack_dir / "laws.parquet"): if cand.is_file(): laws_path = cand break for cand in (pack_dir / "data" / "articles.parquet", pack_dir / "articles.parquet"): if cand.is_file(): arts_path = cand break laws = pd.read_parquet(laws_path) if laws_path else None arts = pd.read_parquet(arts_path) if arts_path else None return laws, arts
def write_pack( out: Path, laws: pd.DataFrame, articles: pd.DataFrame, *, slug: str, source_dataset: str, name: str | None = None, extra_meta: dict[str, Any] | None = None,) -> dict[str, Any]: """Write a local pack that ``load_source`` / ``get_country`` can consume.""" out = Path(out) data_dir = out / "data" data_dir.mkdir(parents=True, exist_ok=True) laws_path = data_dir / "laws.parquet" arts_path = data_dir / "articles.parquet" laws.to_parquet(laws_path, index=False) articles.to_parquet(arts_path, index=False) now = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z") meta = { "slug": slug, "repo": source_dataset, "source_dataset": source_dataset, "name": name or slug.replace("_", " ").title(), "indexable": True, "source_revision": f"local:{now}", "n_laws": int(len(laws)), "n_articles": int(len(articles)), "laws_sha256": sha256_file(laws_path), "articles_sha256": sha256_file(arts_path), "generated_at": now, "incremental": True, } if extra_meta: meta.update(extra_meta) (out / "pack_meta.json").write_text( json.dumps(meta, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) return meta
def package_instruments( *, instruments_dir: Path, out: Path, slug: str, source_dataset: str | None = None, prior_pack: Path | None = None, name: str | None = None, min_body_chars: int = MIN_BODY_CHARS,) -> dict[str, Any]: """Merge collector JSON (+ optional prior parquet) into a local IR source pack.""" incoming_laws, incoming_arts, extract_report = instruments_to_frames( instruments_dir, min_body_chars=min_body_chars ) prior_laws = prior_arts = None prior_dir = Path(prior_pack) if prior_pack else (out if out.exists() else None) if prior_dir is not None: prior_laws, prior_arts = load_existing_parquet(prior_dir) laws = merge_laws(prior_laws, incoming_laws) articles = merge_articles(prior_arts, incoming_arts) if laws.empty: raise RuntimeError( f"no laws with text>={min_body_chars} under {instruments_dir}" ) repo = source_dataset or f"endomorphosis/ipfs_{slug}_laws" meta = write_pack( out, laws, articles, slug=slug, source_dataset=repo, name=name, extra_meta={"extract": extract_report}, ) meta["extract"] = extract_report meta["n_laws_prior"] = int(len(prior_laws)) if prior_laws is not None else 0 meta["n_articles_prior"] = int(len(prior_arts)) if prior_arts is not None else 0 meta["n_laws_incoming"] = int(len(incoming_laws)) meta["n_articles_incoming"] = int(len(incoming_arts)) meta["out"] = str(out) return meta
def default_instruments_dir(iso_or_slug: str, root: Path | None = None) -> Path: base = Path(root) if root is not None else DEFAULT_CORPORA_ROOT return base / iso_or_slug / "instruments"123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232"""Reconstruct empty parent law bodies from article children.
Never invents legal text. Glue uses the same normalized strings as childcorpus fields. Eligible empty parents always get a law row (full glue,streamed prefix, or title/number stub) — they are not dropped."""
from __future__ import annotations
from dataclasses import dataclass, fieldimport osimport reimport unicodedatafrom typing import Any, Iterable
from .structure import normalize_legal_text
RECONSTRUCT_MAX_PARENT_CHARS = 2_000_000RECONSTRUCT_STUB_MAX_CHARS = 8_192RECONSTRUCT_PROCESS_BUDGET_BYTES = 512 * 1024 * 1024RSS_ABORT_SKIP_FULL_CONCAT = frozenset({"france", "eu", "denmark"})PARENT_TRUNCATED_MAX_CHARS = 40
_DIGIT_FOLD = str.maketrans( { "٠": "0", "١": "1", "٢": "2", "٣": "3", "٤": "4", "٥": "5", "٦": "6", "٧": "7", "٨": "8", "٩": "9", "۰": "0", "۱": "1", "۲": "2", "۳": "3", "۴": "4", "۵": "5", "۶": "6", "۷": "7", "۸": "8", "۹": "9", "〇": "0", "零": "0", })_NUM_RUN = re.compile(r"\d+|\D+")
def fold_digits(value: str) -> str: return unicodedata.normalize("NFKC", value or "").translate(_DIGIT_FOLD)
def article_sort_key(article_number: str, source_id: str) -> tuple: folded = fold_digits(article_number or "") nums: list[int] = [] rest: list[str] = [] for run in _NUM_RUN.findall(folded) if folded else []: if run.isdigit(): nums.append(int(run)) else: rest.append(run) if not folded: return (0, (), "", source_id or "") if nums: return (1, tuple(nums), "".join(rest), source_id or "") return (2, (), folded, source_id or "")
def glue_piece(title: str, article_number: str, body: str) -> str: """One child's contribution to a reconstructed parent (normalized strings).""" title = title or "" article_number = article_number or "" body = body or "" chunk = title if title else article_number if chunk and not body.lstrip().startswith(chunk): return f"{chunk}\n{body}" if body else chunk return body
def glue_parent(pieces: Iterable[str]) -> str: return "\n\n".join(p for p in pieces if p)
@dataclassclass ReconstructResult: body: str reconstructed_from_articles: bool reconstruction_truncated: bool reconstruction_gap_note: str reconstruction_article_count: int reconstruction_article_ids: list[str] = field(default_factory=list) reconstruction_article_sha256: list[str] = field(default_factory=list) extra_bytes: int = 0 is_stub: bool = False
def extra_fields(self) -> dict[str, Any]: return { "reconstructed_from_articles": self.reconstructed_from_articles, "reconstruction_truncated": self.reconstruction_truncated, "reconstruction_gap_note": self.reconstruction_gap_note, "reconstruction_article_count": self.reconstruction_article_count, "reconstruction_article_ids": list(self.reconstruction_article_ids), "reconstruction_article_sha256": list(self.reconstruction_article_sha256), }
def parent_needs_reconstruct(parent_body: str, n_articles: int) -> bool: if n_articles < 1: return False body = parent_body or "" return (not body) or len(body) < PARENT_TRUNCATED_MAX_CHARS
def reconstruct_on() -> bool: return os.environ.get("COUNTRY_LAWS_RECONSTRUCT", "1").strip() not in {"0", "false", "off"}
def force_full_concat() -> bool: return os.environ.get("COUNTRY_LAWS_RECONSTRUCT_FULL", "").strip() in {"1", "true", "on"}
def process_budget_bytes() -> int: raw = os.environ.get("RECONSTRUCT_PROCESS_BUDGET_BYTES") if raw and raw.isdigit(): return int(raw) return RECONSTRUCT_PROCESS_BUDGET_BYTES
def reconstruct_parent( *, slug: str, parent_body: str, parent_title: str, children: list[dict[str, str]], running_extra_bytes: int, sha256_hex,) -> ReconstructResult: """Apply the five-way outcome table. ``children`` already normalized.""" # Empty bodies are dropped from the corpus. A title-only piece would make # the parent disagree with the glue of the children that remain. kept = [c for c in children if str(c.get("body") or "").strip()] ordered = sorted( kept, key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""), ) ids = [c.get("id") or "" for c in ordered] shas = [sha256_hex((c.get("body") or "").encode("utf-8")) for c in ordered] n = len(ordered) if n < 1 or not parent_needs_reconstruct(parent_body, n): return ReconstructResult( body=parent_body, reconstructed_from_articles=False, reconstruction_truncated=False, reconstruction_gap_note="", reconstruction_article_count=0, )
stub_note = "" if slug in RSS_ABORT_SKIP_FULL_CONCAT and not force_full_concat(): stub_note = "rss_abort_slug" elif running_extra_bytes >= process_budget_bytes(): stub_note = "reconstruct_budget"
if stub_note: parts: list[str] = [] if parent_title: parts.append(parent_title) for child in ordered: label = child.get("title") or child.get("article_number") or "" if label: parts.append(label) stub = "\n".join(parts)[:RECONSTRUCT_STUB_MAX_CHARS] return ReconstructResult( body=stub, reconstructed_from_articles=True, reconstruction_truncated=False, reconstruction_gap_note=stub_note, reconstruction_article_count=n, reconstruction_article_ids=ids, reconstruction_article_sha256=shas, extra_bytes=0, is_stub=True, )
acc: list[str] = [] size = 0 truncated = False for child in ordered: piece = glue_piece( child.get("title") or "", child.get("article_number") or "", child.get("body") or "", ) if not piece: continue extra = (2 if acc else 0) + len(piece) if size + extra > RECONSTRUCT_MAX_PARENT_CHARS: room = RECONSTRUCT_MAX_PARENT_CHARS - size - (2 if acc else 0) if room > 0: acc.append(piece[:room]) size = RECONSTRUCT_MAX_PARENT_CHARS truncated = True break acc.append(piece) size += extra body = glue_parent(acc) return ReconstructResult( body=body, reconstructed_from_articles=True, reconstruction_truncated=truncated, reconstruction_gap_note="", reconstruction_article_count=n, reconstruction_article_ids=ids, reconstruction_article_sha256=shas, extra_bytes=len(body.encode("utf-8")), is_stub=False, )
def expected_glue_from_children(children: list[dict[str, str]]) -> str: ordered = sorted( children, key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""), ) return glue_parent( glue_piece(c.get("title") or "", c.get("article_number") or "", c.get("body") or "") for c in ordered )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""Admit country-IR workers from live memory, disk, and GPU headroom.
The caller keeps at most ``Admission.workers`` builds in flight. Zero workersmeans pause and sleep ``backoff_seconds`` instead of starting another country."""
from __future__ import annotations
import shutilimport subprocessfrom dataclasses import dataclassfrom pathlib import Path
@dataclass(frozen=True)class GpuSnapshot: index: int memory_free_mib: int memory_total_mib: int
@dataclass(frozen=True)class HostSnapshot: """One host reading for admission.
``mem_available_gib`` is raw Linux MemAvailable. ``schedulable_gib`` adds ZFS ARC above arc_c_min. A negative schedulable value means the caller did not measure the ARC, and admission then uses the raw figure. The under-6 GiB pause keeps using the raw figure. """
mem_available_gib: float disk_free_gib: float gpus: tuple[GpuSnapshot, ...] schedulable_gib: float = -1.0
@dataclass(frozen=True)class Admission: workers: int devices: tuple[str, ...] backoff_s: float reason: str
def job_slots(corpus_rows: int) -> int: """How many admission slots one country consumes.
Unknown size costs one slot. A corpus of at least 150_000 rows costs two. A million-row corpus costs four, so it can share a wide pool instead of waiting until every other country has finished. """
rows = int(corpus_rows or 0) if rows >= 1_000_000: return 4 if rows >= 150_000: return 2 return 1
def can_admit(used_slots: int, limit: int, cost: int) -> bool: if limit <= 0 or cost <= 0: return False return used_slots + cost <= limit
def backoff_seconds(base: float, pressure: int) -> float: """Double the pause on each refused admission, and cap it at two minutes."""
if base <= 0: return 0.0 steps = min(max(int(pressure), 0), 4) return min(120.0, float(base) * (2**steps))
def assign_device(devices: tuple[str, ...], inflight: tuple[str, ...]) -> str: if not devices: return "cpu" counts = {device: inflight.count(device) for device in devices} return min(devices, key=lambda device: (counts[device], devices.index(device)))
def admission_budget_gib(snap: HostSnapshot) -> float: """RAM the slot formula may use.
Probe sets ``schedulable_gib`` to MemAvailable plus evictable ZFS ARC. Callers that only fill ``mem_available_gib`` leave the ARC unmeasured. """
if snap.schedulable_gib >= 0: return snap.schedulable_gib return snap.mem_available_gib
def admit_parallelism( snap: HostSnapshot, *, ceiling: int, per_worker_gib: float = 6.0, reserve_gib: float = 8.0, gpu_free_mib: int = 3072, disk_pause_gib: float = 20.0, disk_slow_gib: float = 40.0,) -> Admission: """Return how many country builds may start, and which devices they may use.
The slot count uses schedulable RAM, so evictable ZFS ARC counts as room. The pause under 6 GiB uses raw MemAvailable. ARC shrink is not instant, and MemAbort keeps that same raw floor. """
ceiling = max(0, int(ceiling)) budget = admission_budget_gib(snap) if snap.disk_free_gib >= 0 and snap.disk_free_gib < disk_pause_gib: return Admission(0, (), 15.0, "disk") if snap.mem_available_gib >= 0 and snap.mem_available_gib < 6.0: return Admission(0, (), 15.0, "memory")
if budget < 0: ram_slots = 1 else: ram_slots = int((budget - reserve_gib) // per_worker_gib) if budget < 12.0: ram_slots = min(ram_slots, 1) ram_slots = max(0, ram_slots)
usable = tuple( f"cuda:{gpu.index}" for gpu in snap.gpus if gpu.memory_free_mib >= gpu_free_mib ) if snap.gpus and not usable: return Admission(0, (), 10.0, "gpu") if not snap.gpus: devices: tuple[str, ...] = ("cpu",) device_slots = 4 else: devices = usable # Encode stays one-at-a-time per GPU. The extra slots overlap # download, normalize, and search-graph builds while RAM is free. device_slots = len(usable) * 4
if snap.disk_free_gib >= 0 and snap.disk_free_gib < disk_slow_gib: device_slots = min(device_slots, 1) ram_slots = min(ram_slots, 1)
workers = min(ceiling, ram_slots, device_slots) if workers <= 0: return Admission(0, (), 15.0, "budget") return Admission(workers, devices, 0.0, "ok")
def probe_host(anchor: Path | None = None) -> HostSnapshot: """Read RAM, free space on ``anchor``, and ``nvidia-smi`` memory.
The snapshot keeps raw MemAvailable and a schedulable budget. The budget adds ZFS ARC above arc_c_min. MemAbort does not read that budget. """
from .mem import mem_available_gib, schedulable_gib
root = anchor or Path.home() try: disk = shutil.disk_usage(root).free / (1024**3) except OSError: disk = -1.0 available = mem_available_gib() return HostSnapshot( mem_available_gib=available, disk_free_gib=disk, gpus=tuple(_gpu_snapshots()), schedulable_gib=schedulable_gib(available), )
def _gpu_snapshots() -> list[GpuSnapshot]: try: raw = subprocess.check_output( [ "nvidia-smi", "--query-gpu=index,memory.free,memory.total", "--format=csv,noheader,nounits", ], text=True, timeout=5, stderr=subprocess.DEVNULL, ) except (OSError, subprocess.SubprocessError, ValueError): return [] found: list[GpuSnapshot] = [] for line in raw.splitlines(): parts = [part.strip() for part in line.split(",")] if len(parts) != 3: continue try: found.append(GpuSnapshot(int(parts[0]), int(parts[1]), int(parts[2]))) except ValueError: continue return found123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128"""Fail-closed schema mapping for endomorphosis/ipfs_*_laws parquet tables.
Verified 2026-09-03 against Malta (pilot) and Germany (column-drift check):
Laws columns (both countries): id, title, text, source_url, source_type, jurisdiction, country, language, eli, date, date_issued, retrieved_at, license, law_status, identifier, official_identifier, article_count, json_path, metadata_json
Drift: Malta article_count is int64; Germany article_count is int32. Germany eli is frequently null. Neither is a missing identifier.
Articles columns (both countries; Malta snapshot has 0 rows): law_id, id, title, text, source_url, document_number, article_number, record_type, metadata_json
Required identity columns are NOT invented. Missing required identifiersfail the build."""
from __future__ import annotations
REQUIRED_LAW_COLUMNS = ("id", "title", "text")REQUIRED_ARTICLE_COLUMNS = ("id", "law_id", "title", "text")
OPTIONAL_LAW_COLUMNS = ( "source_url", "source_type", "jurisdiction", "country", "language", "eli", "date", "date_issued", "retrieved_at", "license", "law_status", "identifier", "official_identifier", "article_count", "json_path", "metadata_json",)
OPTIONAL_ARTICLE_COLUMNS = ( "source_url", "document_number", "article_number", "record_type", "metadata_json",)
# Canonical field mapping used in the CID-keyed corpus.LAW_FIELD_MAP = { "source_id": "id", "title": "title", "body": "text", "source_url": "source_url", "source_type": "source_type", "jurisdiction": "jurisdiction", "country": "country", "language": "language", "eli": "eli", "date": "date", "date_issued": "date_issued", "retrieved_at": "retrieved_at", "license_expression": "license", "law_status": "law_status", "identifier": "identifier", "official_identifier": "official_identifier", "article_count": "article_count", "metadata_json": "metadata_json",}
ARTICLE_FIELD_MAP = { "source_id": "id", "law_id": "law_id", "title": "title", "body": "text", "source_url": "source_url", "document_number": "document_number", "article_number": "article_number", "record_type_src": "record_type", "metadata_json": "metadata_json",}
class SchemaError(ValueError): pass
def _cols(df) -> set[str]: return set(map(str, df.columns))
def validate_laws(df) -> None: missing = [c for c in REQUIRED_LAW_COLUMNS if c not in _cols(df)] if missing: raise SchemaError( f"laws.parquet missing required identifier/content columns {missing}; " f"present={sorted(_cols(df))}. Fail closed — will not invent ids." ) null_ids = int(df["id"].isna().sum()) if "id" in df.columns else len(df) empty_ids = int((df["id"].astype(str).str.strip() == "").sum()) if "id" in df.columns else 0 if null_ids or empty_ids: raise SchemaError( f"laws.parquet has {null_ids} null and {empty_ids} empty id values. Fail closed." )
def validate_articles(df) -> None: if df is None or df.empty: return missing = [c for c in REQUIRED_ARTICLE_COLUMNS if c not in _cols(df)] if missing: raise SchemaError( f"articles.parquet missing required identifier/content columns {missing}; " f"present={sorted(_cols(df))}. Fail closed — will not invent ids." ) null_ids = int(df["id"].isna().sum()) null_law = int(df["law_id"].isna().sum()) empty_ids = int((df["id"].astype(str).str.strip() == "").sum()) empty_law = int((df["law_id"].astype(str).str.strip() == "").sum()) if null_ids or empty_ids or null_law or empty_law: raise SchemaError( f"articles.parquet has null/empty identifiers " f"(id null={null_ids} empty={empty_ids}; law_id null={null_law} empty={empty_law}). Fail closed." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144"""Country-law sparse GraphRAG export through the shared HF GraphRAG builders.
This is the same parquet layout used by US Code, state laws, Federal Register,and SkillCenter:
* ``ipfs_datasets_py.retrieval.hf_graphrag.bm25.build_bm25_layout``* ``ipfs_datasets_py.retrieval.hf_graphrag.graph.write_graph_layout``
No SQLite. Indexes are ZSTD parquet shards under ``data/bm25`` and``data/graph``. DuckDB queries those shards at read time."""
from __future__ import annotations
from pathlib import Pathfrom typing import Any
import pandas as pd
from . import EDGE_IDENTITY_SCHEMA, SCHEMA_VERSIONfrom .cidutil import cid_of_jsonfrom .graph import build_graph
def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]: """Project a normalized country-law corpus onto the shared BM25 row schema.
Rows with no searchable tokens are omitted. The shared ``build_bm25_layout`` builder fail-closes on empty documents (same admission rule as US Code / Federal Register). """ from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text
_MAX_TITLE = 4_096 _MAX_BODY = 200_000 _CTRL = dict.fromkeys(range(32)) rows: list[dict[str, Any]] = [] for rec in corpus.itertuples(index=False): cid = str(getattr(rec, "entry_cid", "") or "") record_type = str(getattr(rec, "record_type", "") or "law") title = str(getattr(rec, "title", "") or "").replace("\x00", "") body = str(getattr(rec, "body", "") or "").replace("\x00", "") title = title.translate(_CTRL).strip() body = body.strip() if len(title) > _MAX_TITLE: title = title[:_MAX_TITLE].rstrip() if len(body) > _MAX_BODY: body = body[:_MAX_BODY].rstrip() if not title: title = f"{record_type} {cid}"[:_MAX_TITLE].strip() if not title and not body: continue if not tokenize_bm25_text(title) and not tokenize_bm25_text(body): continue rows.append( { "entry_cid": cid, "title": title, "body": body, "record_type": record_type, "document_index": int(rec.document_index), } ) if not rows: raise RuntimeError("no corpus rows had searchable BM25 tokens") for i, row in enumerate(rows): row["document_index"] = i return rows
def _graph_nodes_and_edges(corpus: pd.DataFrame) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: """Structural graph only (no precomputed BM25 neighbor matrix).""" built = build_graph(corpus, [[] for _ in range(len(corpus))]) nodes = [ { "node_cid": str(row["node_cid"]), "node_type": str(row["node_type"]), "label": row.get("label"), "entry_cid": row.get("entry_cid") or None, } for row in built["nodes"].to_dict("records") ] edges = [] for row in built["edges"].to_dict("records"): source = str(row.get("source_cid") or row.get("source_node_cid") or "") target = str(row.get("target_cid") or row.get("target_node_cid") or "") edge_type = str(row.get("edge_type") or "") if not source or not target or not edge_type: continue edge_cid = str(row.get("edge_cid") or "") or cid_of_json( { "edge_type": edge_type, "schema": EDGE_IDENTITY_SCHEMA, "source": source, "target": target, } ) edges.append( { "edge_cid": edge_cid, "edge_type": edge_type, "source_node_cid": source, "target_node_cid": target, "retrieval_method": str(row.get("retrieval_method") or "structural"), "score": row.get("score"), } ) return nodes, edges
def export_sparse_graphrag( corpus: pd.DataFrame, output_dir: Path,) -> dict[str, Any]: """Write BM25 + graph parquet shards using the shared HF GraphRAG builders.""" from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import ( BM25LayoutConfig, build_bm25_layout, ) from ipfs_datasets_py.retrieval.hf_graphrag.graph import write_graph_layout
output_dir = Path(output_dir) output_dir.mkdir(parents=True, exist_ok=True) rows = corpus_to_bm25_rows(corpus) bm25 = build_bm25_layout( rows, output_dir, config=BM25LayoutConfig(max_documents=max(len(rows), 1)), ) nodes, edges = _graph_nodes_and_edges(corpus) written = write_graph_layout(nodes, edges, output_dir) layout = written.layout return { "engine": "hf_graphrag", "schema_version": SCHEMA_VERSION, "bm25": bm25.to_manifest_fragment(), "graph": { "node_count": int(layout.node_count), "edge_count": int(layout.edge_count), "adjacency": "data/graph/adjacency/{out,in}/*.parquet", }, "sqlite": False, "query_engine": "duckdb", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532"""Disk-spill helpers for large country IR builds (DuckDB + parquet).
Design (CoS / DO OOM lesson):- Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).- Neighbors for n >= DUCKDB_THRESHOLD (40k): DuckDB FTS over corpus parquet, streamed into neighbor_*.parquet shards — never hold the full neighbor matrix in RAM.- BM25 TF: stream tokenize → DuckDB → posting parquet parts.- Package: sequential parquet write so corpus, bm25, graph, vectors are never all resident together.
No SQLite. Intermediate and published artifacts are parquet / DuckDB."""from __future__ import annotations
import gcimport jsonimport mathimport picklefrom collections import defaultdictfrom pathlib import Pathfrom typing import Any, Callable, Iterable, Iterator
import numpy as npimport pandas as pdimport pyarrow.parquet as pq
from . import SCHEMA_VERSIONfrom .bm25 import ( B, BODY_WEIGHT, K1, POSTING_ROWS_PER_RECORD, TERMS_PER_SHARD, TITLE_WEIGHT,)from .graph import _adjacency, _edge, build_graphfrom .mem import MemAbort, checkpoint, log_memfrom .tokenize import tokenize
DUCKDB_THRESHOLD = 40_000SQLITE_THRESHOLD = DUCKDB_THRESHOLD # backward-compatible alias; not SQLiteBATCH = 256NEIGHBOR_SHARD = 5_000NEIGHBOR_K = 8DF_CAP = 1500MAX_QTERMS = 8TITLE_W = TITLE_WEIGHTBODY_W = BODY_WEIGHT
def spill_dir_for(slug: str, cache: Path) -> Path: return Path(cache) / f"{slug}_bm25_spill"
def spill_pickle(path: Path, obj: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) tmp = path.with_suffix(path.suffix + ".tmp") with tmp.open("wb") as f: pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL) tmp.replace(path)
def load_pickle(path: Path) -> Any: with path.open("rb") as f: return pickle.load(f)
def _idf(n_docs: int, df: int) -> float: return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
def _require_duckdb(): try: import duckdb # type: ignore except ImportError as exc: raise RuntimeError("duckdb is required for sparse GraphRAG spill (no sqlite)") from exc return duckdb
def duckdb_ready(db_path: Path, expected: int) -> bool: if not db_path.is_file(): return False duckdb = _require_duckdb() try: conn = duckdb.connect(str(db_path), read_only=True) n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0]) conn.close() return n == expected except Exception: return False
def build_sqlite_fts(*args, **kwargs): # pragma: no cover - removed raise RuntimeError("SQLite FTS is removed; use DuckDB parquet neighbors")
def neighbors_via_duckdb( corpus_path: Path, spill: Path, n_docs: int, *, k: int = NEIGHBOR_K, resume: bool = True, log: Callable[[str], None] | None = None,) -> list[Path]: """DuckDB FTS over corpus parquet → neighbor_*.parquet shards. No SQLite.""" from .duckdb_store import build_fts_index, stream_neighbors_to_parquet
spill = Path(spill) spill.mkdir(parents=True, exist_ok=True) db_path = spill / "neighbors.duckdb" if not duckdb_ready(db_path, n_docs): if db_path.exists(): db_path.unlink() if log: log(f"building duckdb fts n={n_docs} -> {db_path}") build_fts_index(corpus_path, db_path, n_docs, log=log) else: if log: log(f"reusing duckdb fts n={n_docs} path={db_path}") return stream_neighbors_to_parquet( db_path, spill, n_docs, k=k, resume=resume, log=log )
def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]: """Yield (start_index, shard_list) from parquet neighbor shards.""" from .duckdb_store import iter_neighbor_parquet_shards
parquet = list(Path(spill).glob("neighbors_*.parquet")) if parquet: yield from iter_neighbor_parquet_shards(spill) return # Legacy pickle shards (pre-DuckDB). Do not create new ones. paths = sorted(Path(spill).glob("neighbors_*.pkl")) for sp in paths: parts = sp.stem.split("_") start_i = int(parts[1]) yield start_i, load_pickle(sp)
def assemble_neighbors_streaming(spill: Path, n_docs: int) -> list: """Assemble only when unavoidable; prefer build_graph_from_neighbor_shards.""" neighbors: list = [] for start_i, part in iter_neighbor_shards(spill): while len(neighbors) < start_i: neighbors.append([]) neighbors.extend(part) del part gc.collect() while len(neighbors) < n_docs: neighbors.append([]) if len(neighbors) > n_docs: neighbors = neighbors[:n_docs] return neighbors
def neighbors_via_sqlite(*args, **kwargs): """Removed. Sparse GraphRAG neighbors are DuckDB/parquet only.""" return neighbors_via_duckdb(*args, **kwargs)
def build_graph_from_neighbor_shards( corpus: pd.DataFrame, spill: Path, *, log: Callable[[str], None] | None = None,) -> dict[str, Any]: """Build graph without holding the full neighbor list.
Structural edges first (neighbors=[]), then stream BM25_NEIGHBOR_OF from shards and recompute adjacency once. """ n = len(corpus) # Structural + facets only graph = build_graph(corpus, [[] for _ in range(n)]) cid_by_idx = corpus["entry_cid"].tolist() extra_edges: list[dict[str, Any]] = [] seen = 0 for start_i, part in iter_neighbor_shards(spill): for offset, neigh in enumerate(part): i = start_i + offset if i >= n: break src = cid_by_idx[i] for item in neigh: if len(item) == 3: j, score, terms = item else: j, score = item[0], item[1] terms = [] tgt = cid_by_idx[int(j)] extra_edges.append( _edge( src, "BM25_NEIGHBOR_OF", tgt, "bm25-okapi", float(score), {"k": 8, "neighbor_index": int(j)}, matched_terms=list(terms), ) ) seen += len(part) del part if len(extra_edges) >= 50_000: # Flush into edges df incrementally add = pd.DataFrame(extra_edges) graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True) extra_edges.clear() del add gc.collect() checkpoint(f"graph_neighbor_edges@{seen}", row=seen, every_n=50_000, log=log) if extra_edges: add = pd.DataFrame(extra_edges) graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True) del add, extra_edges gc.collect()
edges_df = graph["edges"] if not edges_df.empty: edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True) edges_df = edges_df.sort_values( ["edge_type", "source_cid", "target_cid"] ).reset_index(drop=True) graph["edges"] = edges_df node_type = {r["node_cid"]: r["node_type"] for r in graph["nodes"].to_dict("records")} incoming, outgoing = _adjacency(edges_df, node_type) graph["incoming"] = incoming graph["outgoing"] = outgoing graph["stats"] = { "n_nodes": int(len(graph["nodes"])), "n_edges": int(len(edges_df)), "n_doc_nodes": int( graph["nodes"]["node_type"].isin(["law_entry", "article", "law"]).sum() ), "n_facet_nodes": int( graph["nodes"]["node_type"].astype(str).str.startswith("facet_").sum() ), "edge_types": sorted(edges_df["edge_type"].unique().tolist()) if not edges_df.empty else [], } if log: log( f"graph from shards nodes={graph['stats']['n_nodes']} " f"edges={graph['stats']['n_edges']}" ) return graph
def build_bm25_tf_spill( corpus_path: Path, spill: Path, n_docs: int, *, batch: int = 512, log: Callable[[str], None] | None = None,) -> dict[str, Any]: """Stream tokenize corpus → DuckDB TF → bm25_documents/postings parquet + stats.
Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.json exist with matching n_docs, reuse. """ spill.mkdir(parents=True, exist_ok=True) docs_path = spill / "bm25_documents.parquet" post_path = spill / "bm25_postings.parquet" stats_json = spill / "bm25_stats.json" stats_path = spill / "bm25_stats.pkl" if docs_path.is_file() and post_path.is_file(): stats = None if stats_json.is_file(): stats = json.loads(stats_json.read_text(encoding="utf-8")) elif stats_path.is_file(): stats = load_pickle(stats_path) if stats is not None and int(stats.get("n_docs", -1)) == n_docs: if log: log(f"reusing bm25 spill n_docs={n_docs}") return {"stats": stats, "documents": docs_path, "postings": post_path}
duckdb = _require_duckdb() bm25_db = spill / "bm25_tf.duckdb" if bm25_db.exists(): bm25_db.unlink() conn = duckdb.connect(str(bm25_db)) conn.execute( "CREATE TABLE tf (term VARCHAR NOT NULL, doc INTEGER NOT NULL, " "ttf INTEGER NOT NULL, btf INTEGER NOT NULL)" ) title_len = np.zeros(n_docs, dtype=np.int32) body_len = np.zeros(n_docs, dtype=np.int32) meta_path = spill / "doc_meta_rows.parquet" meta_path.unlink(missing_ok=True) meta_buf: list[dict] = [] pf = pq.ParquetFile(corpus_path) schema_names = set(pf.schema_arrow.names) cols = [ c for c in [ "document_index", "entry_cid", "law_cid", "instrument_id", "law_id", "source_id", "title", "instrument_title", "article_number", "article_title", "record_type", "language", "jurisdiction", "body", ] if c in schema_names ] processed = 0 batch_rows: list[tuple] = [] for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols): d = batch_tbl.to_pydict() m = len(d["document_index"]) for i in range(m): di = int(d["document_index"][i]) title = str((d.get("title") or [""])[i] or "") body = str((d.get("body") or [""])[i] or "") tt = tokenize(title) bt = tokenize(body) title_len[di] = len(tt) body_len[di] = len(bt) tf_t: dict[str, int] = defaultdict(int) tf_b: dict[str, int] = defaultdict(int) for tok in tt: tf_t[tok] += 1 for tok in bt: tf_b[tok] += 1 for tok in set(tf_t) | set(tf_b): batch_rows.append((tok, di, int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0)))) law_id = str((d.get("law_id") or d.get("instrument_id") or [""])[i] or "") instrument_id = str( (d.get("instrument_id") or d.get("law_id") or [""])[i] or "" ) meta_buf.append( { "entry_cid": str(d["entry_cid"][i]), "document_index": di, "law_cid": str((d.get("law_cid") or [""])[i] or ""), "instrument_id": instrument_id, "law_id": law_id, "source_id": str(d["source_id"][i]), "title": title, "instrument_title": str( (d.get("instrument_title") or [""])[i] or "" ), "article_number": str((d.get("article_number") or [""])[i] or ""), "article_title": str((d.get("article_title") or [""])[i] or ""), "record_type": str(d["record_type"][i]), "language": str((d.get("language") or [""])[i] or ""), "jurisdiction": str((d.get("jurisdiction") or [""])[i] or ""), } ) if len(batch_rows) >= 20_000: conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows) batch_rows.clear() processed += m if len(meta_buf) >= 20_000: dfm = pd.DataFrame(meta_buf) if meta_path.exists(): old = pd.read_parquet(meta_path) dfm = pd.concat([old, dfm], ignore_index=True) del old dfm.to_parquet(meta_path, index=False) del dfm meta_buf.clear() gc.collect() if processed % 20_000 == 0: checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log) gc.collect() if batch_rows: conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows) batch_rows.clear() if meta_buf: dfm = pd.DataFrame(meta_buf) if meta_path.exists(): old = pd.read_parquet(meta_path) dfm = pd.concat([old, dfm], ignore_index=True) del old dfm.to_parquet(meta_path, index=False) del dfm meta_buf.clear() if log: log("bm25 tf spilled to duckdb; writing documents")
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64) avgdl = float(doc_len.mean()) if n_docs else 0.0 meta_df = pd.read_parquet(meta_path).sort_values("document_index").reset_index(drop=True) assert len(meta_df) == n_docs meta_df["title_length"] = title_len[meta_df["document_index"].to_numpy()] meta_df["body_length"] = body_len[meta_df["document_index"].to_numpy()] meta_df["document_length"] = np.round( doc_len[meta_df["document_index"].to_numpy()] ).astype(int) meta_df["schema_version"] = SCHEMA_VERSION meta_df.to_parquet(docs_path, index=False) del meta_df gc.collect() meta_path.unlink(missing_ok=True)
posting_rows: list[dict] = [] n_postings = 0 n_terms = 0 part_i = 0 cur_term = None cur_items: list = []
def flush_term(term: str, items: list) -> None: nonlocal n_postings, n_terms, part_i, posting_rows if not items: return n_terms += 1 dfreq = len(items) cfreq = sum(int(ttf) + int(btf) for _, ttf, btf in items) idf = _idf(n_docs, dfreq) chunks = [ items[i : i + POSTING_ROWS_PER_RECORD] for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD) ] n_chunks = len(chunks) for cidx, chunk in enumerate(chunks): posting_rows.append( { "term": term, "document_indices": [int(d) for d, _, _ in chunk], "title_frequencies": [int(ttf) for _, ttf, _ in chunk], "body_frequencies": [int(btf) for _, _, btf in chunk], "tfs": [ TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf) for _, ttf, btf in chunk ], "lengths": [int(round(doc_len[int(d)])) for d, _, _ in chunk], "document_lengths": [ int(round(doc_len[int(d)])) for d, _, _ in chunk ], "document_frequency": int(dfreq), "corpus_frequency": int(cfreq), "idf": float(idf), "posting_chunk_index": int(cidx), "posting_chunk_count": int(n_chunks), "schema_version": SCHEMA_VERSION, } ) n_postings += dfreq if len(posting_rows) >= 8_000: pd.DataFrame(posting_rows).to_parquet( spill / f"postings_part_{part_i:08d}.parquet", index=False ) posting_rows.clear() part_i += 1 gc.collect()
for term, doc, ttf, btf in conn.execute( "SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc" ).fetchall(): term = str(term) if cur_term is None: cur_term = term if term != cur_term: flush_term(cur_term, cur_items) cur_items = [] cur_term = term if n_terms and n_terms % 50_000 == 0: checkpoint(f"bm25_postings_terms", row=n_terms, every_n=50_000, log=log) cur_items.append((int(doc), int(ttf), int(btf))) if cur_term is not None: flush_term(cur_term, cur_items) if posting_rows: pd.DataFrame(posting_rows).to_parquet( spill / f"postings_part_{part_i:08d}.parquet", index=False ) posting_rows.clear() conn.close() gc.collect()
parts = sorted(spill.glob("postings_part_*.parquet")) frames: list[pd.DataFrame] = [] for i, part in enumerate(parts): frames.append(pd.read_parquet(part)) if len(frames) >= 8: frames = [pd.concat(frames, ignore_index=True)] gc.collect() if i and i % 20 == 0: checkpoint(f"concat_postings", row=i, every_n=20, log=log) postings = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame() del frames for part in parts: part.unlink() postings.to_parquet(post_path, index=False) out_rows = len(postings) del postings gc.collect() stats = { "k1": K1, "b": B, "title_weight": TITLE_WEIGHT, "body_weight": BODY_WEIGHT, "average_document_length": avgdl, "tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1", "max_query_terms": 64, "posting_rows_per_record": POSTING_ROWS_PER_RECORD, "terms_per_shard": TERMS_PER_SHARD, "n_docs": n_docs, "n_terms": int(n_terms), "n_posting_rows": int(out_rows), "n_postings": int(n_postings), } stats_json.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8") try: bm25_db.unlink() except Exception: pass if log: log(f"bm25 spill done terms={n_terms} posting_rows={out_rows}") return {"stats": stats, "documents": docs_path, "postings": post_path}
def should_use_spill(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool: return n_docs >= threshold
def should_use_sqlite(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool: """Alias: large-corpus path is DuckDB/parquet, not SQLite.""" return should_use_spill(n_docs, threshold)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203"""Extract legal hierarchy from country-law text (Oregon-style, multilingual).
Oregon Revised Statutes are stored as title / chapter / section / subsectiontrees. National gazettes are not that uniform: some use Article/Artikel,some §, some only a single instrument body.
This module:
* strips leftover HTML chrome so GraphRAG sees legal text, not tags;* detects multilingual heading markers (title/chapter/part/article/section);* splits an instrument into those units when at least two headings exist;* otherwise keeps the whole instrument (never invents a hierarchy).
Subsection markers such as ``(a)`` / ``(1)`` are recorded on the parentunit; they are not forced into their own retrieval rows."""
from __future__ import annotations
from dataclasses import dataclass, fieldfrom html.parser import HTMLParserimport html as html_libimport jsonimport osfrom pathlib import Pathimport reimport unicodedatafrom typing import Any
_WS_RE = re.compile(r"\s+", re.UNICODE)_HAS_TAG_RE = re.compile(r"</?[a-zA-Z][^>]*>")
# 1:1 map so match offsets stay aligned with the stored body. re.I does not# treat É as E; gazettes use Décision, Ordonnance, Điều, Člen, etc._LATIN_FOLD = str.maketrans({ **dict.fromkeys("áàâäãåăąāấầẩẫậắằẳẵặảạ", "a"), **dict.fromkeys("ÁÀÂÄÃÅĂĄĀẢẠ", "A"), **dict.fromkeys("éèêëěęēếềểễệẻẹə", "e"), **dict.fromkeys("ÉÈÊËĚĘĒẺẸƏ", "E"), **dict.fromkeys("íìîïĩįīıịỉ", "i"), **dict.fromkeys("ÍÌÎÏĨĮĪİỈỊ", "I"), **dict.fromkeys("óòôöõőøōốồổỗộớờởỡợỏọ", "o"), **dict.fromkeys("ÓÒÔÖÕŐØŌỎỌ", "O"), **dict.fromkeys("úùûüűũūůứừửữựủụ", "u"), **dict.fromkeys("ÚÙÛÜŰŨŪŮỦỤ", "U"), **dict.fromkeys("ýÿỳỹỷỵ", "y"), **dict.fromkeys("ÝŸỶỴ", "Y"), **dict.fromkeys("çćčĉċ", "c"), **dict.fromkeys("ÇĆČĈĊ", "C"), **dict.fromkeys("ďđ", "d"), **dict.fromkeys("ĎĐ", "D"), **dict.fromkeys("ğĝģġ", "g"), **dict.fromkeys("ĞĜĢĠ", "G"), **dict.fromkeys("ñńņň", "n"), **dict.fromkeys("ÑŃŅŇ", "N"), **dict.fromkeys("ŕŗř", "r"), **dict.fromkeys("ŔŖŘ", "R"), **dict.fromkeys("śŝşšș", "s"), **dict.fromkeys("ŚŜŞŠȘ", "S"), **dict.fromkeys("ţťț", "t"), **dict.fromkeys("ŢŤȚ", "T"), **dict.fromkeys("źżž", "z"), **dict.fromkeys("ŹŻŽ", "Z"), **dict.fromkeys("ĺļľł", "l"), **dict.fromkeys("ĹĻĽŁ", "L"), "æ": "a", "Æ": "A", "œ": "o", "Œ": "O", "ß": "s", "ɛ": "e", "Ɛ": "E", "ɔ": "o", "Ɔ": "O", "ŋ": "n", "Ŋ": "N", **dict.fromkeys("ơớờởỡợ", "o"), **dict.fromkeys("ƠỚỜỞỠỢ", "O"), **dict.fromkeys("ưứừửữự", "u"), **dict.fromkeys("ƯỨỪỬỮỰ", "U"), **dict(zip("άέήίόύώϊϋΐΰ", "αεηιουωιυιυ")), **dict(zip("ΆΈΉΊΌΎΏ", "ΑΕΗΙΟΥΩ")), "ς": "σ", "ё": "е", "Ё": "Е", "ї": "и", "Ї": "И", "є": "е", "Є": "Е", "ґ": "г", "Ґ": "Г",})
def _latin_fold(text: str) -> str: return text.translate(_LATIN_FOLD)
# Headings at line start *or* after . ; : so compacted "Art. 1. … Art. 2." still splits.# Separator allows "Art. 1", "Art.1", "Član 12.", "ARTICULO 10.-", "Madde 1 –",# "Article (1)", French "Art. L. 111-1", Roman "ARTICLE I"._HEADING_NUM = ( r"(?:[0-9٠-٩۰-۹]+(?:er|ère|bis|ter|quater|o)?" r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])" r"|premier(?:e)?|première|primero|primeira" r"|unique|unico|unica|único|única)")_ARTICLE_N = ( r"(?:" r"(?:[LRD]\.?\s*)?" r"(?:" r"[0-9٠-٩۰-۹]+(?:\.[0-9]+)?" r"(?:er|ère|bis|ter|quater|aad|[A-Za-z]|o)?" r"(?:/[0-9A-Za-z]+)?" r"(?:\s+(?:bis|ter|quater))?" r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])" r"|[Α-Ω]{1,6}(?![Α-Ωα-ω])" r")" r"(?:[-–](?:[0-9]+|aad|bis|ter|quater|[A-Za-z](?![A-Za-z])))?" r"(?:\([0-9A-Za-z]+\))?" r"|premier(?:e)?" r"|première" r"|unique|unico|unica|único|única" r"|primero|primera|primeiro|primeira" r"|primo(?![A-Za-z])|secondo(?![A-Za-z])|terzo(?![A-Za-z])|quarto(?![A-Za-z])|quinto(?![A-Za-z])|prima(?![A-Za-z])" r"|eerste|första|første" r"|annexe" r"|primera|segunda|tercera|cuarta|quinta" r"|sexta|séptima|octava|novena|décima" r")")_HEADING_START = r"(?:^|(?<=[.;:])|(?<=\d[ \t]))[ \t\[\(\u00ab\u00bb\"“”‘’«»‹›\u2039\u203a]*"_HEADING_RE = re.compile( _latin_fold( r"(?im)" + _HEADING_START + r"(?:" r"(?P<title>TITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|TITLUL|T[IÍ]TUL|LUKU|PEAT[UÜ]KK|" r"РАЗДЕЛ|РОЗДІЛ|DZIA[ŁL]|ΤΙΤΛΟΣ|ДЯЛ)\s+" r"(?P<title_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)" r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|" r"ROZDZIA[ŁL]|CAPITOLUL|NODA[ĻL]A|GLAVA|ГЛАВА|POGLAVLJE|KAPITOLA|" r"ΚΕΦΑΛΑΙ[ΟO]|CH[UƯ][OƠ]NG|BAB|KABANATA|CAPO|HLAVA|KREU|FEJEZET|" r"B[ÖO]L[ÜU]M|FESIL|CAIBIDIL|PENNOD|KAPITOLU|CHAPIT|ODDIEL|" r"SURA(?:\s+YA)?|KAPITTEL|KAPITTUL|ANDIANY|SASHE(?:\s+NA)?|WASE|" r"ISIGABA|ICANDELO|KGAOLO|BOBI|KUTAA|ORI|CAP\.)\s+" r"(?P<chapter_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)" r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL|LIVRE|BOOK|BUCH|TOMO|KNIHA|" r"KODEKS|CODE|ZAKONIK|BAHAGIAN|BAGIAN|SEHEMU|MỤC|MUC|LIBRO|PH[AẦ]N|" r"QAYBTA|WAHANGA|VAEGA|HAP|KAROLO|CHIKAMU|BES|EKITUNDU|ETENI|" r"AKPA|FAANDA|PATTE|ΜΕΡΟΣ)\s+" r"(?P<part_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)" r"|(?P<article>(?:l['’])?(?:(?:EK|GEÇICI|GECICI|GEÇİCİ)\s+)?" r"(?:ART(?:ICLE|IKEL|ÍCULO|ICULO|IGO|ICOLO|IKKEL|YKU[ŁL]|ICOLUL|ICOL|IKOLU|IKULA)?\.?" r"|ART\.|NENI|PASAL|MADDE|MADDƏ|ĐIỀU|ĐIÊU|DIEU|CLANAK|ČLANAK|ČLÁNEK|ČLÁNOK|ČLEN|ČLAN|CLAN" r"|ЧЛАНАК|ЧЛАН|ЧЛЕН|ЧЛ\.|СТАТЬЯ|СТАТТЯ|SZAKASZ|CIKK|ΆΡΘΡΟ|ΑΡΘΡΟ" r"|PYKÄLÄ|GREIN|PANTS|SEKSYEN|CIKK|KIFUNGU|MODDA|ATIK|KUPU|ATIKOL|" r"INGINGO(?:\s+YA)?|NDIME|ABALA|NKEJI|SARIYA|TERE|AHYEDE|PENNAD|ERTHYGEL|HYEDEE|" r"ARTIGU|PAUKU|IRAVA" r"|მუხლი|ՀՈԴՎԱԾ|Հոդված))(?![A-Za-z])" r"(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*" r"(?P<article_n>" + _ARTICLE_N + r")\)?" r"|(?P<section>SUB(?:-)?SECTION|SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|PARAGRAHV|PARAGRAPHE|PARAGRAAF|PARAGRAPH|" r"RECITAL|CONSIDERANDO|" r"ALIN[EÉ]A|ALINEATUL|INCISO|P[AÁ]RRAFO|PUNKT(?![A-Za-z])|SATZ(?![A-Za-z])|LID|" r"ΠΑΡΑΓΡΑΦΟΣ|ABSATZ|APARTADO|COMMA(?![A-Za-z])|FIKRA|STAVAK|STK\.?|АЛ\.|SEKSHON|" r"NUMERAL|CAPOVERSO|NUMMER|" r"AYAT|KHOẢN|KHOAN|" r"RULE(?![A-Za-z])|REGULATION(?![A-Za-z])|SCHEDULE(?![A-Za-z])|FORM(?![A-Za-z])|" r"ORDINANCE|ORDONNANCE|ORDONAN[TŢȚ][AĂÁ]?|ORDIN(?![A-Za-z])|BY-?LAW|DIRECTIVE(?![A-Za-z])|" r"D[EÉ]CISION(?![A-Za-z])|DECISION(?![A-Za-z])|DECIZIE|" r"BESLUIT(?![A-Za-z])|REGELING(?![A-Za-z])|BESCHIKKING(?![A-Za-z])|" r"ODLUKA|PRAVILNIK|HOT[ĂA]R[ÂAÎI]RE|" r"RESOLUCI[OÓ]N(?![A-Za-z])|RESOLU[CÇ][AÃ]O(?![A-Za-z])|PORTARIA(?![A-Za-z])|ACUERDO(?![A-Za-z])|" r"MEDIDA\s+PROVIS[OÓ]RIA|" r"PROCLAMATION(?![A-Za-z])|PROKLAMATION|CIRCULAR(?![A-Za-z])|INSTRUCTION(?![A-Za-z])|" r"GUIDELINE(?![A-Za-z])|MEMORANDUM(?![A-Za-z])|" r"AVISO(?![A-Za-z])|AVIS(?![A-Za-z])|BEKANNTMACHUNG|MEDDELANDE|" r"NORMA(?![A-Za-z])|" r"PRESIDENTIAL\s+DECREE|DECRETO-LEI|DECRETO(?![A-Za-z])|DECREE(?![A-Za-z])|" r"D[EÉ]CRET-LOI|D[EÉ]CRET(?![A-Za-z])|ARR[EÊ]T[EÉ]|" r"DELIBERA[CÇ][AÃ]O|D[EÉ]LIB[EÉ]RATION|COMUNICADO|" r"R[EÈ]GLEMENT(?![A-Za-z])|CIRCULAIRE(?![A-Za-z])|VERORDNUNG(?![A-Za-z])|ERLASS(?![A-Za-z])|" r"PUNTO(?![A-Za-z])|SUB(?:-)?PARAGRAPH|" r"ANNEX(?:E)?(?![A-Za-z])|ANEXO|ANLAGE|BIJLAGE|APPENDIX|ALLEGATO|" r"ZA[ŁL][AĄ]CZNIK|BILAGA|LIITE|P[ŘR][IÍ]LOHA|" r"UST\.|ODST\.|ODS\.|BEK\.|" r"SEC(?:\.|(?=\s+[0-9])))(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?[.\s:]*\(?\s*" r"(?P<section_n>(?:[0-9][0-9A-Za-z.\-]*(?:\([0-9A-Za-z]+\))?|" r"(?-i:[IVXLCDM]{1,8})(?![A-Za-z])|[A-Za-z](?![A-Za-z])))\)?" r"|(?P<section_sym>§+)\s*(?P<section_sym_n>[0-9]+(?:[A-Za-z](?![A-Za-z]))?(?:\s+[A-Za-z](?![A-Za-z]))?(?:\s*\([0-9A-Za-z]+\))?)" r"|(?P<section_pre_n>[0-9]+(?:\s*[a-z])?)\s*\.?\s*(?P<section_pre>§)" r"|(?P<grein_n>[0-9]+[a-z]?)\s*\.\s*(?P<grein>gr|pants)(?![A-Za-z])\.?" r"|(?P<straipsnis_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<straipsnis>straipsnis)" r"|(?P<artikulua_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<artikulua>artikulua)" r"|(?P<ledd_n>[0-9]+)\s*[.]?\s*(?P<ledd>ledd)" r"|(?P<kap_n>[0-9]+)\s*(?P<kap>kap)\.?" r"|(?P<luku_n>[0-9]+)\s*(?P<luku>luku)" r"|(?P<fejezet_n>[IVXLCDM0-9]+)\s*\.\s*(?P<fejezet>fejezet)" r"|(?P<peatukk_n>[0-9]+)\s*[.]?\s*(?P<peatukk>peat[uü]kk)" r"|(?P<skyrius_n>[IVXLCDM0-9]+)\s*(?P<skyrius>skyrius)" r"|(?P<nodala_n>[IVXLCDM0-9]+)\s*(?P<nodala>noda[ļl]a)" r"|(?P<kafli_n>[IVXLCDM0-9]+)\s*[.]?\s*(?P<kafli>kafli)" r"|(?P<bob_n>[0-9]+)\s*-\s*(?P<bob>bob)" r"|(?P<tarau_n>[0-9]+)\s*-\s*(?P<tarau>тарау)" r"|(?P<bolum_n>[0-9]+)\s*-\s*(?P<bolum>бөлүм)" r"|(?P<modda_n>[0-9]+)\s*-\s*(?P<modda>модда|modda)" r"|(?P<mn_n>[0-9]+)\s*(?P<mn>(?:дүгээр|дугаар)\s*зүйл)" r"|(?P<kk_n>[0-9]+)\s*-?\s*(?P<kk>бап)" r"|(?P<mom_n>[0-9]+)\s*(?P<mom>momentti)" r"|(?P<order>(?:EXECUTIVE\s+)?ORDER)\s+(?P<order_n>[0-9]+)" r"|(?P<kidogo>KIFUNGU\s+KIDOG[OU])\s*\(?\s*(?P<kidogo_n>[0-9]+)" r"|(?P<disp>DISPOSICI[OÓ]N)(?:\s+(?:adicional(?:es)?|transitoria(?:s)?|derogatoria(?:s)?|final(?:es)?))?\s+" r"(?P<disp_n>" + _ARTICLE_N + r")" r"|(?P<esresol>primero|segundo|tercero|cuarto|quinto|sexto|septimo|octavo|noveno|decimo|" r"erstens|zweitens|drittens|viertens|funftens|" r"premierement|deuxiemement|troisiemement|quatriemement|cinquiemement)\s*:" r")" ))# Commonwealth "1. Short title" — used only when keyword headings are scarce._PAREN_SUBSECTION_RE = re.compile(r"^\(\s*[0-9A-Za-z]{1,6}\s*\)")_CW_NUM_RE = re.compile( r"(?m)^[ \t]*(?P<cw_n>[0-9]+[A-Za-z]?)\.?\s*[-–—]?\s*" r"(?:\(\s*[0-9A-Za-z]+\s*\)\s+)?" r"(?=[A-Z][a-z]+|[A-Z]{3,}\b|A\s)")_MONTH_START_RE = re.compile( r"(?i)^(january|february|march|april|may|june|july|august|september|october|november|december|" r"janvier|f[eé]vrier|marzo|abril|enero|junio|julio)\b")# Malta bye-laws and Zambia Acts put the marginal note before the section number:# "Citation. 1." and "Prohibited 33." A dotted number such as "Penalty. 5.1" needs no# extra period. Months, chapter citations, and schedule labels are not section notes._MARGINAL_NOTE_RE = re.compile( r"(?m)^(?P<marginal>[A-Z][A-Za-z]{2,40}\.?)\s+" r"(?P<marginal_n>(?:[0-9]+(?:\.[0-9]+){1,3}|[0-9]{1,4}(?=\.(?!\d))))")_MARGINAL_STOP = frozenset({ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december", "janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "aout", "septembre", "octobre", "novembre", "decembre", "enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto", "septiembre", "octubre", "noviembre", "diciembre", "cap", "from", "open", "table", "figure", "box", "plate", "page", "item", "act", "ley", "total", "column", "nr", "no", "nos", "pag", "pagina", "data", "saldo", "and", "the", "for",})_CW_NUM_LANGS = frozenset({"", "en", "hi", "bn", "ne", "ur", "ms", "fil", "sw", "si"})_LEXICON_HEADING_RE: re.Pattern[str] | None = None_LEXICON_KIND: dict[str, str] = {}
_SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)")
_KIND_RANK = { "title": 1, "chapter": 2, "part": 3, "article": 4, "section": 5, "subsection": 6,}
MIN_SPLIT_HEADINGS = 2MIN_UNIT_CHARS = 40
# Markers on the *stored* body (no rewritten newline copy)._ZH_ART_RE = re.compile( r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:之[一二三四五六七八九十百0-9]+)?")_AR_ORD = ( r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*والعشرون|" r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*عشرة|" r"العشرون|" r"الأولى|الأولي|األولى|الاولى|الثانية|الثالثة|الرابعة|الخامسة|" r"السادسة|السابعة|الثامنة|التاسعة|العاشرة")_AR_ORD_M = ( r"الأول|الاول|الثاني|الثالث|الرابع|الخامس|" r"السادس|السابع|الثامن|التاسع|العاشر")_AR_ART_RE = re.compile( r"\(?(?:الماد[ةه]|املاد[ةه]|مادة)\s*[-–]?\s*[()]*\s*(?:[0-9٠-٩۰-۹]+|" + _AR_ORD + r")" r"(?:\s*[-–])?(?:\s*[()]*)?(?:\s*مكرر(?:اً|ا)?)?")_CITE_TAIL_RE = re.compile( _latin_fold( r"(?i)\s+(?:" r"of\s+(?:this\s+|the\s+)?(?:act|law|agreement|code|constitution|article|section|" r"principal\s+act|ordinance|regulation|decree|chapter|part|title|ruling|order)" r"|thereof\b" r"|hereof\b" r"|hereunder\b" r"|de\s+la\s+(?:loi|ley|presente|présente)" r"|du\s+(?:code|présent|present)" r"|des\s+gesetzes" r"|van\s+(?:deze\s+)?(?:wet|artikel)" r"|i\s+lov\b" r"|cua\s+luat(?:\s+nay)?" r")\b" ))_NUMERO_FOLD_RE = re.compile( r"(?i)(?:№|n\.\s*o\b|n\.?[°º]|nÂ[oº°]|\bno\.?\s+(?=\d))\.?\s*")_CJK_RANGE_RE = re.compile( r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條]\s*(?:至|到|から)\s*" r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:まで)?")_FA_ORD = ( r"یازدهم|دوازدهم|سیزدهم|چهاردهم|پانزدهم|شانزدهم|هفدهم|هجدهم|نوزدهم|بیستم|" r"اولی?|نخست|دوم|سوم|چهارم|چارم|جارم|پنجم|ششم|هفتم|هشتم|نهم|دهم")_FA_ART_RE = re.compile(r"(?:ماده|مادة)\s*(?:[0-9۰-۹]+|" + _FA_ORD + r")")_DA_ART_RE = re.compile(r"(?:Artikel|§)\s*[0-9]+", re.IGNORECASE)_CHROME_LINE_RE = re.compile( r"(?i)^(?:" r"početna stranica\b.*|" r"upute za korištenje\b.*|" r"elektronička pošta\b.*|" r"vsebina uradnega lista\b.*|" r"the incident id is\b.*|" r"ωράριο λειτουργίας\b.*|" r"τηλέφωνο επικοινωνίας\b.*|" r"skip to (?:main )?content\b.*|" r"javascript is (?:required|disabled)\b.*|" r"privacy policy\s*$|" r"traduction française pour information\s*$|" r"pdf\s*$|" r"https?://\S+\s*$|" r"légimonaco\b.*|" r"statutory instruments\s*$|" r"official gazette\s*$|" r"government gazette\s*$|" r"(?:the )?london gazette\s*$|" r"journal officiel(?: de la république(?: [^\n]{0,40})?)?\.?\s*$|" r"bulletin officiel\s*$|" r"gazette du canada\s*$|" r"(?:the )?[\w .'-]{0,50}gazette\s*$|" r"الوقائع المصرية\s*$|" r"الوقائع العراقية\b.*|" r"العدد\s*$|" r"العدد\s+\S.{0,80}الوقائع\b.*|" r".*شعبة الجريدة الرسمية\s*$|" r"(?:the )?(?:republic of sudan gazette|gazette published by authority|official gazette of the republic of sudan)\b.*|" r"الصفحة(?:\s*[0-9٠-٩]+)?\s*$|" r"(?:الجريدة|اجلريدة|جريدة)(?:\s+الر\s*سمية)?(?:\s+العدد(?:\s*\(\s*\)?\s*[0-9٠-٩]+)?)?\s*$|" r"république du s[ée]n[ée]gal\s*$|" r"jamhuuriyadda\b.*|" r"warta kerajaan\s*$|" r"lembaran negara\s*$|" r"berita negara\s*$|" r"công báo\s*$|" r"la gaceta\s*$|" r"no\.?\s*\d+\s+government gazette\b.*|" r"supplement to (?:the |official ).{0,60}gazette\b.*|" r"[a-z0-9 ,.'()-]*supplement to official gazette[a-z0-9 ,.'()-]*$|" r"printed by\b.*|" r"https?://\S+(?:\s+\d+(?:\.\d+)*)?\s*$|" r"©+\s*.*congress\b.*|" r"(?:s|sm)\s+congress\b.*|" r"palikir,\s*pohnpei\b.*|" r"www\.\S+(?:\s+\d+)?\s*$|" r"at\s+www\.\S+\s*$|" r".*research bulletin.*|" r"acts supplement\s*$|" r"supplement\s+(?:nr\.\s*|no\.?\s*)\d+(?:\s+\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\.?)?\s*$|" r"no\.\s+of\s+\d{4}\.?\s*$|" r"act no\.\s+of\s+\d{4}\.?\s*$|" r"bill for the\s*$|" r"(?:the )?republic of [a-z]+(?:\s+[a-z]+)?\s*$|" r"federal republic of [a-z]+(?:\s+[a-z]+)?\s*$|" r"democratic people's republic of korea\s*$|" r".{0,10}republic of palau\s*$|" r"saint vincent and the grenadines\s*$|" r"\[?\s*član\s+\.\.\.\s*\]?\s*$|" r".*аудиони тинглаш.*|" r"reprint\s*$|" r"reprint authorised by\b.*|" r"parliament building\s*$|" r"oau drive, tower hill\s*$|" r"office of the clerk of parliament\s*$|" r"(?:(?:first|second|third|fourth|fifth)\s+parliament(?:\s+of\s+the\s+(?:first|second|third|fourth|fifth)\s+republic)?\s*){1,2}$|" r"(?:(?:first|second|third|fourth|fifth)\s+meeting of parliament\s*){1,2}$|" r"تفاصيل\s+(?:النظام|اللائحة)\s*$|" r"مجموعة الأنظمة السعودية\s*$|" r"المجلد\s+\S+\s*$|" r"أنظمة\s+\S.{0,60}$|" r"(?:first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth)\s+folder\s*$|" r"this law includes:\s*$|" r"-\s*اختر\s*-\s*$|" r"تاريخ الإصدار\s*$|" r"تاريخ النشر\s*$|" r"الحالة\s*$|" r"ساري\s*$|" r"العربية\s*$|" r"الإسم\s*$|" r"البريد الإلكتروني\s*$|" r"رقم الجوال\s*$|" r"نوع البلاغ\s*$|" r"\d{4}/\d{2}/\d{2}\s+ه\s+الموافق\s*:?\s*\d{2}/\d{2}/\d{4}\s+م\s*$|" r"\d{3,4}\s+ه\s*$|" r"خطأ لغوي\s*$|" r"خطأ في مادة\s*$|" r"يتضمن (?:النظام|التنظيم) ما يلي\s*:?\s*$|" r"عدد مرات التصفح\s*\d*\s*$|" r"نبذة عن النظام\s*$|" r"اسم النظام/اللائحة\b.*|" r"تاريخ (?:إصدار|نشر) النظام/اللائحة\s*$|" r"حالة النظام/اللائحة\b.*|" r"أدوات إصدار النظام\s*$|" r"نص النظام\s*$|" r"مادة معدلة\s*$|" r"مادة ملغية\s*$|" r"اصل الوثيقة\s*$|" r"طباعة\s*$|" r"إبلاغ\s*$|" r"الإصدارات\s*$|" r"اللغات\s*$|" r"الإنجليزية\s*\(English\)\s*$|" r"(?:\d{4}\s+)?revised edition(?:\s+as at\b.*|\s+page\s+\d+)?\s*$|" r"page\s+\d+\s+\d{4}\s+revised edition\s*$|" r"\[note: this version\b.*|" r"\[this is the version of this document\b.*|" r"el peruano\s*$|" r"(?:act\s+\d+\s+of\s+\d{4}\s+)?page\s*\d+(?:\s+(?:of\s+\d+|act\s+\d+\s+of\s+\d{4}|[a-z]))?\s*$|" r"[a-z]\s+page\s*\d+\s*$|" r"(?:section\s+)?pages?\s*$|" r"seite\s+\d+(?:\s+(?:von|of|bis)\s+\d+)?\s*$|" r"bundesrecht konsolidiert\b.*|" r".*ris\.bka\.gv\.at.*$|" r"\{\\rtf\d+\b.*|" r"p[aá]gina\s+\d+\s*$|" r"pagina\s+\d+\s*$|" r"strona\s+\d+\s*$|" r"p\.\s*\d+(?:\s+(?:of|di|von|sur|de)\s+\d+)?\s*$|" r"pag\.\s*\d+(?:\s+(?:di|of|de)\s+\d+)?\s*$|" r"blz\.\s*\d+\s*$|" r"folio\s+\d+\s*$|" r"foglio\s+\d+\s*$|" r"лист\s+\d+\s*$|" r"стр\.\s*\d+\s*$|" r"ص\s*\.?\s*\d+\s*$|" r"עמוד\s+\d+\s*$|" r"trang\s+\d+\s*$|" r"halaman\s+\d+\s*$|" r"sayfa\s+\d+\s*$|" r"oldal\s+\d+\s*$|" r"stran(?:ica)?\s+\d+\s*$|" r"www\.\S+\s*$|" r"downloaded from\b.*|" r"printed on\s+\d.*|" r"generated by\b.*|" r"e-?mail:\s*\S+@\S+\s*$|" r"tel(?:ephone)?:\s*[+\d].*$|" r"for more information visit\b.*|" r"[-–—]\s*\d{1,4}\s*[-–—]\s*$|" r"table of contents\s*$|" r"table des mati[eè]res\s*$|" r"inhaltsverzeichnis\s*$|" r"(?:índice|indice)\s*$|" r"sommaire\s*$|" r".*\barrangement of (?:sections|provisions|regulations|rules)\.?(?:\s+cap\.\s*[\d.]+.*)?\s*$|" r"contents\s*$|" r"section\s*$|" r"[\s.\-;,*/_×|+~•·{}()\\=»«®∞]+$|" r"(?=.*[+|])[+\-|]{3,}\s*$|" r"\[original service \d{4}\].*|" r"statute law of the [a-z ]+$|" r"[A-Z][A-Z .'\-]{0,40}\[ch\.\s*\d+.*|" r"التاريخ:\s*$|" r"republic of the marshall islands\s*$|" r"jepilpilin ke ejukaan\s*$|" r"zastupni[cč]ki dom hrvatskoga sabora\s*$|" r"dr[zž]avni zavod za normizaciju i mjeriteljstvo\s*$|" r"олдинги таҳрирга қаранг\.?\s*$|" r"explanatory note\s*$|" r"\.\s*\(\s*\d+\s*\)\s*$|" r"(?:يناير|فبراير|مارس|أبريل|ابريل|مايو|يونيو|يوليو|أغسطس|اغسطس|سبتمبر|أكتوبر|اكتوبر|نوفمبر|ديسمبر)\s+\d{4}\s*$|" r"laws of (?:the )?[a-z]+(?:\s+(?:&|[a-z]+)){0,4}\s*$|" r"(?-i:LAWS OF (?:THE )?[A-Z]+(?:\s+[A-Z]+){0,6}\s+s\s*\d+\s*$)|" r"(?:í|i)ndice legislativo\s*$|" r"قائمة (?:المحتويات|احملتويات)\s*$|" r"spis tre[sś]ci\s*$|" r"содержание\s*$|" r"πίνακας περιεχομένων\s*$|" r"목차\s*$|" r"目次\s*$|" r"สารบัญ\s*$|" r"[aα]ριθμός\s+\d+[^\n]{0,24}\s*$|" r"[aα]ρ\.\s*\d+(?:/\d+)?[^\n]{0,12}\s*$|" r"številka\s+\d+[^\n]{0,24}\s*$|" r"(?:nr|no|n[uú]m(?:ero|éro|ber)?|broj|č[ií]slo|szám|sayı|номер)\.?\s*\d{2,}(?:/\d+)?[.\s]*$|" r"№\s*\d+\s*$|" r"copyright\s*©?\s*\d{4}.*$|" r"©\s*\d{4}.*$|" r"\d{1,2}[./-]\d{1,2}[./-]\d{2,4}\s*$|" r"\d{4}-\d{2}-\d{2}\s*$|" r"\d{1,2}\s+(?:january|february|march|april|may|june|july|august|september|october|november|december|" r"janvier|f[eé]vrier|mars|avril|mai|juin|juillet|ao[uû]t|septembre|octobre|novembre|d[eé]cembre|" r"enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)\s+\d{4}\s*$|" r"end of (?:the )?document\s*$|" r"fin du document\s*$|" r"ende des dokuments?\s*$|" r"fin del documento\s*$|" r"fim do documento\s*$|" r"[-*=._]{3,}\s*$|" r"published\s*$|" r"publi[eé]\s*$|" r"publicado\s*$|" r"veröffentlicht\s*$|" r"\[?seal\]?\s*$|" r"\(seal\)\s*$|" r"l\.s\.?\s*$|" r"god save the (?:king|queen)\s*$|" r"vive la r[eé]publique\s*$|" r"by (?:order|command)\s*$|" r"signed\s*$|" r"diario oficial(?: de la federación)?\s*$|" r"gazzetta ufficiale(?: della repubblica(?: italiana)?)?\s*$|" r"boletín oficial(?: del estado)?\s*$|" r"diário da república\s*$|" r"bundesgesetzblatt\s*$|" r"moniteur belge\s*$|" r"belgisch staatsblad\s*$|" r"staatsblad\s*$|" r"lovtidende\s*$|" r"svensk författningssamling\s*$|" r"uradni list\s*$|" r"dziennik ustaw\s*$|" r"monitorul oficial\s*$|" r"εφημερίδα της κυβερνήσεως\s*$|" r"resmi gazete\s*$|" r"iris oifigiúil\s*$|" r"latvijas vēstnesis\s*$|" r"valstybės žinios\s*$|" r"官報\s*$|" r"国务院公报\s*$|" r"관보\s*$|" r"ราชกิจจานุเบกษา\s*$|" r"(?:เล่ม|เลม)\s*[๐-๙0-9].*ราชกิจจานุเบกษา.*|" r"اطلاق نسخة جديدة من الميزان\s*$|" r"\[\d+/\d{4}(?:\s+wef\s+[\d/]+)?\]\s*$|" r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+\s+\d{4}\]\s+.+\s+\d{1,4}\s*$|" r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\]\s*$|" r"(?:18|19|20)\d{2}\s*$|" r"gazette\.?\s*$|" r"cap\.\s*\d+(?:\.\d+)*\s*$|" r".+\scap\.?\s*[\d.]+\s+section\s+\d+\s*$|" r"diario oficial\s*$|" r"diário oficial(?: da união)?\s*$|" r"gaceta oficial(?: de la república)?\s*$|" r"registro oficial\s*$|" r"sbírka zákonů\s*$|" r"zbierka z[^\n]{0,40}\s*$|" r"magyar közlöny\s*$|" r"narodne novine\s*$|" r"službeni glasnik\s*$|" r"службени гласник\s*$|" r"държавен вестник\s*$|" r"monitorul oficial(?: al româniei)?\s*$|" r"norsk lovtidend\s*$|" r"suomen säädöskokoelma\s*$|" r"finlands författningssamling\s*$|" r"riigi teataja\s*$|" r"российская газета\s*$|" r"(?:the )?kenya gazette\s*$|" r"federal negar[ie]t gazett?e\s*$|" r"gazette officielle\s*$|" r"amtsblatt(?: der europäischen union)?\s*$|" r"official journal of the european union\s*$|" r"journal officiel de l'union européenne\s*$|" r"gazzetta ufficiale dell'unione europea\s*$|" r"الجريدة الرسمية\b.*|" r"ваш броузер застарів\b.*|" r"your browser is (?:out of date|outdated|obsolete)\b.*|" r"all rights reserved\b.*|" r"subscribe to\s+(?:our\s+)?(?:newsletter|mailing(?:\s+list)?|updates|feed)\b.*|" r"(?:we use|this (?:site|website) uses)\s+cookies\b.*|" r".{0,80}використовуємо cookies\b.*|" r".{0,80}використання cookies\b.*|" r"продовжуючи відвідування сайту\b.*|" r"al meezan\b.*|" r"الميزان\b.*|" r".{0,40}وزارة العدل(?: و الشؤون القانونية)?\s*$|" r"التشريعات\b.*|" r"page not found\b.*|" r"(?:error\s+)?404(?:\s+not found)?\b.*|" r"access denied\s*$|" r"forbidden\s*$|" r"public notification\s*$|" r"[^\n]{0,40}@mjla\b.*|" r".{0,40}gaceta oficial(?: digital)?\b.*|" r"paragraph\s*$|" r"[^\n]{0,60}slov-lex\s*$|" r"(?:crown\s+)?copyright\s*(?:©\s*)?\d{4}\.?\s*$|" r"copying\s*/\s*unauthori[sz]ed distribution strictly prohibited\.?\s*$|" r"(?:revision|consolidation) date\s*:.*|" r"showing the law as at\s+\d.*|" r"this is a revised edition of the law\b.*|" r"printed under authority by\s*$|" r"(?:the )?regional law revision centre\b.*|" r"continued on next page\b.*|" r"back to (?:page one|the top|top)\s*$|" r"page\s*:\s*\d+\s+date\s*:.*|" r"bwpageid\s*::.*|" r"bwservice\s*::.*|" r".*ron_book\b.*|" r"\d+\s+service\s+\d+\s*$|" r"(?:pdf|word|audio)\s+download\s*$|" r"login with (?:facebook|google|apple|twitter|email)\b.*|" r"(?:view|print|e-?mail)\s*$|" r"last updated(?:\s+on)?\s+\d.*|" r"speakers office\s*$|" r"fsm congress\s*$|" r".*almeezan\b.*|" r"add new section\s*$|" r"section name\s*$|" r".*hijripage\b.*|" r"search in articles\s*$|" r"privacy statement\s*$|" r"terms of use\s*$|" r"rate this website\s*$|" r"feedback via reach\s*$|" r"singapore statutes online\b.*|" r".*reprint is authorised by\b.*|" r"công báo\s*/\s*số\b.*|" r"thời gian ký\s*:.*|" r"lex\.?uz\b.*|" r"\[?(?:окоз|тсз|спит)\s*:.*|" r"\d+(?:\.\d{2}){3,}.*[\u0400-\u04FF].*|" r"issue\s*:\s*\d+\s*,\s*amendment\s*:\s*\d+\b.*|" r"presidential comm\.?\s*no\b.*|" r"(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2},?\s+\d{4}(?:\s+[a-z])?\s*$|" r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\.\d+\b(?!.*\b(?!etc\b)[a-z]{3,}\b).*$)|" r"(?-i:(?!.*\b(?!etc\b)[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\.\d+(?:\.\d+)*\s+\d{1,4}\s*$)|" r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\s+(?!.*\b[a-z]{3,}\b).+$)|" r"(?-i:(?!.*\b[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\s+\d{1,4}\s*$)|" r"(?-i:\d{1,4}\s+[Cc]hap\.\s*\d+(?::\d+)?\b(?!.*\b[a-z]{3,}\b).*$)|" r"(?-i:\d{1,4}\s+(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s*$)|" r"(?-i:(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s+\d{1,4}\s*$)|" r"constituci[oó]n pol[ií]tica del per[uú]\s+\d+\s*$|" r"\d{1,4}\s+edici[oó]n del congreso\b.*|" r"nr\.\s*\d+\s*\].*\[.*|" r"st\.?\s*christopher and nevis\s*$|" r"official gazette\s+nr\.\s*\d[\d\s/.-]*(?:\s+of\s+[\d/.-]+)?\s*$|" r"www\.\S+(?:\s+(?!(?:for|under|and|the|is|of)\b)[A-Za-z][\w.-]{1,24}){1,2}\s*$|" r".*laws\.africa\b.*|" r".*share widely and freely.*|" r".*no copyright on the legislative content.*|" r"(?-i:^(?:Malawi|Zambia|Kenya|Uganda|Ghana|Namibia|Botswana|Lesotho|Eswatini|Rwanda|Tanzania|Nigeria|Zimbabwe|Mauritius|Seychelles|Liberia|Gambia)\s+.{0,80}\(Chapter\s+\d+\)\s*$)|" r"(?-i:^Act\s+\d+\s+(?:[A-Z][a-z]+\s+){1,6}(?:19|20)\d{2}\s*$)|" r"issue\s*:?\s*\d+(?:\.\d+)?\s+page\s+\d+\s+of\s+\d+\b.*|" r"issue\s*:\s*\d+(?:\.\d+)?\s+\d+\s+\d{1,2}\s+[a-z]+\s+\d{4}\s*$|" r".*edition officielle mise [aà] jour.*|" r"code general des impots\s+\d{4}\s*$|" r"\d{1,2}\.\d{1,2}\.\d{4}\s*-\s*\d{1,2}\.\d{1,2}\.\d{4}\s*$|" r"(?!.*δημοσιευ)(?!.*\bστην\b)(?=.*εφημερ.{0,12}κυβερν)(?=.*(?:τευξ|τεύχ|\(\s*τευ)).{0,140}$|" r"(?:\d{1,4}\s+)?επ[ιί]σημη\s+εφημερ[ιί]δ[αά]\b.*|" r"sistema integrado de gest[aã]o de finan[cç]as p[uú]blicas\s*\(sigfip\)\s*\d+\s*/\s*\d+\s*$|" r"editado por\s*:.*\beditado em\s*:.*|" r"issue\s+\d{1,4}\s*$|" r"\d{1,4}\s*\|\s*page\s*$|" r"page\s*\|\s*\d{1,4}\s*$|" r"\{\{[^}\n]*\}\}\s*$|" r"lap tetej[eé]re\s*$|" r"megnyitottak\s*$|" r"jogszab[aá]lykeres[oő]\s*$|" r".*slu[zž]beni glasnik\b.{0,50}stranica\s+\d+\s*$|" r".*\(unknown\)/ron\b.*|" r"\[the next page is\s+[\d,]+\s*\]\s*$|" r"service\s+\d+\s+[\d,]+\s*$|" r"\[act\s+\d+\s+of\s+\d{4}\s+wef\s+[\d/]+\]\s*$|" r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})\s+s[eé]rie\s*-\s*n[uú]mero\s+\d+(?:\s+(?:[a-zç]+-feira|s[aá]bado|domingo),?\s*\d{1,2}\s+de\s*[a-zç]+\s+de\s+\d{4})?\s*$|" r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})\s*-?\s*s[eé]rie\b.*\d.*|" r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})s[eé]rie\b.*\d.*|" r"\d+\s+(?:[a-zç]+-feira|s[aá]bado|domingo),?\s+\d{1,2}\s+de\s+[a-zç]+\s+de\s+\d{4}(?:\s+p[aá]gina\s+\d+)?\s*$|" r"s[eé]rie\s+[ivx]+\s*,\s*nr\.\s*\d+\b.{0,80}p[aá]gina\s+\d+\s*$|" r"(?:[a-zç]+-feira|s[aá]bado|domingo),?\s+\d{1,2}\s+de\s+[a-zç]+\s+de\s+\d{4}\s+s[eé]rie\s+[ivx]+\s*,\s*nr\.\s*\d+\s*$|" r"\d+\s*[\(\)]+\s*مذكرة تفسيرية\b.*|" r"-\s*\d+\s*-\s*\).*$|" r".*constituteproject\.org.*|" r"pdf generated\s*:.*|" r"[a-z][a-z]+(?:\s+[a-z][a-z]+){0,3}\s+(?:19|20)\d{2}\s+page\s+\d+\s*$|" r"الصفحة\s*\.?\s*[0-9٠-٩]+\s*$|" r"\[state/territory\]\s*$|" r"direction g[eé]n[eé]rale adjointe des imp[oô]ts\s*$|" r"et des domaines\s*$|" r"rio:\s*\d+\s*$|" r"#+\s*journal officiel\b.*|" r"journal officiel\s*-\s*banque des?\s*donn[eé]es juridiques\b.*|" r"(?!.*\b(?:publie|publi[eé]|shall|entre)\b)journal officiel (?:de la r[eé]publique|du faso)\b.{0,50}$|" r"\[(?:\.{3}|…)\]\s*$|" r"bsd:\s*\d+\s*$|" r"\d{1,2}\.?\s+(?:gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre)\s*$|" r"(?-i:(?:[A-Z][A-Za-z]+\s+){1,12}(?:Act|Law|Code),?\s+(?:19|20)\d{2}(?:\s+(?:19|20)\d{2})?\s+nr\.\s*\d+\s+[A-Z]\s+\d+\s*$)|" r"(?-i:^[A-Z]\s+\d{1,4}\s+(?:19|20)\d{2}\s+nr\.\s*\d+\s+(?:[A-Z][A-Za-z]+\s+){1,12}(?:Act|Law|Code),?\s+(?:19|20)\d{2}\s*$)|" r"printed on the orders? of government\s*\.?\s*$|" r".*(?<![A-Za-z])(?:printed|thinted)\b.{0,80}government printing\b.*|" r"to be purchased at the govt\.?\s*publications bureau\b.*|" r"b\.?\s*l\.?\s*r\.?\s*o\.?\s*\d+\s*/\s*\d{4}\s*$|" r"pages authorised\s*$|" r"(?:current\s+)?authorised pages\s*$|" r"\(inclusive\)\s*by\s+lro\.?\s*$|" r"(?-i:(?:[A-Z][a-z]+(?:\s+|$)){1,8}(?:Malawi|Zambia|Kenya|Uganda|Ghana|Namibia|Botswana|Lesotho|Eswatini|Rwanda|Tanzania|Nigeria|Zimbabwe|Mauritius|Seychelles|Liberia|Gambia)\s*$)|" r"code\s+\S+(?:\s+\S+){0,6}\s+\d{1,3}/\d{2,3}\s*$|" r"index\s*$|" r"ministry/program(?:me)?/sub(?:head|program(?:me)?)\s+page\s*$|" r"page\s+\d{1,3}\s*/\s*\d{1,3}\s*$|" r"\[?\s*printed by authority of the\s*$|" r"printed in [a-z][a-z .'-]{0,40}by the government printer\s*$|" r"[\w.+-]+@[\w.-]+\.[a-z]{2,}\s+www\.\S+\s*$|" r"secr[eé]tariat g[eé]n[eé]ral du gouvernement\s+www\.\S+\s*$|" r"site:\s*(?:https?://|www\.)\S+\s*$|" r"justice sector support program\s*\(jssp\).*|" r"serial number:\s*\d+\b.*|" r"copyright government of [a-z]+(?:\s+[a-z]+){0,3}\s*$|" r"this page was intentionally left blank\.?\s*$|" r"this is page \d+ of \d+\s+pages? of the above table\.?\s*$|" r"new provisions(?: in the schedule)? are printed in italics\.?\s*$|" r"go to top page(?: next chapter)?\s*$|" r"(?:\d{4}\s+)?parliamentary series\s+(?:nr\.|no\.?)\s*\d+\s*$|" r"try reloading the page or downloading the pdf\.?\s*$|" r"reload page\s*$|" r"uploaded by:\s*https?://\S+\s*$|" r"t[eé]l[eé]charg[eé] sur www\.\S+\s*$|" r"ibirimo/summary/sommaire\b.*|" r"website:\s*(?:https?://|www\.)\S+\s*$|" r"www\.\S+\s+[\w.+-]+@[\w.-]+\s*$|" r"gazette order page\.?\s*$|" r"(?:lexis finder|esilec profesional)\s*-\s*www\.\S+\s*$|" r"official gazette\s+(?:nr\.|no\.?)\s*(?:special(?:\s+bis)?|\d+\s*bis)\s+of\b.*|" r"s[eé]rie\s+[ivxlcdm]+\s*,\s*nr\.\s*\S+(?:\s+[A-Za-z0-9]+)?\s*$|" r"unofficial translat(?:ed|ion)\b.*|" r"\(?\d[\d\s().-]{6,}\)?\s*\|\s*(?:https?://|www\.)\S+\s*$|" r"volume:\s*\d+\s+issue no:\s*\d+\s+government gazette\s*$|" r"tonga government gazette supplement\s*$|" r"ministry of legal affairs\s+www\.\S+\s*$|" r"\d+\s+www\.\S+\s*$|" r"www\.\S+\s+\d+\s*/\s*\d+\s*$|" r"www\.\S+\s+(?:(?!for\b|is\b|shall\b|the\b)[a-z][a-z .'-]{0,50})$|" r".*/type/page>{2,}.*|" r"subject\.\s*reference\.\s*page\.?\s*$|" r"name reference page no\.?\s*$|" r"sl\s*#\s*law\s*#\s*legislation commencement gazette\s*$|" r"gn\s*=\s*gazette notice\b.*|" r"de blank page\b.*|" r"printed and published by the ministry of justice\b.*|" r"rarotonga,\s*cook islands:\s*printed under the authority\b.*|" r"e-?mail\s*:\s*\S+@\S+.*(?:site web|www\.)\S+.*|" r"διεύθυνση στο διαδίκτυο\s*\(url\)\s*:\s*https?://\S+.*|" r"spletna stran:\s*www\.\S+\s*$|" r"copyright\s*$|" r"copyright and designs act\s+\d{4}\s*$|" r"copyright act\s+\d{4}\s*$|" r"powered by tcpdf\b.*|" r"pour l'acquisition de votre abonnement\b.*|" r"a\s*bonnement au journal officiel\b.*|" r"[eé]dit[eé] par la direction de l'[eé]dition du journal officiel\b.*|" r"\[the inclusion of this page is authori[sz]ed by\b.*|" r"ins\s*=\s*inserted\b.*|" r"[a-z]{2,8}\s*=\s*gazette\b.*|" r"site web\s*:\s*www\.\S+\s*$|" r"web\s*sites?\s*:?\s*-?\s*www\.\S+\s*$|" r".*www\.documents\.gov\.lk\s*$|" r"τηλ\.?:?\s*[\d\s,]+φαξ:?\s*[\d\s]+\s*-\s*www\.\S+\s*$|" r"das dokument ist einsehbar unter:\s*www\.\S+\s*$|" r"sujet articles page\s*$|" r"language is printed on uneven numbered pages\.?\s*$|" r".*www\.nbs\.sk\.?\s*$|" r"\d{2}-\d{4,6}\s+\d{1,3}/\d{1,3}\s*$|" r"\d{1,3}/\d{1,3}\s+\d{2}-\d{4,6}\s*$|" r"[as]/(?:res|prst)/\d+\s*\(\d{4}\)\s*$|" r"ab\s+\d{4},\s*nr\.\s*\d+\s*$|" r"grondslag\s*:\s*[.\-–\s]*$|" r"رقم الهاتف\s*:.*|" r"\+[\u0600-\u06FF]{1,2}\s*$|" r"(?-i:(?!.*\b(?:est|sont|doit|shall)\b)(?!.*\b[a-z]{4,}\b).*\bImprimerie\s+[A-Z].*$)|" r"(?-i:(?!.*\b(?:shall|is|are|means|under|must)\b).{8,120}\(Chapter\s+\d+(?::\d+)?\)\s+[A-Z][a-z]+\s*$)|" r"(?-i:(?!.*\b(?:ACT|LAW|CODE|DECREE|ORDINANCE|CHAPTER|ARTICLE|SECTION|TITLE|PART|SCHEDULE|GENERAL|PROVISIONS|SHORT|INTERPRETATION|PRELIMINARY|AMENDMENT|REPEAL|COMMENCEMENT|DEFINITIONS|REGULATIONS|RULES|ORDER|APPENDIX)\b)(?:[A-ZÁÉÍÓÚÜÑ]{2,}(?:\s+|$)){4,10}\d{1,3}\s*$)|" r"(?-i:(?!.*\b(?:ACT|LAW|CODE|DECREE|ORDINANCE|CHAPTER|ARTICLE|SECTION|TITLE|PART|SCHEDULE|GENERAL|PROVISIONS|SHORT|INTERPRETATION|PRELIMINARY|AMENDMENT|REPEAL|COMMENCEMENT|DEFINITIONS|REGULATIONS|RULES|ORDER|APPENDIX)\b)\d{3,4}\s+(?:[A-ZÁÉÍÓÚÜÑ]{3,}(?:\s+|$)){1,3}\s*$)|" r"\[\d{1,4}\]?\s*$|" r"หน.?า\s+[0-9๐-๙]+\s*$|" r"(?:home|blog|contact us|cookie|accueil|startseite|" r"página inicial|página principal|επικοινωνία|αρχική)\s*$" r")")_CHROME_INLINE_RE = re.compile( r"(?i)skip to (?:main )?content|all rights reserved|click here|" r"légimonaco")_JA_ART_RE = re.compile(r"第\s*[0-9一二三四五六七八九十百]+\s*[条條]")_CIRCLED_ART_RE = re.compile(r"[①-⑳⑴-⒇❶-❿⓫-⓴]")_CJK_ENUM_RE = re.compile(r"(?m)^[ \t]*[一二三四五六七八九十百]+、")_CJK_PAREN_RE = re.compile(r"(?m)^[ \t]*[((][一二三四五六七八九十百]+[))]")_CJK_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[0-90-9]+、")_KO_GA_RE = re.compile(r"(?m)^[ \t]*[가나다라마바사아자차카타파하]\.")_JA_KATA_ENUM_RE = re.compile(r"(?m)^[ \t]*[アイウエオカキクケコ]、")_HANGUL_GA = "가나다라마바사아자차카타파하"_KATA_ENUM = "アイウエオカキクケコ"_AR_ABJAD_INDEX = { "أ": "1", "ا": "1", "ب": "2", "ج": "3", "د": "4", "ه": "5", "و": "6", "ز": "7", "ح": "8", "ط": "9", "ي": "10",}_HE_ALEF = "אבגדהוזחטי"_TH_KO = "กขคงจฉชซฌญ"_AR_ABJAD_RE = re.compile(r"(?m)^[ \t]*[(\[]?[أابجدهوزحطي][)\]]?\s*[-.)]")_HE_ALEF_RE = re.compile(r"(?m)^[ \t]*[אבגדהוזחטי]\.")_HE_PEREK_RE = re.compile(r"(?m)^[ \t]*פרק\s+[א-ת]{1,3}['׳]?")_HE_SIMAN_RE = re.compile(r"(?m)^[ \t]*סימן\s+[א-ת]{1,3}['׳]?")_HE_HELEK_RE = re.compile(r"(?m)^[ \t]*חלק\s+[א-ת]{1,3}['׳]?")_HE_TOS_RE = re.compile( r"(?m)^[ \t]*תוספת\s+(?:ראשונה|שנייה|שניה|שלישית|רביעית|חמישית|שישית|[א-ת]['׳]?|[0-9]+)")_HE_TAKANA_RE = re.compile(r"(?m)^[ \t]*תקנה\s+[0-9]+")_AR_ANNEX_RE = re.compile(r"(?m)^[ \t]*ملحق(?:\s*رقم)?\s*[0-9٠-٩()]+")_AR_BAB_RE = re.compile( r"(?m)^[ \t]*الباب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")")_AR_FASL_RE = re.compile( r"(?m)^[ \t]*الفصل\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")")_AR_QISM_RE = re.compile( r"(?m)^[ \t]*القسم\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")")_AR_KITAB_RE = re.compile( r"(?m)^[ \t]*الكتاب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")")_AR_FARA_RE = re.compile( r"(?m)^[ \t]*الفرع\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")")_FA_BAND_RE = re.compile(r"بند\s*[0-9۰-۹]+")_CJK_ZHANG_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*章")_KO_JANG_RE = re.compile(r"제\s*[0-9]+\s*장")_TA_ART_RE = re.compile(r"பிரிவு\s*[0-9௦-௯]+")_TE_ART_RE = re.compile(r"ప్రకరణ(?:ము)?\s*[0-9౦-౯]+")_KN_ART_RE = re.compile(r"ಪ್ರಕರಣ\s*[0-9೦-೯]+")_GU_ART_RE = re.compile(r"કલમ\s*[0-9૦-૯]+")_PA_ART_RE = re.compile(r"ਧਾਰਾ\s*[0-9੦-੯]+")_ML_ART_RE = re.compile(r"വകുപ്പ്\s*[0-9൦-൯]+")_CJK_BIAN_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[编編]")_KO_PYEON_RE = re.compile(r"제\s*[0-9]+\s*편")_TH_LAK_RE = re.compile(r"(?m)^[ \t]*ลักษณะ\s*[0-9๐-๙]+")_KM_CHAP_RE = re.compile(r"ជំពូក\s*[0-9០-៩]+")_LO_PART_RE = re.compile(r"ພາກ\s*[0-9໐-໙]+")_MY_CHAP_RE = re.compile(r"အခန်း\s*[0-9၀-၉]+")_KA_CHAP_RE = re.compile(r"თავი\s+[IVXLCDM0-9]+")_HY_CHAP_RE = re.compile(r"Գլուխ\s+[IVXLCDM0-9]+", re.IGNORECASE)_HY_BAZHIN_RE = re.compile(r"(?m)^[ \t]*Բաժին\s+[0-9]+", re.IGNORECASE)_HY_MAS_RE = re.compile(r"(?m)^[ \t]*Մաս\s+[IVXLCDM0-9]+", re.IGNORECASE)_AM_CHAP_RE = re.compile(r"ምዕራፍ\s*[0-9፩-፻]+")_HI_CHAP_RE = re.compile(r"���ध्याय\s*[0-9०-९]+")_BN_CHAP_RE = re.compile(r"অধ্যায়\s*[0-9০-৯]+")_UR_CHAP_RE = re.compile(r"باب\s*[0-9۰-۹]+")_FA_FASL_RE = re.compile(r"فصل\s*[0-9۰-۹]+")_NE_CHAP_RE = re.compile(r"परिच्छेद\s*[0-9०-९]+")_CJK_JIE_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[节節]")_KO_JEOL_RE = re.compile(r"제\s*[0-9]+\s*절")_TH_TON_RE = re.compile(r"(?m)^[ \t]*ตอน\s*[0-9๐-๙]+")_SR_PART_RE = re.compile(r"(?:Одељак|ОДЕЉАК)\s+[IVXLCDM0-9]+", re.IGNORECASE)_RU_TITLE_RE = re.compile( r"(?:Раздел|РАЗДЕЛ|Розділ|РОЗДІЛ|Раздзел|РАЗДЗЕЛ)\s+[IVXLCDM0-9]+", re.IGNORECASE,)_RU_CHAP_RE = re.compile(r"(?:Глава|ГЛАВА)\s+[IVXLCDM0-9]+", re.IGNORECASE)_TH_KO_RE = re.compile(r"(?m)^[ \t]*[กขคงจฉชซฌญ]\.")_HI_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[०-९]+\s*[.।]")_BN_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[০-৯]+\s*[.।]")_CYR_AB = "абвгдежзийк"_EL_AB = "αβγδεζηθικ"_KA_AB = "აბგდევზთიკლ"_HY_AB = "աբգդեզէըթժ"_CYR_AB_RE = re.compile(r"(?im)^[ \t]*[абвгдежзийк]\s*[).]")_EL_AB_RE = re.compile(r"(?im)^[ \t]*[αβγδεζηθικ]\s*[).]")_KA_AB_RE = re.compile(r"(?m)^[ \t]*[აბგდევზთიკლ]\s*[).]")_HY_AB_RE = re.compile(r"(?m)^[ \t]*[աբգդեզէըթժ]\s*[).]")_MARK_AFTER = r"(?:\s+|(?=[^\x00-\x7f]))"_LATIN_LETTER_RE = re.compile( r"(?m)^[ \t]*(?:\(\s*(?P<paren>[a-z])\s*\)|(?P<bare>[a-z])\)|" r"(?P<roman>viii|iii|vii|ii|iv|ix|vi|i|v|x)\.)" + _MARK_AFTER)_BULLET_RE = re.compile(r"(?m)^[ \t]*[•·●‣⁃*#]\s+")_DASH_NUM_RE = re.compile(r"(?m)^[ \t]*-\s*(?P<bn>[0-9]{1,3})\s+(?=[^\W\d_])")_LATIN_NUM_LIST_RE = re.compile( r"(?m)^[ \t]*(?:" r"\(\s*(?P<nparen>[0-9]{1,3})\s*\)|" r"(?P<nclose>[0-9]{1,3})\)|" r"(?P<nord>[0-9]{1,3})[º°o]|" r"(?P<ndot>[0-9]{1,3})\.-|" r"(?P<ncolon>[0-9]{1,3}):|" r"(?P<ndash>[0-9]{1,3})-|" r"(?P<dbl>([a-z])\2)\)" r")" + _MARK_AFTER)_ROMAN_LOWER = { "i": "1", "ii": "2", "iii": "3", "iv": "4", "x": "10", "v": "5", "vi": "6", "vii": "7", "viii": "8", "ix": "9",}_JA_KOU_RE = re.compile(r"第[0-9一二三四五六七八九十百]+項")_ZH_KUAN_RE = re.compile(r"第[一二三四五六七八九十百千万零〇两0-9]+款")_KO_ART_RE = re.compile(r"제\s*[0-9]+\s*조")_KO_HANG_RE = re.compile(r"제\s*[0-9]+\s*항")_KO_HO_RE = re.compile(r"제\s*[0-9]+\s*호")_TH_PARA_RE = re.compile(r"วรรค\s*[0-9๐-๙]+")_TH_KHO_RE = re.compile(r"(?m)^[ \t]*ข้อ\s*[0-9๐-๙]+")_TH_HUAT_RE = re.compile(r"(?m)^[ \t]*หมวด\s*[0-9๐-๙]+")_FA_TAB_RE = re.compile(r"تبصره\s*[0-9۰-۹]+")_HE_PARA_RE = re.compile(r"פסקה\s*[0-9]+")_AR_PARA_RE = re.compile(r"الفقرة\s*[0-9٠-٩]+")_AR_QARAR_RE = re.compile(r"قرار(?:\s*رقم)?\s*[0-9٠-٩]+")_AR_DECREE_RE = re.compile(r"(?:مرسوم|أمر)(?:\s*رقم)?\s*[0-9٠-٩]+")_RU_INST_RE = re.compile(r"(?:Указ|Постановление|Приказ)\s+[0-9]+", re.IGNORECASE)_KO_RANGE_RE = re.compile( r"제\s*[0-9]+\s*조\s*부터\s*제\s*[0-9]+\s*조(?:까지)?")_HE_ART_RE = re.compile( r"(?:סעיף\s*(?:[0-9]+|(?!קטן)[א-ת]{1,3}['׳]?)|\.\s*[0-9]+(?=[\u0590-\u05FF]))")_HE_KATAN_RE = re.compile(r"סעיף\s+קטן\s*\(?\s*[א-ת]'?\)?")_TH_ART_RE = re.compile(r"มาตรา\s*[0-9๐-๙]+")_HI_ART_RE = re.compile(r"(?:धारा|ধারা)\s*[0-9০-৯]+")_RU_ART_RE = re.compile(r"(?:Статья|СТАТЬЯ|Стаття|СТАТТЯ)\s+[0-9]+(?:-[0-9]+)?", re.IGNORECASE)_KA_ART_RE = re.compile(r"მუხლი\s*[0-9]+")_HY_ART_RE = re.compile(r"Հոդված\s*[0-9]+", re.IGNORECASE)_AM_ART_RE = re.compile(r"አንቀጽ\s*[0-9፩-፻]+")_BN_ART_RE = re.compile(r"ধারা\s*[0-9০-৯]+")_LO_ART_RE = re.compile(r"ມາດຕາ\s*[0-9໐-໙]+")_KM_ART_RE = re.compile(r"មាត្រា\s*[0-9០-៩]+")_MY_ART_RE = re.compile(r"ပုဒ်မ\s*[0-9၀-၉]+")_UZ_ART_RE = re.compile(r"[0-9]+\s*-\s*(?:модда|modda)", re.IGNORECASE)_MN_ART_RE = re.compile(r"[0-9]+\s*(?:дүгээр|дугаар)\s*зүйл", re.IGNORECASE)_KK_ART_RE = re.compile(r"[0-9]+\s*-?\s*бап", re.IGNORECASE)_NE_ART_RE = re.compile(r"दफा\s*[0-9०-९]+")_TI_ART_RE = re.compile(r"ዓንቀጽ\s*[0-9፩-፻]+")_BO_ART_RE = re.compile(r"དོན་ཚན་\s*[0-9༠-༩]+")_UG_ART_RE = re.compile(r"ماددا\s*[0-9۰-۹]+")_AR_POINT_RE = re.compile(r"(?m)^[ \t]*(?:أولا|ثانيا|ثالثا|رابعا|خامسا)\s*[:/]")_AR_POINT_NUM = (("أولا", "1"), ("ثانيا", "2"), ("ثالثا", "3"), ("رابعا", "4"), ("خامسا", "5"))_SI_ART_RE = re.compile(r"වගන්තිය\s*[0-9෦-෯]+")_UR_ART_RE = re.compile(r"دفعہ\s*[0-9۰-۹]+")_KY_ART_RE = re.compile(r"[0-9]+\s*-?\s*берене", re.IGNORECASE)_BE_ART_RE = re.compile(r"Артыкул\s*[0-9]+", re.IGNORECASE)
# "A R T Í C U L O 86" / "C A P I T U L O I" → ARTÍCULO 86 / CAPITULO I_SPACED_KEYWORD_RE = re.compile( r"(?iu)\b((?:[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ]\s+){3,}" r"[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ])\b" r"(?=\s*[.:\-–—]?\s*[0-9IVXLCDM])")
def _squeeze_spaced_keyword(match: re.Match[str]) -> str: return re.sub(r"\s+", "", match.group(1))
_ZW_RE = re.compile( r"[\ufeff\u200b\u200c\u200d\u00ad\u2060\u200e\u200f\u202a-\u202e\u2066-\u2069]")# Tashkeel, niqqud, Latin combining. Keep Thai/Lao/Khmer/Myanmar/Indic Mn._STRIP_MARKS_RE = re.compile( "[" "\u0300-\u036f" "\u0483-\u0489" "\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7" "\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06ed" "\u08d3-\u08e1\u08e3-\u08ff" "]")_SCRIPT_CITE_TAIL_RE = re.compile( r"(?i)^\s*(?:" r"من\s*(?:الدستور|القانون|الأمر|المرسوم|القرار)|" r"của\s+luật|" r"של\s+(?:חוק|פקודה)" r")")
# UTF-8 read as Latin-1: § (U+00C2 U+00A7) is §, é is é. Âmbito stays._LATIN1_UTF8_RE = re.compile(r"[\u00c2\u00c3][\u0080-\u00bf]")
def _repair_latin1_utf8(text: str) -> str: if "\u00c2" not in text and "\u00c3" not in text: return text
def repl(match: re.Match[str]) -> str: try: return match.group(0).encode("latin-1").decode("utf-8") except UnicodeDecodeError: return match.group(0)
return _LATIN1_UTF8_RE.sub(repl, text)
# Script-tagged gazettes that still publish English Article/Section translations._LATIN_FALLBACK_LANGS = frozenset( {"ka", "km", "hy", "am", "lo", "my", "si", "th", "he", "ne", "fa"})
class _HTMLText(HTMLParser): SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
def __init__(self) -> None: super().__init__(convert_charrefs=True) self.parts: list[str] = [] self.skip = 0
def handle_starttag(self, tag, attrs): if tag in self.SKIP: self.skip += 1 if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0: self.parts.append("\n")
def handle_endtag(self, tag): if tag in self.SKIP and self.skip: self.skip -= 1 if tag in {"p", "div", "li", "tr"} and self.skip == 0: self.parts.append("\n")
def handle_data(self, data): if self.skip == 0: self.parts.append(data)
def has_html_tags(text: str) -> bool: return bool(text and _HAS_TAG_RE.search(text))
def strip_html(raw: str) -> str: """Turn leftover HTML into visible legal text. No-op if there are no tags.""" if not raw or not _HAS_TAG_RE.search(raw): return raw parser = _HTMLText() try: parser.feed(raw) parser.close() text = "".join(parser.parts) except Exception: text = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw) text = re.sub(r"(?is)<style.*?>.*?</style>", " ", text) text = re.sub(r"(?is)<[^>]+>", " ", text) text = html_lib.unescape(text).replace("\xa0", " ") text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n[ \t]+", "\n", text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip()
_ROMAN_PAGE_RE = re.compile( r"(?i)(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3}|xiv|xv)$")
def _is_roman_page_line(line: str, nxt: str) -> bool: """A lone i/ii/iii between blocks is a page stamp, not a list item.""" if _ROMAN_PAGE_RE.fullmatch(line.strip()) is None: return False nxt = nxt.strip() if not nxt: return True return not (nxt[:1].islower() or nxt.startswith("("))
def _is_page_num_line(line: str) -> bool: token = line.strip() if 1 <= len(token) <= 4 and all(unicodedata.category(ch) == "Nd" for ch in token): return True # "1/3" between paragraphs is page 1 of 3, not a section. parts = token.split("/") if len(parts) == 2 and all(part.isascii() and part.isdigit() for part in parts): left, right = int(parts[0]), int(parts[1]) return 1 <= left <= right <= 30 return False
def _is_facing_page_line(line: str) -> bool: """'736 737' between blocks is a two-page spread, not a citation.""" parts = line.split() if len(parts) != 2 or not all(part.isascii() and part.isdigit() for part in parts): return False left, right = int(parts[0]), int(parts[1]) return 100 <= left and right == left + 1 and right <= 9999
_PAGE_OF_RE = re.compile(r"(?i)(\d{1,2})\s+of\s+(\d{1,2})")
def _is_page_of_line(line: str) -> bool: """'3 of 5' between blocks is a page count, not a citation.""" match = _PAGE_OF_RE.fullmatch(line.strip()) if match is None: return False left, right = int(match.group(1)), int(match.group(2)) return 1 <= left <= right <= 30
def learned_patterns_path() -> Path: override = os.environ.get("COUNTRY_LAWS_LEARNED_PATTERNS") if override: return Path(override) return Path(__file__).resolve().parent / "data" / "learned_line_patterns.json"
_LEARNED: tuple[float, re.Pattern[str] | None] | None = None
def learned_line_pattern() -> re.Pattern[str] | None: """Whole-line rules added by the normalize loop. Compiled once per file change.""" global _LEARNED path = learned_patterns_path() if not path.is_file(): return None mtime = path.stat().st_mtime if _LEARNED is not None and _LEARNED[0] == mtime: return _LEARNED[1] try: payload = json.loads(path.read_text(encoding="utf-8")) except (OSError, json.JSONDecodeError): _LEARNED = (mtime, None) return None parts: list[str] = [] for item in payload.get("patterns") or []: if not isinstance(item, str): continue try: re.compile(item, re.IGNORECASE) except re.error: continue parts.append(item) compiled = re.compile("|".join(f"(?:{part})" for part in parts), re.IGNORECASE) if parts else None _LEARNED = (mtime, compiled) return compiled
def strip_chrome_lines(text: str) -> str: """Drop gazette-site chrome lines. Never invents replacement legal text.""" if not text: return "" raw_lines = text.splitlines() multi = sum(1 for ln in raw_lines if ln.strip()) > 1 learned = learned_line_pattern() # Index of the next non-empty line. Slicing the tail on every line is # quadratic and stalls multi-megabyte statutes. count = len(raw_lines) next_nonempty = [count] * count nxt_i = count for idx in range(count - 1, -1, -1): next_nonempty[idx] = nxt_i if raw_lines[idx].strip(): nxt_i = idx kept = [] for idx, ln in enumerate(raw_lines): stripped = ln.strip() if not stripped: continue # The chrome expression is superlinear on multi-megabyte lines. # Gazette chrome that it removes is a short line. A longer line is # kept, which does not drop statute text. if len(stripped) <= 400 and ( _CHROME_LINE_RE.match(stripped) or _CHROME_INLINE_RE.search(ln) ): continue if len(stripped) > 400 and _CHROME_INLINE_RE.search(stripped[:200]): continue if learned is not None and len(stripped) <= 400 and learned.match(stripped): continue # A lone "2" or "10" is an article number. The same token inside a # longer page is a page stamp. if multi and ( _is_page_num_line(stripped) or _is_facing_page_line(stripped) or _is_page_of_line(stripped) ): continue nxt = "" nxt_at = next_nonempty[idx] if nxt_at < count: nxt = raw_lines[nxt_at] if multi and _is_roman_page_line(stripped, nxt): continue kept.append(ln) return "\n".join(kept).strip()
_HYPHEN_BREAK_RE = re.compile(r"(?<=[^\W\d_])-[ \t]*\n+[ \t]*([^\W\d_])")
def _join_hyphen_breaks(text: str) -> str: """Join a hyphenated word split across lines. Leave a following capital header."""
def repl(match: re.Match[str]) -> str: nxt = match.group(1) if nxt.isupper(): return match.group(0) return nxt
return _HYPHEN_BREAK_RE.sub(repl, text)
def normalize_legal_text(value: Any) -> str: """NFKC + HTML strip. Keeps newlines so heading detection still works.""" if value is None: return "" text = unicodedata.normalize("NFKC", str(value)).replace("\x00", "") if text.startswith("ÿþ") or text.startswith("þÿ"): text = text[2:] text = re.sub(r"[\x00-\x08\x0b\x0e-\x1f\x7f]", " ", text) text = text.replace("\ufffd", " ") text = re.sub(r"[\ue000-\uf8ff]", "", text) text = _repair_latin1_utf8(text) text = re.sub(r"\(cid:\d+\)", " ", text) text = _ZW_RE.sub("", text).replace("ـ", "") text = _STRIP_MARKS_RE.sub("", text) text = re.sub(r"[\u2010-\u2015\u2212\ufe58\ufe63\uff0d]", "-", text) text = re.sub(r"[\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]", " ", text) text = text.replace("\u2028", "\n").replace("\u2029", "\n").replace("\f", "\n") text = _join_hyphen_breaks(text) text = _NUMERO_FOLD_RE.sub("nr. ", text) text = re.sub(r"المادة\s*-\s*اختر\s*-\s*", "", text) text = re.sub(r"(?m)^[ \t]*©+\s*", "", text) text = re.sub(r"\b((?:19|20)\d{2}) \1\b", r"\1", text) text = re.sub(r"(?<=[A-Za-z])!+(?=\d)", " ", text) text = re.sub(r":!+", ":", text) text = re.sub(r"(?m)!+\s*$", "", text) text = _SPACED_KEYWORD_RE.sub(_squeeze_spaced_keyword, text) text = re.sub(r"(?s)<!--.*?-->", " ", text) text = strip_html(text) text = html_lib.unescape(text).replace("\xa0", " ") text = re.sub(r"_{3,}", " ", text) text = re.sub(r"\.{4,}", " ", text) text = re.sub(r"(?m)^[ \t]*#{1,6}[ \t]+", "", text) text = strip_chrome_lines(text) text = text.replace("\xa0", " ") text = re.sub(r"~\$\S{0,16}", " ", text) text = re.sub(r"\*\*([^*]{1,80})\*\*", r"\1", text) text = re.sub(r"__([^_]{1,80})__", r"\1", text) text = re.sub(r"'{3}([^']{1,80})'{3}", r"\1", text) text = re.sub(r"^={2,6}\s*(.+?)\s*={2,6}\s*$", r"\1", text, flags=re.MULTILINE) text = re.sub(r"[ \t]+", " ", text) text = re.sub(r"\n[ \t]+", "\n", text) text = re.sub(r"[ \t]+\n", "\n", text) text = _join_hyphen_breaks(text) text = re.sub(r"\n{3,}", "\n\n", text) return text.strip()
@dataclassclass StructureUnit: kind: str number: str heading: str body: str title_number: str = "" chapter_number: str = "" part_number: str = "" article_number: str = "" section_number: str = "" subsections: tuple[str, ...] = () hierarchy_path: str = "" char_start: int = 0 char_end: int = 0
def to_dict(self) -> dict[str, Any]: return { "kind": self.kind, "number": self.number, "heading": self.heading, "body": self.body, "title_number": self.title_number, "chapter_number": self.chapter_number, "part_number": self.part_number, "article_number": self.article_number, "section_number": self.section_number, "subsections": list(self.subsections), "hierarchy_path": self.hierarchy_path, "char_start": self.char_start, "char_end": self.char_end, }
def _cursor_path(cursor: dict[str, str]) -> str: parts = [] for key, label in ( ("title", "Title"), ("chapter", "Chapter"), ("part", "Part"), ("article", "Article"), ("section", "Section"), ): value = cursor.get(key) or "" if value: parts.append(f"{label} {value}") return " > ".join(parts)
def _subsection_tokens(text: str) -> tuple[str, ...]: seen: list[str] = [] for match in _SUBSECTION_RE.finditer(text): token = match.group(1) if token not in seen: seen.append(token) if len(seen) >= 40: break return tuple(seen)
def check_exclusive_cover(text: str, units: list[StructureUnit]) -> bool: """True iff units are contiguous, non-overlapping, and cover *text* exactly.""" if not units: return not text ordered = sorted(units, key=lambda u: u.char_start) if ordered[0].char_start != 0 or ordered[-1].char_end != len(text): return False prev = 0 for unit in ordered: if unit.char_start != prev or unit.char_end < unit.char_start: return False if text[unit.char_start : unit.char_end] != unit.body: return False prev = unit.char_end return True
def _script_regex(language: str): from .profiles import iso_lang
lang = iso_lang(language) if lang in {"zh", "zh-cn", "zh-tw"}: return _ZH_ART_RE if lang == "ar": return _AR_ART_RE if lang == "fa": return _FA_ART_RE if lang == "ja": return _JA_ART_RE if lang == "ko": return _KO_ART_RE if lang == "he": return _HE_ART_RE if lang == "th": return _TH_ART_RE if lang == "hi": return _HI_ART_RE if lang == "bn": return _BN_ART_RE if lang in {"ru", "uk", "be"}: return _RU_ART_RE if lang == "ka": return _KA_ART_RE if lang == "hy": return _HY_ART_RE if lang == "am": return _AM_ART_RE if lang == "ti": return _TI_ART_RE if lang == "bo": return _BO_ART_RE if lang == "ug": return _UG_ART_RE if lang == "lo": return _LO_ART_RE if lang == "km": return _KM_ART_RE if lang == "my": return _MY_ART_RE if lang == "uz": return _UZ_ART_RE if lang == "mn": return _MN_ART_RE if lang == "kk": return _KK_ART_RE if lang == "ne": return _NE_ART_RE if lang == "si": return _SI_ART_RE if lang == "ta": return _TA_ART_RE if lang == "te": return _TE_ART_RE if lang == "kn": return _KN_ART_RE if lang == "gu": return _GU_ART_RE if lang == "pa": return _PA_ART_RE if lang == "ml": return _ML_ART_RE if lang == "ur": return _UR_ART_RE if lang == "ky": return _KY_ART_RE if lang == "be": return _BE_ART_RE return None
def _detected_script_regexes(text: str, language: str) -> list: found: list = [] primary = _script_regex(language) if primary is not None: found.append(primary) if re.search(r"[①-⑳⑴-⒇❶-❿⓫-⓴]", text): found.append(_CIRCLED_ART_RE) if re.search(r"[\u4e00-\u9fff]", text): found.extend((_ZH_ART_RE, _JA_ART_RE, _ZH_KUAN_RE, _JA_KOU_RE, _CJK_ZHANG_RE, _CJK_BIAN_RE, _CJK_JIE_RE, _CJK_ENUM_RE, _CJK_PAREN_RE, _CJK_DIGIT_ENUM_RE)) if re.search(r"[\uac00-\ud7af]", text): found.extend((_KO_ART_RE, _KO_HANG_RE, _KO_HO_RE, _KO_GA_RE, _KO_JANG_RE, _KO_PYEON_RE, _KO_JEOL_RE)) if re.search(r"[\u30a0-\u30ff]", text): found.append(_JA_KATA_ENUM_RE) if re.search(r"[\u0600-\u06ff]", text): found.extend(( _AR_ART_RE, _FA_ART_RE, _FA_TAB_RE, _FA_BAND_RE, _FA_FASL_RE, _AR_PARA_RE, _AR_QARAR_RE, _AR_DECREE_RE, _AR_ABJAD_RE, _AR_ANNEX_RE, _AR_BAB_RE, _AR_FASL_RE, _AR_QISM_RE, _AR_KITAB_RE, _AR_FARA_RE, _UR_CHAP_RE, _UG_ART_RE, _AR_POINT_RE, )) if re.search(r"[\u0590-\u05ff]", text): found.extend(( _HE_ART_RE, _HE_PARA_RE, _HE_ALEF_RE, _HE_PEREK_RE, _HE_SIMAN_RE, _HE_HELEK_RE, _HE_TOS_RE, _HE_TAKANA_RE, _HE_KATAN_RE, )) if re.search(r"[\u0e00-\u0e7f]", text): found.extend((_TH_ART_RE, _TH_PARA_RE, _TH_KO_RE, _TH_KHO_RE, _TH_HUAT_RE, _TH_LAK_RE, _TH_TON_RE)) if re.search(r"[\u0900-\u097f]", text): found.extend((_HI_ART_RE, _HI_DIGIT_ENUM_RE, _HI_CHAP_RE, _NE_CHAP_RE)) if re.search(r"[\u0980-\u09ff]", text): found.extend((_BN_ART_RE, _BN_DIGIT_ENUM_RE, _BN_CHAP_RE)) if re.search(r"[\u0b80-\u0bff]", text): found.append(_TA_ART_RE) if re.search(r"[\u0c00-\u0c7f]", text): found.append(_TE_ART_RE) if re.search(r"[\u0c80-\u0cff]", text): found.append(_KN_ART_RE) if re.search(r"[\u0a80-\u0aff]", text): found.append(_GU_ART_RE) if re.search(r"[\u0a00-\u0a7f]", text): found.append(_PA_ART_RE) if re.search(r"[\u0d00-\u0d7f]", text): found.append(_ML_ART_RE) if re.search(r"[\u0e80-\u0eff]", text): found.extend((_LO_ART_RE, _LO_PART_RE)) if re.search(r"[\u1780-\u17ff]", text): found.extend((_KM_ART_RE, _KM_CHAP_RE)) if re.search(r"[\u1000-\u109f]", text): found.extend((_MY_ART_RE, _MY_CHAP_RE)) if re.search(r"[\u1200-\u137f]", text): found.extend((_AM_ART_RE, _AM_CHAP_RE, _TI_ART_RE)) if re.search(r"[\u0f00-\u0fff]", text): found.append(_BO_ART_RE) if re.search(r"[\u10a0-\u10ff]", text): found.extend((_KA_ART_RE, _KA_AB_RE, _KA_CHAP_RE)) if re.search(r"[\u0530-\u058f]", text): found.extend((_HY_ART_RE, _HY_AB_RE, _HY_CHAP_RE, _HY_BAZHIN_RE, _HY_MAS_RE)) if re.search(r"[\u0400-\u04ff]", text): found.extend((_CYR_AB_RE, _RU_TITLE_RE, _RU_CHAP_RE, _SR_PART_RE)) if re.search(r"[\u0370-\u03ff]", text): found.append(_EL_AB_RE) if "модда" in text.casefold() or re.search(r"\bmodda\b", text, re.IGNORECASE): found.append(_UZ_ART_RE) if re.search(r"зүйл", text, re.IGNORECASE): found.append(_MN_ART_RE) if re.search(r"бап", text, re.IGNORECASE): found.append(_KK_ART_RE) if "दफा" in text: found.append(_NE_ART_RE) if "परिच्छेद" in text: found.append(_NE_CHAP_RE) if "වගන්තිය" in text: found.append(_SI_ART_RE) if "دفعہ" in text: found.append(_UR_ART_RE) if re.search(r"берене", text, re.IGNORECASE): found.append(_KY_ART_RE) if re.search(r"артыкул", text, re.IGNORECASE): found.append(_BE_ART_RE) if re.search(r"статья|стаття", text, re.IGNORECASE): found.append(_RU_ART_RE) if re.search(r"указ|постановление|приказ", text, re.IGNORECASE): found.append(_RU_INST_RE) # Preserve order, drop duplicate pattern objects. out: list = [] seen: set[int] = set() for regex in found: key = id(regex) if key not in seen: seen.add(key) out.append(regex) return out
def _lexicon_heading_re() -> re.Pattern[str]: """Heading matcher generated from HEADING_LEXICON so new languages are data.""" global _LEXICON_HEADING_RE, _LEXICON_KIND if _LEXICON_HEADING_RE is not None: return _LEXICON_HEADING_RE from .profiles import HEADING_LEXICON
words: list[str] = [] kinds: dict[str, str] = {} for token, hits in HEADING_LEXICON.items(): token = (token or "").strip() if len(token) < 2: continue kinds_found = [kind for kind, _lang in hits if kind in {"article", "section", "title", "chapter", "part"}] if not kinds_found: continue folded = _latin_fold(token) words.append(folded) kinds[folded.casefold()] = kinds_found[0] words.sort(key=len, reverse=True) escaped = [re.escape(w) for w in words] _LEXICON_HEADING_RE = re.compile( _latin_fold( r"(?im)" + _HEADING_START + r"(?:l['’])?(?P<lex>" + "|".join(escaped) + r")(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*(?P<lex_n>" + _ARTICLE_N + r")\)?" ) ) _LEXICON_KIND = kinds return _LEXICON_HEADING_RE
def _plausible_cw_number(raw: str) -> bool: """Drop year-like '1902. Amendment' titles from keyword-less numbering.""" digits = re.sub(r"\D", "", raw or "") if not digits: return False value = int(digits) if value <= 0 or value > 2000: return False if 1800 <= value <= 2099: return False return True
def _fold_digits_in_number(raw: str) -> str: """Map Nd digits (١, १, ๑, …) to ASCII so retrieval numbers stay decimal.""" if not raw: return raw out: list[str] = [] changed = False for ch in raw: if unicodedata.category(ch) == "Nd": digit = unicodedata.digit(ch) if digit is not None: mapped = str(digit) out.append(mapped) if mapped != ch: changed = True continue out.append(ch) return "".join(out) if changed else raw
def _unicode_digit_runs(text: str) -> list[str]: """ASCII-fold Nd runs (Thai ๑, Myanmar ၁, Arabic-Indic, …).""" runs: list[str] = [] cur: list[str] = [] for char in text: if unicodedata.category(char) == "Nd": cur.append(str(unicodedata.digit(char))) elif cur: runs.append("".join(cur)) cur = [] if cur: runs.append("".join(cur)) return runs
_AR_ORDINAL_NUM = ( ("الحادية عشرة", "11"), ("الثانية عشرة", "12"), ("الثالثة عشرة", "13"), ("الرابعة عشرة", "14"), ("الخامسة عشرة", "15"), ("السادسة عشرة", "16"), ("السابعة عشرة", "17"), ("الثامنة عشرة", "18"), ("التاسعة عشرة", "19"), ("الحادية والعشرون", "21"), ("الثانية والعشرون", "22"), ("الثالثة والعشرون", "23"), ("الرابعة والعشرون", "24"), ("الخامسة والعشرون", "25"), ("السادسة والعشرون", "26"), ("السابعة والعشرون", "27"), ("الثامنة والعشرون", "28"), ("التاسعة والعشرون", "29"), ("العشرون", "20"), ("الأولى", "1"), ("الأولي", "1"), ("األولى", "1"), ("الاولى", "1"), ("الثانية", "2"), ("الثالثة", "3"), ("الرابعة", "4"), ("الخامسة", "5"), ("السادسة", "6"), ("السابعة", "7"), ("الثامنة", "8"), ("التاسعة", "9"), ("العاشرة", "10"), ("الأول", "1"), ("الاول", "1"), ("الثاني", "2"), ("الثالث", "3"), ("الرابع", "4"), ("الخامس", "5"), ("السادس", "6"), ("السابع", "7"), ("الثامن", "8"), ("التاسع", "9"), ("العاشر", "10"),)_HE_VALUES = { "א": 1, "ב": 2, "ג": 3, "ד": 4, "ה": 5, "ו": 6, "ז": 7, "ח": 8, "ט": 9, "י": 10, "כ": 20, "ך": 20, "ל": 30, "מ": 40, "ם": 40, "נ": 50, "ן": 50, "ס": 60, "ע": 70, "פ": 80, "ף": 80, "צ": 90, "ץ": 90, "ק": 100, "ר": 200, "ש": 300, "ת": 400,}_HE_ORDINAL_NUM = ( ("ראשונה", "1"), ("שנייה", "2"), ("שניה", "2"), ("שלישית", "3"), ("רביעית", "4"), ("חמישית", "5"), ("שישית", "6"),)_ETH_VALUES = { "፩": 1, "፪": 2, "፫": 3, "፬": 4, "፭": 5, "፮": 6, "፯": 7, "፰": 8, "፱": 9, "፲": 10, "፳": 20, "፴": 30, "፵": 40, "፶": 50, "፷": 60, "፸": 70, "፹": 80, "፺": 90, "፻": 100, "፼": 10000,}_FA_ORDINAL_NUM = ( ("دوازدهم", "12"), ("سیزدهم", "13"), ("چهاردهم", "14"), ("پانزدهم", "15"), ("شانزدهم", "16"), ("هفدهم", "17"), ("هجدهم", "18"), ("نوزدهم", "19"), ("یازدهم", "11"), ("بیستم", "20"), ("چهارم", "4"), ("چارم", "4"), ("جارم", "4"), ("پنجم", "5"), ("ششم", "6"), ("هفتم", "7"), ("هشتم", "8"), ("نهم", "9"), ("دهم", "10"), ("سوم", "3"), ("دوم", "2"), ("اولی", "1"), ("اول", "1"), ("نخست", "1"),)_CJK_DIGIT = { "零": 0, "〇": 0, "一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9,}
def _cjk_numeral_value(text: str) -> str | None: body = re.sub(r"[第条條項款章编編节節之조항호편절、]", "", text) if not body or not all(ch in _CJK_DIGIT or ch == "十" or ch == "百" for ch in body): return None if body == "十": return "10" if body.startswith("十"): return str(10 + _CJK_DIGIT.get(body[1], 0)) if "百" in body: left, right = body.split("百", 1) if not left: hundreds = 100 elif left in _CJK_DIGIT: hundreds = _CJK_DIGIT[left] * 100 else: return None if not right: return str(hundreds) rest = _cjk_numeral_value(right) if rest is None: return None return str(hundreds + int(rest)) if "十" in body: left, right = body.split("十", 1) tens = _CJK_DIGIT.get(left, 0) * 10 ones = _CJK_DIGIT.get(right, 0) if right else 0 return str(tens + ones) if body in _CJK_DIGIT: return str(_CJK_DIGIT[body]) return None
def _circled_to_int(char: str) -> str | None: if not char: return None code = ord(char[0]) if 0x2460 <= code <= 0x2473: return str(code - 0x2460 + 1) if 0x2474 <= code <= 0x2487: return str(code - 0x2474 + 1) if 0x2488 <= code <= 0x249B: return str(code - 0x2488 + 1) if 0x2776 <= code <= 0x277F: return str(code - 0x2776 + 1) if 0x24EB <= code <= 0x24F4: return str(code - 0x24EB + 11) return None
def _ethiopic_numeral_value(text: str) -> str | None: chars = [ch for ch in text if ch in _ETH_VALUES] if not chars: return None body = "".join(chars) if "፼" in body: left, right = body.split("፼", 1) mul = _ethiopic_numeral_value(left) if left else "1" rest = _ethiopic_numeral_value(right) if right else "0" if mul is None or rest is None: return None return str(int(mul) * 10000 + int(rest)) if "፻" in body: left, right = body.split("፻", 1) mul = sum(_ETH_VALUES[ch] for ch in left) if left else 1 rest = sum(_ETH_VALUES[ch] for ch in right) return str(mul * 100 + rest) return str(sum(_ETH_VALUES[ch] for ch in chars))
def _hebrew_letter_num(raw: str) -> str | None: """Map פרק א' / תוספת שניה / סעיף יא to decimal. Long Hebrew words stay unmapped.""" cleaned = re.sub(r"['׳״\"`]", "", raw) for word, num in _HE_ORDINAL_NUM: if word in cleaned: return num katan = re.search(r"סעיף\s+קטן\s*\(?\s*([א-ת])", cleaned) if katan: ch = katan.group(1) return str(_HE_VALUES[ch]) if ch in _HE_VALUES else ch match = re.search(r"(?:פרק|סימן|חלק|תוספת|סעיף)\s*(?!קטן)([א-ת]{1,3})", cleaned) if not match: return None total = sum(_HE_VALUES.get(ch, 0) for ch in match.group(1)) return str(total) if total else None
def _script_hit_kind(regex: re.Pattern[str]) -> str: if regex is _RU_TITLE_RE or regex is _TH_LAK_RE: return "title" if regex in ( _HE_PEREK_RE, _AR_BAB_RE, _TH_HUAT_RE, _CJK_ZHANG_RE, _KO_JANG_RE, _RU_CHAP_RE, _KM_CHAP_RE, _MY_CHAP_RE, _KA_CHAP_RE, _HY_CHAP_RE, _AM_CHAP_RE, _HI_CHAP_RE, _BN_CHAP_RE, _UR_CHAP_RE, _FA_FASL_RE, _NE_CHAP_RE, ): return "chapter" if regex in (_HE_HELEK_RE, _AR_KITAB_RE, _CJK_BIAN_RE, _KO_PYEON_RE, _LO_PART_RE, _SR_PART_RE, _HY_MAS_RE): return "part" if regex in ( _HE_SIMAN_RE, _HE_TOS_RE, _HE_TAKANA_RE, _HE_PARA_RE, _HE_KATAN_RE, _AR_ANNEX_RE, _AR_PARA_RE, _AR_FASL_RE, _AR_QISM_RE, _AR_FARA_RE, _HY_BAZHIN_RE, _JA_KOU_RE, _ZH_KUAN_RE, _KO_HANG_RE, _KO_HO_RE, _TH_PARA_RE, _TH_KHO_RE, _TH_TON_RE, _FA_TAB_RE, _FA_BAND_RE, _AR_POINT_RE, _CJK_JIE_RE, _KO_JEOL_RE, ): return "section" return "article"
def _script_article_number(raw: str) -> str: stripped = raw.strip() for word, num in _AR_POINT_NUM: if stripped.startswith(word): return num compact = raw.strip().strip("()[] \t\u3001\uff08\uff09.、-–—") circled = _circled_to_int(compact) if circled: return circled if compact and len(compact) <= 3: first = compact[0] if first in _HANGUL_GA: return str(_HANGUL_GA.index(first) + 1) if first in _KATA_ENUM: return str(_KATA_ENUM.index(first) + 1) if first in _AR_ABJAD_INDEX: return _AR_ABJAD_INDEX[first] if first in _HE_ALEF: return str(_HE_ALEF.index(first) + 1) if first in _TH_KO: return str(_TH_KO.index(first) + 1) low = first.casefold() if low in _CYR_AB: return str(_CYR_AB.index(low) + 1) if low in _EL_AB: return str(_EL_AB.index(low) + 1) if first in _KA_AB: return str(_KA_AB.index(first) + 1) if first in _HY_AB: return str(_HY_AB.index(first) + 1) cjk_early = _cjk_numeral_value(compact) if cjk_early: return cjk_early he = _hebrew_letter_num(raw) if he: return he digits = _unicode_digit_runs(raw) if digits: if len(digits) >= 2 and re.search(r"[0-9٠-٩۰-۹]+-[0-9٠-٩۰-۹]+", raw): return "-".join(digits[:2]) return digits[0] eth = _ethiopic_numeral_value(raw) if eth: return eth compact = re.sub(r"[\s\u0640]+", "", raw) for word, num in _AR_ORDINAL_NUM + _FA_ORDINAL_NUM: needle = re.sub(r"[\s\u0640]+", "", word) if needle and needle in compact: return num cjk = _cjk_numeral_value(compact) if cjk: return cjk tail = re.search(r"([0-9٠-٩۰-۹]+|[IVXLCDM]{1,8})$", compact) if tail: return tail.group(1) return compact
def _in_range_boilerplate(text: str, start: int) -> bool: for regex in (_KO_RANGE_RE, _CJK_RANGE_RE): for match in regex.finditer(text): if match.start() <= start < match.end(): return True return False
def _kind_number_from_heading_match(match: re.Match) -> tuple[str, str]: for name in ("title", "chapter", "part", "article", "section"): if match.group(name): return name, (match.group(f"{name}_n") or "").strip() if match.group("section_sym"): return "section", (match.group("section_sym_n") or "").strip() if match.group("section_pre"): return "section", (match.group("section_pre_n") or "").strip() if match.group("grein"): return "article", (match.group("grein_n") or "").strip() if match.group("straipsnis"): return "article", (match.group("straipsnis_n") or "").strip() if match.group("artikulua"): return "article", (match.group("artikulua_n") or "").strip() if match.group("ledd"): return "section", (match.group("ledd_n") or "").strip() if match.group("kap"): return "chapter", (match.group("kap_n") or "").strip() if match.group("luku"): return "chapter", (match.group("luku_n") or "").strip() if match.group("fejezet"): return "chapter", (match.group("fejezet_n") or "").strip() if match.group("peatukk"): return "chapter", (match.group("peatukk_n") or "").strip() if match.group("skyrius"): return "chapter", (match.group("skyrius_n") or "").strip() if match.group("nodala"): return "chapter", (match.group("nodala_n") or "").strip() if match.group("kafli"): return "chapter", (match.group("kafli_n") or "").strip() if match.group("bob"): return "chapter", (match.group("bob_n") or "").strip() if match.group("tarau"): return "chapter", (match.group("tarau_n") or "").strip() if match.group("bolum"): return "chapter", (match.group("bolum_n") or "").strip() if match.group("modda"): return "article", (match.group("modda_n") or "").strip() if match.group("mn"): return "article", (match.group("mn_n") or "").strip() if match.group("kk"): return "article", (match.group("kk_n") or "").strip() if match.group("disp"): return "article", (match.group("disp_n") or "").strip() if match.group("mom"): return "section", (match.group("mom_n") or "").strip() if match.group("order"): return "section", (match.group("order_n") or "").strip() if match.group("kidogo"): return "section", (match.group("kidogo_n") or "").strip() if match.group("esresol"): word = _latin_fold(match.group("esresol") or "").casefold() return "section", { "primero": "1", "segundo": "2", "tercero": "3", "cuarto": "4", "quinto": "5", "sexto": "6", "septimo": "7", "octavo": "8", "noveno": "9", "decimo": "10", "erstens": "1", "zweitens": "2", "drittens": "3", "viertens": "4", "funftens": "5", "premierement": "1", "deuxiemement": "2", "troisiemement": "3", "quatriemement": "4", "cinquiemement": "5", }.get(word, word) return "", ""
@dataclassclass _Hit: start: int kind: str number: str heading: str
_PAREN_XREF_RE = re.compile( r"(?i)^\s*(?:\([a-z0-9]{1,4}\))?\s+" r"(?:is|are|or|and|of|have|has|was|were|by|to|for|from|in|that|shall)\b")
def _paren_letter_xref(raw: str, number: str, rest: str) -> bool: """Skip 'paragraph (i) or …' / 'subsection (l)(b) is …' cross-references.""" if len(number) != 1 or not number.isalpha() or "(" not in raw: return False return _PAREN_XREF_RE.match(rest) is not None
def _collect_hits(text: str, *, language: str, latin: bool) -> list[_Hit]: hits: list[_Hit] = [] folded = _latin_fold(text) if latin else text if latin: for match in _HEADING_RE.finditer(folded): kind, number = _kind_number_from_heading_match(match) if not kind: continue if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]): continue if _paren_letter_xref(match.group(0), number, folded[match.end() : match.end() + 48]): continue for gname in ( "title_n", "chapter_n", "part_n", "article_n", "section_n", "section_sym_n", "section_pre_n", "grein_n", "straipsnis_n", "artikulua_n", "ledd_n", "kap_n", "luku_n", "fejezet_n", "peatukk_n", "skyrius_n", "nodala_n", "kafli_n", "bob_n", "tarau_n", "bolum_n", "modda_n", "mn_n", "kk_n", "mom_n", "order_n", "kidogo_n", "disp_n", ): try: start, end = match.span(gname) except IndexError: continue if start >= 0: number = text[start:end] break number = _fold_digits_in_number(number.strip().rstrip(".-:–—")) line_end = text.find("\n", match.start()) if line_end < 0: line_end = len(text) heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] hits.append(_Hit(match.start(), kind, number, heading)) for match in _lexicon_heading_re().finditer(folded): if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]): continue token = (match.group("lex") or "").casefold() kind = _LEXICON_KIND.get(token, "article") start, end = match.span("lex_n") number = _fold_digits_in_number( (text[start:end] if start >= 0 else match.group("lex_n") or "").strip().rstrip(".-:–—") ) if not number: continue line_end = text.find("\n", match.start()) if line_end < 0: line_end = len(text) heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] hits.append(_Hit(match.start(), kind, number, heading)) for match in _LATIN_LETTER_RE.finditer(text): letter = match.group("paren") or match.group("bare") if letter: number = str(ord(letter) - 96) else: number = _ROMAN_LOWER.get(match.group("roman") or "", "") if not number: continue line_end = text.find("\n", match.start()) if line_end < 0: line_end = len(text) heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] hits.append(_Hit(match.start(), "section", number, heading)) for match in _LATIN_NUM_LIST_RE.finditer(text): number = ( match.group("nparen") or match.group("nclose") or match.group("nord") or match.group("ndot") or match.group("ncolon") or match.group("ndash") or "" ) dbl = match.group("dbl") if dbl: number = str(ord(dbl[0]) - 96) if not number: continue line_end = text.find("\n", match.start()) if line_end < 0: line_end = len(text) heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] hits.append(_Hit(match.start(), "section", number, heading)) for i, match in enumerate(_BULLET_RE.finditer(text), start=1): line_end = text.find("\n", match.start()) if line_end < 0: line_end = len(text) heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] hits.append(_Hit(match.start(), "section", str(i), heading)) for match in _DASH_NUM_RE.finditer(text): number = (match.group("bn") or "").strip() if not number: continue line_end = text.find("\n", match.start()) if line_end < 0: line_end = len(text) heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] hits.append(_Hit(match.start(), "section", number, heading)) for regex in _detected_script_regexes(text, language): for match in regex.finditer(text): if _in_range_boilerplate(text, match.start()): continue if _SCRIPT_CITE_TAIL_RE.match(text[match.end() : match.end() + 48]): continue raw = match.group(0) number = _fold_digits_in_number(_script_article_number(raw)) heading = re.sub(r"\s+", " ", raw).strip()[:240] hits.append(_Hit(match.start(), _script_hit_kind(regex), number, heading)) if latin: from .profiles import iso_lang
for match in _MARGINAL_NOTE_RE.finditer(text): word = _latin_fold(match.group("marginal") or "").casefold().rstrip(".") if not word or word in _MARGINAL_STOP: continue number = _fold_digits_in_number((match.group("marginal_n") or "").strip()) if not number: continue line_end = text.find("\n", match.start()) if line_end < 0: line_end = len(text) heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240] hits.append(_Hit(match.start(), "section", number, heading)) lang = iso_lang(language) keyword_hits = [ hit for hit in hits if hit.kind in {"article", "section"} and not _PAREN_SUBSECTION_RE.match(hit.heading.lstrip()) ] if len(keyword_hits) < MIN_SPLIT_HEADINGS and lang in _CW_NUM_LANGS: for match in _CW_NUM_RE.finditer(text): number = (match.group("cw_n") or "").strip() if not _plausible_cw_number(number): continue if _MONTH_START_RE.match(text[match.end() : match.end() + 16]): continue hits.append( _Hit( match.start(), "section", number, match.group(0).strip()[:240], ) ) hits.sort(key=lambda h: (h.start, -len(h.heading))) merged: list[_Hit] = [] seen_starts: set[int] = set() for hit in hits: if hit.start in seen_starts: continue seen_starts.add(hit.start) merged.append(hit) return _drop_parenthetical_subsections(merged)
def _drop_parenthetical_subsections(hits: list[_Hit]) -> list[_Hit]: """Keep ``(1)`` on the parent clause when a real section heading exists."""
parents = [ hit for hit in hits if hit.kind in {"article", "section"} and not _PAREN_SUBSECTION_RE.match(hit.heading.lstrip()) ] if not parents: return hits return [ hit for hit in hits if not (hit.kind == "section" and _PAREN_SUBSECTION_RE.match(hit.heading.lstrip())) ]
def _units_from_hits(text: str, hits: list[_Hit]) -> list[StructureUnit]: if not hits: return [ StructureUnit(kind="preamble", number="", heading="", body=text, char_start=0, char_end=len(text)) ] cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""} units: list[StructureUnit] = [] if hits[0].start > 0: units.append( StructureUnit( kind="preamble", number="", heading="", body=text[0 : hits[0].start], char_start=0, char_end=hits[0].start, ) ) for i, hit in enumerate(hits): start = hit.start end = hits[i + 1].start if i + 1 < len(hits) else len(text) body = text[start:end] cursor[hit.kind] = hit.number for lower, rank in _KIND_RANK.items(): if rank > _KIND_RANK.get(hit.kind, 99): cursor[lower] = "" units.append( StructureUnit( kind=hit.kind, number=hit.number, heading=hit.heading[:240], body=body, title_number=cursor["title"], chapter_number=cursor["chapter"], part_number=cursor["part"], article_number=cursor["article"], section_number=cursor["section"], subsections=_subsection_tokens(body), hierarchy_path=_cursor_path(cursor), char_start=start, char_end=end, ) ) return units
def segment_exclusive(text: str, *, language: str = "") -> list[StructureUnit]: """Internal exclusive-span segmentation of *text* (includes preamble).""" from .profiles import iso_lang, latin_split_allowed
if not text: return [] latin = not language or latin_split_allowed(language) hits = _collect_hits(text, language=language, latin=latin) retrieval_like = [h for h in hits if h.kind in {"article", "section"}] if ( not latin and len(retrieval_like) < MIN_SPLIT_HEADINGS and iso_lang(language) in _LATIN_FALLBACK_LANGS ): hits = _collect_hits(text, language=language, latin=True) return _units_from_hits(text, hits)
def split_script_units(text: str, language: str) -> list[StructureUnit]: """Retrieval projection of script-specific exclusive spans.""" internal = segment_exclusive(text, language=language) retrieval = [u for u in internal if u.kind == "article" and len(u.body.strip()) >= 16] return retrieval if len(retrieval) >= MIN_SPLIT_HEADINGS else []
def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]: """Retrieval units. Empty list means keep the whole instrument.
Prefers article/section. When those are scarce, numbered chapter then title headings (Cameroon CHAPITRE, Bolivia TÍTULO, Cape Verde CAPÍTULO). """ if not text or len(text) < 16: return [] from .profiles import latin_split_allowed
internal = segment_exclusive(text, language=language)
def _take(kinds: set[str]) -> list[StructureUnit]: out: list[StructureUnit] = [] for u in internal: if u.kind not in kinds: continue min_len = 16 if u.number else MIN_UNIT_CHARS if language and not latin_split_allowed(language): min_len = 16 if len(u.body.strip()) >= min_len: out.append(u) return out
for kinds in ( {"article", "section"}, {"chapter"}, {"part"}, {"title"}, ): retrieval = _take(kinds) if len(retrieval) >= MIN_SPLIT_HEADINGS: return retrieval return []scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/americas/__init__.pyAdded+5
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/asia_pacific/__init__.pyAdded+5
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/__init__.pyAdded+73
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/base.pyAdded+161
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/complaint_types.pyAdded+1520
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/legal_patterns.pyAdded+489
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/civil_rights_tree.jsonAdded+95
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/consumer_tree.jsonAdded+97
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/criminal_defense_tree.jsonAdded+72
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/dei_tree.jsonAdded+55
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/employment_tree.jsonAdded+129
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/environmental_law_tree.jsonAdded+71
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/family_law_tree.jsonAdded+74
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/free_speech_tree.jsonAdded+72
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/healthcare_tree.jsonAdded+83
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/housing_tree.jsonAdded+141
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/immigration_tree.jsonAdded+70
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/intellectual_property_tree.jsonAdded+72
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/probate_tree.jsonAdded+116
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/tax_law_tree.jsonAdded+74
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/__init__.pyAdded+19
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/__main__.pyAdded+463
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/admit.pyAdded+702
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/auth.pyAdded+38
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/bm25.pyAdded+227
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/build.pyAdded+661
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/catalog.pyAdded+307
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/cidutil.pyAdded+102
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/citations.pyAdded+139
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/coverage.pyAdded+455
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/duckdb_store.pyAdded+475
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/graph.pyAdded+350
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/html_legal.pyAdded+213
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/incremental.pyAdded+562
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/instrument_inherit.pyAdded+442
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/mem.pyAdded+301
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/national_directory.pyAdded+697
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize.pyAdded+1272
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize_loop.pyAdded+621
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/package.pyAdded+1010
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/parquet_io.pyAdded+83
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/profiles.pyAdded+342
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/query.pyAdded+221
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/raw_package.pyAdded+324
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/reconstruct.pyAdded+232
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/resources.pyAdded+200
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/schema.pyAdded+128
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/sparse.pyAdded+144
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/spill.pyAdded+532
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/structure.pyAdded+2203