Add scrapers_and_normalizers overlay (subnational/subnational_general, data/* untouched) [2/3]
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/americas/__init__.py +5 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/asia_pacific/__init__.py +5 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/__init__.py +73 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/base.py +161 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/complaint_types.py +1520 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/legal_patterns.py +489 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/civil_rights_tree.json +95 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/consumer_tree.json +97 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/criminal_defense_tree.json +72 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/dei_tree.json +55 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/employment_tree.json +129 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/environmental_law_tree.json +71 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/family_law_tree.json +74 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/free_speech_tree.json +72 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/healthcare_tree.json +83 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/housing_tree.json +141 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/immigration_tree.json +70 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/intellectual_property_tree.json +72 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/probate_tree.json +116 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/tax_law_tree.json +74 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/__init__.py +19 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/__main__.py +463 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/admit.py +702 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/auth.py +38 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/bm25.py +227 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/build.py +661 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/catalog.py +307 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/cidutil.py +102 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/citations.py +139 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/coverage.py +455 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/duckdb_store.py +475 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/graph.py +350 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/html_legal.py +213 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/incremental.py +562 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/instrument_inherit.py +442 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/mem.py +301 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/national_directory.py +697 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize.py +1272 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize_loop.py +621 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/package.py +1010 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/parquet_io.py +83 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/profiles.py +342 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/query.py +221 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/raw_package.py +324 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/reconstruct.py +232 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/resources.py +200 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/schema.py +128 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/sparse.py +144 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/spill.py +532 -0
- scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/structure.py +2203 -0
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/americas/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Americas official-gazette collectors (North, Central, South America, Caribbean)."""
|
| 2 |
+
|
| 3 |
+
from ipfs_datasets_py.processors.legal_scrapers.regions import Americas
|
| 4 |
+
|
| 5 |
+
__all__ = ["Americas"]
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/asia_pacific/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Asia-Pacific official-gazette collectors, including Oceania."""
|
| 2 |
+
|
| 3 |
+
from ipfs_datasets_py.processors.legal_scrapers.regions import AsiaPacific
|
| 4 |
+
|
| 5 |
+
__all__ = ["AsiaPacific"]
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/__init__.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Shared components for legal search and complaint analysis.
|
| 3 |
+
|
| 4 |
+
This module contains components that are used by both:
|
| 5 |
+
- Brave Legal Search system (query_processor, search_term_generator)
|
| 6 |
+
- Complaint Analysis system (analyzer, indexer, risk_scoring)
|
| 7 |
+
|
| 8 |
+
Components extracted from complaint_analysis for reusability:
|
| 9 |
+
- keywords.py: Keyword registry and management
|
| 10 |
+
- legal_patterns.py: Pattern extraction and matching
|
| 11 |
+
- base.py: Abstract base classes and interfaces
|
| 12 |
+
- complaint_types.py: Complaint type definitions and registry
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
from ipfs_datasets_py.processors.legal_scrapers.common import (
|
| 16 |
+
get_keywords,
|
| 17 |
+
LegalPatternExtractor,
|
| 18 |
+
BaseComplaintAnalyzer,
|
| 19 |
+
get_registered_types
|
| 20 |
+
)
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
# Import all shared components for easy access
|
| 24 |
+
from .keywords import (
|
| 25 |
+
COMPLAINT_KEYWORDS,
|
| 26 |
+
register_keywords,
|
| 27 |
+
register_legal_terms,
|
| 28 |
+
get_keywords,
|
| 29 |
+
get_type_specific_keywords,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
from .legal_patterns import (
|
| 33 |
+
LegalPatternExtractor,
|
| 34 |
+
ComplaintLegalPatternExtractor,
|
| 35 |
+
extract_legal_patterns,
|
| 36 |
+
extract_complaint_patterns,
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
from .base import (
|
| 40 |
+
BaseComplaintAnalyzer,
|
| 41 |
+
BaseRiskScorer,
|
| 42 |
+
BaseComplaintIndexer,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
from .complaint_types import (
|
| 46 |
+
ComplaintType,
|
| 47 |
+
register_complaint_type,
|
| 48 |
+
get_registered_types,
|
| 49 |
+
get_complaint_type,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
__all__ = [
|
| 53 |
+
# Keywords
|
| 54 |
+
"COMPLAINT_KEYWORDS",
|
| 55 |
+
"register_keywords",
|
| 56 |
+
"register_legal_terms",
|
| 57 |
+
"get_keywords",
|
| 58 |
+
"get_type_specific_keywords",
|
| 59 |
+
# Legal Patterns
|
| 60 |
+
"LegalPatternExtractor",
|
| 61 |
+
"ComplaintLegalPatternExtractor",
|
| 62 |
+
"extract_legal_patterns",
|
| 63 |
+
"extract_complaint_patterns",
|
| 64 |
+
# Base Classes
|
| 65 |
+
"BaseComplaintAnalyzer",
|
| 66 |
+
"BaseRiskScorer",
|
| 67 |
+
"BaseComplaintIndexer",
|
| 68 |
+
# Complaint Types
|
| 69 |
+
"ComplaintType",
|
| 70 |
+
"register_complaint_type",
|
| 71 |
+
"get_registered_types",
|
| 72 |
+
"get_complaint_type",
|
| 73 |
+
]
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/base.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Base Classes for Extensible Complaint Analysis
|
| 3 |
+
|
| 4 |
+
These abstract base classes define the interface for extending the complaint
|
| 5 |
+
analysis system with new complaint types, keywords, and risk scoring logic.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from abc import ABC, abstractmethod
|
| 9 |
+
from typing import Dict, List, Optional, Any
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class BaseLegalPatternExtractor(ABC):
|
| 13 |
+
"""
|
| 14 |
+
Abstract base class for legal pattern extraction.
|
| 15 |
+
|
| 16 |
+
Extend this class to add custom legal term patterns for new complaint types.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
@abstractmethod
|
| 20 |
+
def extract_provisions(self, text: str, context_chars: int = 200) -> Dict[str, Any]:
|
| 21 |
+
"""
|
| 22 |
+
Extract legal provisions from text.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
text: Text to analyze
|
| 26 |
+
context_chars: Number of characters to include before/after match
|
| 27 |
+
|
| 28 |
+
Returns:
|
| 29 |
+
Dictionary with provisions, terms_found, provision_count, etc.
|
| 30 |
+
"""
|
| 31 |
+
pass
|
| 32 |
+
|
| 33 |
+
@abstractmethod
|
| 34 |
+
def extract_citations(self, text: str) -> List[Dict[str, str]]:
|
| 35 |
+
"""
|
| 36 |
+
Extract legal citations from text.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
text: Text to analyze
|
| 40 |
+
|
| 41 |
+
Returns:
|
| 42 |
+
List of found citations with metadata
|
| 43 |
+
"""
|
| 44 |
+
pass
|
| 45 |
+
|
| 46 |
+
@abstractmethod
|
| 47 |
+
def categorize_complaint_type(self, text: str) -> List[str]:
|
| 48 |
+
"""
|
| 49 |
+
Categorize the complaint based on content.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
text: Text to analyze
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
List of applicable complaint categories
|
| 56 |
+
"""
|
| 57 |
+
pass
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class BaseKeywordRegistry(ABC):
|
| 61 |
+
"""
|
| 62 |
+
Abstract base class for keyword registry.
|
| 63 |
+
|
| 64 |
+
Extend this class to implement custom keyword management for different
|
| 65 |
+
complaint types or domains.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
@abstractmethod
|
| 69 |
+
def register_keywords(
|
| 70 |
+
self, category: str, keywords: List[str], complaint_type: Optional[str] = None
|
| 71 |
+
) -> None:
|
| 72 |
+
"""
|
| 73 |
+
Register keywords for a category.
|
| 74 |
+
|
| 75 |
+
Args:
|
| 76 |
+
category: Category name (e.g., 'complaint', 'evidence', 'legal')
|
| 77 |
+
keywords: List of keywords to register
|
| 78 |
+
complaint_type: Optional complaint type to scope keywords to
|
| 79 |
+
"""
|
| 80 |
+
pass
|
| 81 |
+
|
| 82 |
+
@abstractmethod
|
| 83 |
+
def get_keywords(self, category: str, complaint_type: Optional[str] = None) -> List[str]:
|
| 84 |
+
"""
|
| 85 |
+
Get keywords for a category.
|
| 86 |
+
|
| 87 |
+
Args:
|
| 88 |
+
category: Category name
|
| 89 |
+
complaint_type: Optional complaint type to filter by
|
| 90 |
+
|
| 91 |
+
Returns:
|
| 92 |
+
List of keywords
|
| 93 |
+
"""
|
| 94 |
+
pass
|
| 95 |
+
|
| 96 |
+
@abstractmethod
|
| 97 |
+
def get_all_categories(self, complaint_type: Optional[str] = None) -> List[str]:
|
| 98 |
+
"""
|
| 99 |
+
Get all registered categories.
|
| 100 |
+
|
| 101 |
+
Args:
|
| 102 |
+
complaint_type: Optional complaint type to filter by
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
List of category names
|
| 106 |
+
"""
|
| 107 |
+
pass
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class BaseRiskScorer(ABC):
|
| 111 |
+
"""
|
| 112 |
+
Abstract base class for risk scoring.
|
| 113 |
+
|
| 114 |
+
Extend this class to implement custom risk scoring logic for different
|
| 115 |
+
complaint types or risk models.
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
@abstractmethod
|
| 119 |
+
def calculate_risk(
|
| 120 |
+
self, text: str, legal_provisions: Optional[List[Dict]] = None, **kwargs
|
| 121 |
+
) -> Dict[str, Any]:
|
| 122 |
+
"""
|
| 123 |
+
Calculate risk score for a complaint.
|
| 124 |
+
|
| 125 |
+
Args:
|
| 126 |
+
text: Document text to analyze
|
| 127 |
+
legal_provisions: Optional pre-extracted legal provisions
|
| 128 |
+
**kwargs: Additional parameters for risk calculation
|
| 129 |
+
|
| 130 |
+
Returns:
|
| 131 |
+
Dictionary containing:
|
| 132 |
+
- score: Risk score (numeric)
|
| 133 |
+
- level: Risk level name
|
| 134 |
+
- factors: List of contributing factors
|
| 135 |
+
- recommendations: Suggested actions
|
| 136 |
+
"""
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
@abstractmethod
|
| 140 |
+
def get_risk_levels(self) -> List[str]:
|
| 141 |
+
"""
|
| 142 |
+
Get available risk levels.
|
| 143 |
+
|
| 144 |
+
Returns:
|
| 145 |
+
List of risk level names (e.g., ['minimal', 'low', 'medium', 'high'])
|
| 146 |
+
"""
|
| 147 |
+
pass
|
| 148 |
+
|
| 149 |
+
@abstractmethod
|
| 150 |
+
def is_actionable(self, text: str, threshold: float = 0.5) -> bool:
|
| 151 |
+
"""
|
| 152 |
+
Determine if complaint is actionable.
|
| 153 |
+
|
| 154 |
+
Args:
|
| 155 |
+
text: Document text
|
| 156 |
+
threshold: Minimum score threshold
|
| 157 |
+
|
| 158 |
+
Returns:
|
| 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|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Complaint Type Registration
|
| 3 |
+
|
| 4 |
+
Provides convenience functions for registering different complaint types
|
| 5 |
+
with their specific keywords, patterns, and scoring models.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Any, Dict, List, Optional
|
| 9 |
+
from .keywords import register_keywords
|
| 10 |
+
from .legal_patterns import register_legal_terms
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def register_housing_complaint():
|
| 14 |
+
"""Register keywords and patterns for housing complaints."""
|
| 15 |
+
# Already registered in keywords.py, but this allows for programmatic registration
|
| 16 |
+
pass
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def register_employment_complaint():
|
| 20 |
+
"""Register keywords and patterns for employment complaints."""
|
| 21 |
+
# Already registered in keywords.py
|
| 22 |
+
pass
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def register_civil_rights_complaint():
|
| 26 |
+
"""Register keywords and patterns for civil rights complaints."""
|
| 27 |
+
# Additional civil rights specific keywords
|
| 28 |
+
register_keywords(
|
| 29 |
+
"complaint",
|
| 30 |
+
[
|
| 31 |
+
"police brutality",
|
| 32 |
+
"excessive force",
|
| 33 |
+
"unlawful search",
|
| 34 |
+
"unlawful seizure",
|
| 35 |
+
"first amendment",
|
| 36 |
+
"freedom of speech",
|
| 37 |
+
"freedom of assembly",
|
| 38 |
+
"voting rights",
|
| 39 |
+
],
|
| 40 |
+
complaint_type="civil_rights",
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def register_consumer_complaint():
|
| 45 |
+
"""Register keywords and patterns for consumer protection complaints."""
|
| 46 |
+
register_keywords(
|
| 47 |
+
"complaint",
|
| 48 |
+
[
|
| 49 |
+
"fraud",
|
| 50 |
+
"deception",
|
| 51 |
+
"misrepresentation",
|
| 52 |
+
"unfair practice",
|
| 53 |
+
"deceptive practice",
|
| 54 |
+
"false advertising",
|
| 55 |
+
"bait and switch",
|
| 56 |
+
"warranty breach",
|
| 57 |
+
"consumer protection",
|
| 58 |
+
"ftc",
|
| 59 |
+
"federal trade commission",
|
| 60 |
+
],
|
| 61 |
+
complaint_type="consumer",
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
register_legal_terms(
|
| 65 |
+
"consumer",
|
| 66 |
+
[
|
| 67 |
+
r"\b(fraud|fraudulent)\b",
|
| 68 |
+
r"\b(deceptive (practice|trade))\b",
|
| 69 |
+
r"\b(false advertising)\b",
|
| 70 |
+
r"\b(consumer protection)\b",
|
| 71 |
+
r"\b(ftc|federal trade commission)\b",
|
| 72 |
+
],
|
| 73 |
+
)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def register_healthcare_complaint():
|
| 77 |
+
"""Register keywords and patterns for healthcare complaints."""
|
| 78 |
+
register_keywords(
|
| 79 |
+
"complaint",
|
| 80 |
+
[
|
| 81 |
+
"medical malpractice",
|
| 82 |
+
"negligence",
|
| 83 |
+
"hipaa",
|
| 84 |
+
"medical privacy",
|
| 85 |
+
"patient rights",
|
| 86 |
+
"informed consent",
|
| 87 |
+
"emergency medical",
|
| 88 |
+
"emtala",
|
| 89 |
+
],
|
| 90 |
+
complaint_type="healthcare",
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def register_free_speech_complaint():
|
| 95 |
+
"""Register keywords and patterns for censorship and free speech complaints."""
|
| 96 |
+
register_keywords(
|
| 97 |
+
"complaint",
|
| 98 |
+
[
|
| 99 |
+
# First Amendment
|
| 100 |
+
"first amendment",
|
| 101 |
+
"free speech",
|
| 102 |
+
"freedom of speech",
|
| 103 |
+
"freedom of expression",
|
| 104 |
+
"freedom of the press",
|
| 105 |
+
"prior restraint",
|
| 106 |
+
"viewpoint discrimination",
|
| 107 |
+
"content-based restriction",
|
| 108 |
+
"content-neutral",
|
| 109 |
+
# Censorship
|
| 110 |
+
"censorship",
|
| 111 |
+
"censor",
|
| 112 |
+
"censored",
|
| 113 |
+
"suppression",
|
| 114 |
+
"silenced",
|
| 115 |
+
"deplatformed",
|
| 116 |
+
"banned",
|
| 117 |
+
"suspension",
|
| 118 |
+
"account termination",
|
| 119 |
+
# Social media / platforms
|
| 120 |
+
"content moderation",
|
| 121 |
+
"platform moderation",
|
| 122 |
+
"community guidelines",
|
| 123 |
+
"terms of service violation",
|
| 124 |
+
"shadowban",
|
| 125 |
+
"demonetized",
|
| 126 |
+
"demonetization",
|
| 127 |
+
"algorithm bias",
|
| 128 |
+
"content suppression",
|
| 129 |
+
# Public forum / government
|
| 130 |
+
"public forum",
|
| 131 |
+
"limited public forum",
|
| 132 |
+
"government censorship",
|
| 133 |
+
"state action",
|
| 134 |
+
"chilling effect",
|
| 135 |
+
"prior restraint",
|
| 136 |
+
# Academic / institutional
|
| 137 |
+
"academic freedom",
|
| 138 |
+
"intellectual freedom",
|
| 139 |
+
"library censorship",
|
| 140 |
+
"book ban",
|
| 141 |
+
"curriculum restriction",
|
| 142 |
+
# Whistleblower / retaliation
|
| 143 |
+
"whistleblower",
|
| 144 |
+
"retaliation for speech",
|
| 145 |
+
"protected speech",
|
| 146 |
+
"political speech",
|
| 147 |
+
],
|
| 148 |
+
complaint_type="free_speech",
|
| 149 |
+
)
|
| 150 |
+
|
| 151 |
+
register_legal_terms(
|
| 152 |
+
"free_speech",
|
| 153 |
+
[
|
| 154 |
+
r"\b(first amendment)\b",
|
| 155 |
+
r"\b(free(dom of)? speech)\b",
|
| 156 |
+
r"\b(free(dom of)? (expression|press))\b",
|
| 157 |
+
r"\b(prior restraint)\b",
|
| 158 |
+
r"\b(viewpoint discrimination)\b",
|
| 159 |
+
r"\b(content[- ]based restriction)\b",
|
| 160 |
+
r"\b(public forum)\b",
|
| 161 |
+
r"\b(state action)\b",
|
| 162 |
+
r"\b(chilling effect)\b",
|
| 163 |
+
r"\b(censorship|censor(ed)?)\b",
|
| 164 |
+
],
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def register_immigration_complaint():
|
| 169 |
+
"""Register keywords and patterns for immigration law complaints."""
|
| 170 |
+
register_keywords(
|
| 171 |
+
"complaint",
|
| 172 |
+
[
|
| 173 |
+
# Immigration status
|
| 174 |
+
"immigration",
|
| 175 |
+
"immigrant",
|
| 176 |
+
"undocumented",
|
| 177 |
+
"visa",
|
| 178 |
+
"green card",
|
| 179 |
+
"permanent resident",
|
| 180 |
+
"naturalization",
|
| 181 |
+
"citizenship",
|
| 182 |
+
"asylum",
|
| 183 |
+
"refugee",
|
| 184 |
+
"asylee",
|
| 185 |
+
"temporary protected status",
|
| 186 |
+
"tps",
|
| 187 |
+
"daca",
|
| 188 |
+
"dreamer",
|
| 189 |
+
"deferred action",
|
| 190 |
+
# Agencies and processes
|
| 191 |
+
"uscis",
|
| 192 |
+
"ice",
|
| 193 |
+
"cbp",
|
| 194 |
+
"immigration and customs enforcement",
|
| 195 |
+
"customs and border protection",
|
| 196 |
+
"immigration court",
|
| 197 |
+
"eoir",
|
| 198 |
+
"deportation",
|
| 199 |
+
"removal proceedings",
|
| 200 |
+
"detention",
|
| 201 |
+
"immigration detention",
|
| 202 |
+
"bond hearing",
|
| 203 |
+
# Employment immigration
|
| 204 |
+
"h-1b",
|
| 205 |
+
"h-2a",
|
| 206 |
+
"h-2b",
|
| 207 |
+
"l-1",
|
| 208 |
+
"o-1",
|
| 209 |
+
"employment-based visa",
|
| 210 |
+
"labor certification",
|
| 211 |
+
"perm",
|
| 212 |
+
"prevailing wage",
|
| 213 |
+
# Family immigration
|
| 214 |
+
"family-based immigration",
|
| 215 |
+
"family petition",
|
| 216 |
+
"i-130",
|
| 217 |
+
"marriage-based green card",
|
| 218 |
+
"adjustment of status",
|
| 219 |
+
"consular processing",
|
| 220 |
+
# Immigration violations
|
| 221 |
+
"immigration fraud",
|
| 222 |
+
"unlawful presence",
|
| 223 |
+
"visa overstay",
|
| 224 |
+
"bars to admission",
|
| 225 |
+
"inadmissibility",
|
| 226 |
+
"removal order",
|
| 227 |
+
# Rights and remedies
|
| 228 |
+
"withholding of removal",
|
| 229 |
+
"cancellation of removal",
|
| 230 |
+
"relief from removal",
|
| 231 |
+
"stay of removal",
|
| 232 |
+
"travel document",
|
| 233 |
+
"advance parole",
|
| 234 |
+
"employment authorization",
|
| 235 |
+
"work permit",
|
| 236 |
+
],
|
| 237 |
+
complaint_type="immigration",
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
register_legal_terms(
|
| 241 |
+
"immigration",
|
| 242 |
+
[
|
| 243 |
+
r"\b(immigration|immigrant)\b",
|
| 244 |
+
r"\b(visa|green card)\b",
|
| 245 |
+
r"\b(asylum|refugee|asylee)\b",
|
| 246 |
+
r"\b(deportation|removal)\b",
|
| 247 |
+
r"\b(uscis|ice|cbp|eoir)\b",
|
| 248 |
+
r"\b(daca|dreamer)\b",
|
| 249 |
+
r"\b(h-?1b|h-?2[ab]|l-?1|o-?1)\b",
|
| 250 |
+
r"\b(adjustment of status)\b",
|
| 251 |
+
r"\b(withholding of removal)\b",
|
| 252 |
+
r"\b(cancellation of removal)\b",
|
| 253 |
+
],
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def register_family_law_complaint():
|
| 258 |
+
"""Register keywords and patterns for family law complaints."""
|
| 259 |
+
register_keywords(
|
| 260 |
+
"complaint",
|
| 261 |
+
[
|
| 262 |
+
# Divorce / dissolution
|
| 263 |
+
"divorce",
|
| 264 |
+
"dissolution of marriage",
|
| 265 |
+
"legal separation",
|
| 266 |
+
"annulment",
|
| 267 |
+
"marital property",
|
| 268 |
+
"community property",
|
| 269 |
+
"equitable distribution",
|
| 270 |
+
"property division",
|
| 271 |
+
# Child custody
|
| 272 |
+
"child custody",
|
| 273 |
+
"parenting time",
|
| 274 |
+
"visitation",
|
| 275 |
+
"sole custody",
|
| 276 |
+
"joint custody",
|
| 277 |
+
"shared custody",
|
| 278 |
+
"physical custody",
|
| 279 |
+
"legal custody",
|
| 280 |
+
"custodial parent",
|
| 281 |
+
"non-custodial parent",
|
| 282 |
+
"parenting plan",
|
| 283 |
+
"custody order",
|
| 284 |
+
# Child support
|
| 285 |
+
"child support",
|
| 286 |
+
"support obligation",
|
| 287 |
+
"child support arrears",
|
| 288 |
+
"support enforcement",
|
| 289 |
+
"support modification",
|
| 290 |
+
# Spousal support
|
| 291 |
+
"alimony",
|
| 292 |
+
"spousal support",
|
| 293 |
+
"maintenance",
|
| 294 |
+
"temporary support",
|
| 295 |
+
"rehabilitative support",
|
| 296 |
+
"permanent support",
|
| 297 |
+
# Domestic violence
|
| 298 |
+
"domestic violence",
|
| 299 |
+
"domestic abuse",
|
| 300 |
+
"protective order",
|
| 301 |
+
"restraining order",
|
| 302 |
+
"order of protection",
|
| 303 |
+
"no-contact order",
|
| 304 |
+
# Adoption / guardianship
|
| 305 |
+
"adoption",
|
| 306 |
+
"guardianship",
|
| 307 |
+
"foster care",
|
| 308 |
+
"termination of parental rights",
|
| 309 |
+
# Paternity
|
| 310 |
+
"paternity",
|
| 311 |
+
"parentage",
|
| 312 |
+
"genetic testing",
|
| 313 |
+
],
|
| 314 |
+
complaint_type="family_law",
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
register_legal_terms(
|
| 318 |
+
"family_law",
|
| 319 |
+
[
|
| 320 |
+
r"\b(divorce|dissolution)\b",
|
| 321 |
+
r"\b(child custody|parenting time)\b",
|
| 322 |
+
r"\b(child support)\b",
|
| 323 |
+
r"\b(alimony|spousal support)\b",
|
| 324 |
+
r"\b(domestic (violence|abuse))\b",
|
| 325 |
+
r"\b((protective|restraining) order)\b",
|
| 326 |
+
r"\b(adoption|guardianship)\b",
|
| 327 |
+
r"\b(paternity|parentage)\b",
|
| 328 |
+
],
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def register_criminal_defense_complaint():
|
| 333 |
+
"""Register keywords and patterns for criminal defense complaints."""
|
| 334 |
+
register_keywords(
|
| 335 |
+
"complaint",
|
| 336 |
+
[
|
| 337 |
+
# Constitutional rights
|
| 338 |
+
"fourth amendment",
|
| 339 |
+
"unreasonable search",
|
| 340 |
+
"illegal search",
|
| 341 |
+
"warrantless search",
|
| 342 |
+
"fifth amendment",
|
| 343 |
+
"self-incrimination",
|
| 344 |
+
"miranda rights",
|
| 345 |
+
"right to remain silent",
|
| 346 |
+
"sixth amendment",
|
| 347 |
+
"right to counsel",
|
| 348 |
+
"effective assistance of counsel",
|
| 349 |
+
"speedy trial",
|
| 350 |
+
"jury trial",
|
| 351 |
+
"eighth amendment",
|
| 352 |
+
"cruel and unusual punishment",
|
| 353 |
+
"excessive bail",
|
| 354 |
+
"excessive fine",
|
| 355 |
+
# Due process
|
| 356 |
+
"due process",
|
| 357 |
+
"procedural due process",
|
| 358 |
+
"substantive due process",
|
| 359 |
+
"fundamental fairness",
|
| 360 |
+
# Criminal procedure
|
| 361 |
+
"arrest",
|
| 362 |
+
"detention",
|
| 363 |
+
"probable cause",
|
| 364 |
+
"search warrant",
|
| 365 |
+
"arrest warrant",
|
| 366 |
+
"suppression of evidence",
|
| 367 |
+
"exclusionary rule",
|
| 368 |
+
"fruit of the poisonous tree",
|
| 369 |
+
"interrogation",
|
| 370 |
+
"confession",
|
| 371 |
+
"coerced confession",
|
| 372 |
+
# Criminal charges
|
| 373 |
+
"criminal charge",
|
| 374 |
+
"indictment",
|
| 375 |
+
"information",
|
| 376 |
+
"misdemeanor",
|
| 377 |
+
"felony",
|
| 378 |
+
"infraction",
|
| 379 |
+
# Trial rights
|
| 380 |
+
"jury selection",
|
| 381 |
+
"voir dire",
|
| 382 |
+
"peremptory challenge",
|
| 383 |
+
"confrontation clause",
|
| 384 |
+
"cross-examination",
|
| 385 |
+
"prosecutorial misconduct",
|
| 386 |
+
"brady violation",
|
| 387 |
+
"exculpatory evidence",
|
| 388 |
+
# Sentencing
|
| 389 |
+
"sentencing",
|
| 390 |
+
"sentence enhancement",
|
| 391 |
+
"three strikes",
|
| 392 |
+
"mandatory minimum",
|
| 393 |
+
"parole",
|
| 394 |
+
"probation",
|
| 395 |
+
"supervised release",
|
| 396 |
+
# Post-conviction
|
| 397 |
+
"habeas corpus",
|
| 398 |
+
"post-conviction relief",
|
| 399 |
+
"ineffective assistance",
|
| 400 |
+
"actual innocence",
|
| 401 |
+
"wrongful conviction",
|
| 402 |
+
],
|
| 403 |
+
complaint_type="criminal_defense",
|
| 404 |
+
)
|
| 405 |
+
|
| 406 |
+
register_legal_terms(
|
| 407 |
+
"criminal_defense",
|
| 408 |
+
[
|
| 409 |
+
r"\b((fourth|fifth|sixth|eighth) amendment)\b",
|
| 410 |
+
r"\b(miranda (rights|warning))\b",
|
| 411 |
+
r"\b(right to (counsel|remain silent|jury trial))\b",
|
| 412 |
+
r"\b(due process)\b",
|
| 413 |
+
r"\b(unreasonable search)\b",
|
| 414 |
+
r"\b(probable cause)\b",
|
| 415 |
+
r"\b(exclusionary rule)\b",
|
| 416 |
+
r"\b(brady violation)\b",
|
| 417 |
+
r"\b(habeas corpus)\b",
|
| 418 |
+
r"\b(ineffective assistance)\b",
|
| 419 |
+
],
|
| 420 |
+
)
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def register_tax_law_complaint():
|
| 424 |
+
"""Register keywords and patterns for tax law complaints."""
|
| 425 |
+
register_keywords(
|
| 426 |
+
"complaint",
|
| 427 |
+
[
|
| 428 |
+
# Tax agencies
|
| 429 |
+
"irs",
|
| 430 |
+
"internal revenue service",
|
| 431 |
+
"tax court",
|
| 432 |
+
"u.s. tax court",
|
| 433 |
+
"state tax",
|
| 434 |
+
"state department of revenue",
|
| 435 |
+
# Tax types
|
| 436 |
+
"income tax",
|
| 437 |
+
"corporate tax",
|
| 438 |
+
"estate tax",
|
| 439 |
+
"gift tax",
|
| 440 |
+
"payroll tax",
|
| 441 |
+
"employment tax",
|
| 442 |
+
"excise tax",
|
| 443 |
+
"sales tax",
|
| 444 |
+
"property tax",
|
| 445 |
+
# Tax processes
|
| 446 |
+
"tax audit",
|
| 447 |
+
"examination",
|
| 448 |
+
"revenue agent",
|
| 449 |
+
"notice of deficiency",
|
| 450 |
+
"statutory notice",
|
| 451 |
+
"tax assessment",
|
| 452 |
+
"tax liability",
|
| 453 |
+
"collection due process",
|
| 454 |
+
"cdp hearing",
|
| 455 |
+
# Tax penalties
|
| 456 |
+
"tax penalty",
|
| 457 |
+
"accuracy penalty",
|
| 458 |
+
"fraud penalty",
|
| 459 |
+
"failure to file",
|
| 460 |
+
"failure to pay",
|
| 461 |
+
"estimated tax penalty",
|
| 462 |
+
# Tax remedies
|
| 463 |
+
"innocent spouse relief",
|
| 464 |
+
"offer in compromise",
|
| 465 |
+
"installment agreement",
|
| 466 |
+
"currently not collectible",
|
| 467 |
+
"penalty abatement",
|
| 468 |
+
"interest abatement",
|
| 469 |
+
# Tax collection
|
| 470 |
+
"tax levy",
|
| 471 |
+
"tax lien",
|
| 472 |
+
"wage garnishment",
|
| 473 |
+
"bank levy",
|
| 474 |
+
"seizure",
|
| 475 |
+
"collection action",
|
| 476 |
+
# Tax procedure
|
| 477 |
+
"tax return",
|
| 478 |
+
"amended return",
|
| 479 |
+
"refund claim",
|
| 480 |
+
"statute of limitations",
|
| 481 |
+
"collection statute",
|
| 482 |
+
"assessment statute",
|
| 483 |
+
],
|
| 484 |
+
complaint_type="tax_law",
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
register_legal_terms(
|
| 488 |
+
"tax_law",
|
| 489 |
+
[
|
| 490 |
+
r"\b(irs|internal revenue service)\b",
|
| 491 |
+
r"\b(tax court)\b",
|
| 492 |
+
r"\b(tax (audit|assessment|liability))\b",
|
| 493 |
+
r"\b(notice of deficiency)\b",
|
| 494 |
+
r"\b(tax (penalty|levy|lien))\b",
|
| 495 |
+
r"\b(innocent spouse)\b",
|
| 496 |
+
r"\b(offer in compromise)\b",
|
| 497 |
+
r"\b(collection due process)\b",
|
| 498 |
+
],
|
| 499 |
+
)
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def register_intellectual_property_complaint():
|
| 503 |
+
"""Register keywords and patterns for intellectual property complaints."""
|
| 504 |
+
register_keywords(
|
| 505 |
+
"complaint",
|
| 506 |
+
[
|
| 507 |
+
# Patents
|
| 508 |
+
"patent",
|
| 509 |
+
"patent infringement",
|
| 510 |
+
"utility patent",
|
| 511 |
+
"design patent",
|
| 512 |
+
"patent pending",
|
| 513 |
+
"prior art",
|
| 514 |
+
"obviousness",
|
| 515 |
+
"enablement",
|
| 516 |
+
"patent claim",
|
| 517 |
+
"patent prosecution",
|
| 518 |
+
# Trademarks
|
| 519 |
+
"trademark",
|
| 520 |
+
"service mark",
|
| 521 |
+
"trade name",
|
| 522 |
+
"trademark infringement",
|
| 523 |
+
"likelihood of confusion",
|
| 524 |
+
"trademark dilution",
|
| 525 |
+
"famous mark",
|
| 526 |
+
"generic mark",
|
| 527 |
+
"descriptive mark",
|
| 528 |
+
"suggestive mark",
|
| 529 |
+
"arbitrary mark",
|
| 530 |
+
"trade dress",
|
| 531 |
+
"secondary meaning",
|
| 532 |
+
# Copyrights
|
| 533 |
+
"copyright",
|
| 534 |
+
"copyright infringement",
|
| 535 |
+
"fair use",
|
| 536 |
+
"transformative use",
|
| 537 |
+
"derivative work",
|
| 538 |
+
"copyright registration",
|
| 539 |
+
"dmca",
|
| 540 |
+
"digital millennium copyright act",
|
| 541 |
+
"takedown notice",
|
| 542 |
+
"counter-notice",
|
| 543 |
+
# Trade secrets
|
| 544 |
+
"trade secret",
|
| 545 |
+
"confidential information",
|
| 546 |
+
"misappropriation",
|
| 547 |
+
"utsa",
|
| 548 |
+
"non-disclosure agreement",
|
| 549 |
+
"nda",
|
| 550 |
+
"non-compete agreement",
|
| 551 |
+
# General IP
|
| 552 |
+
"intellectual property",
|
| 553 |
+
"ip",
|
| 554 |
+
"licensing",
|
| 555 |
+
"royalty",
|
| 556 |
+
"license agreement",
|
| 557 |
+
"infringement",
|
| 558 |
+
"cease and desist",
|
| 559 |
+
"damages",
|
| 560 |
+
"injunctive relief",
|
| 561 |
+
],
|
| 562 |
+
complaint_type="intellectual_property",
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
register_legal_terms(
|
| 566 |
+
"intellectual_property",
|
| 567 |
+
[
|
| 568 |
+
r"\b(patent( infringement)?)\b",
|
| 569 |
+
r"\b(trademark( infringement)?)\b",
|
| 570 |
+
r"\b(copyright( infringement)?)\b",
|
| 571 |
+
r"\b(trade secret)\b",
|
| 572 |
+
r"\b(fair use)\b",
|
| 573 |
+
r"\b(dmca)\b",
|
| 574 |
+
r"\b(likelihood of confusion)\b",
|
| 575 |
+
r"\b(trade dress)\b",
|
| 576 |
+
],
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def register_environmental_law_complaint():
|
| 581 |
+
"""Register keywords and patterns for environmental law complaints."""
|
| 582 |
+
register_keywords(
|
| 583 |
+
"complaint",
|
| 584 |
+
[
|
| 585 |
+
# Environmental agencies
|
| 586 |
+
"epa",
|
| 587 |
+
"environmental protection agency",
|
| 588 |
+
"clean air act",
|
| 589 |
+
"clean water act",
|
| 590 |
+
"safe drinking water act",
|
| 591 |
+
# Environmental issues
|
| 592 |
+
"pollution",
|
| 593 |
+
"contamination",
|
| 594 |
+
"air pollution",
|
| 595 |
+
"water pollution",
|
| 596 |
+
"soil contamination",
|
| 597 |
+
"groundwater contamination",
|
| 598 |
+
"toxic waste",
|
| 599 |
+
"hazardous waste",
|
| 600 |
+
"hazardous substance",
|
| 601 |
+
"pollutant",
|
| 602 |
+
# Environmental laws
|
| 603 |
+
"cercla",
|
| 604 |
+
"superfund",
|
| 605 |
+
"rcra",
|
| 606 |
+
"resource conservation and recovery act",
|
| 607 |
+
"comprehensive environmental response",
|
| 608 |
+
"nepa",
|
| 609 |
+
"environmental impact statement",
|
| 610 |
+
"endangered species act",
|
| 611 |
+
"esa",
|
| 612 |
+
# Environmental violations
|
| 613 |
+
"environmental violation",
|
| 614 |
+
"permit violation",
|
| 615 |
+
"discharge violation",
|
| 616 |
+
"emission violation",
|
| 617 |
+
"npdes",
|
| 618 |
+
"national pollutant discharge",
|
| 619 |
+
# Environmental liability
|
| 620 |
+
"environmental liability",
|
| 621 |
+
"cleanup cost",
|
| 622 |
+
"remediation",
|
| 623 |
+
"natural resource damage",
|
| 624 |
+
"citizen suit",
|
| 625 |
+
"environmental enforcement",
|
| 626 |
+
# Climate
|
| 627 |
+
"greenhouse gas",
|
| 628 |
+
"carbon emission",
|
| 629 |
+
"climate change",
|
| 630 |
+
"global warming",
|
| 631 |
+
],
|
| 632 |
+
complaint_type="environmental_law",
|
| 633 |
+
)
|
| 634 |
+
|
| 635 |
+
register_legal_terms(
|
| 636 |
+
"environmental_law",
|
| 637 |
+
[
|
| 638 |
+
r"\b(epa|environmental protection agency)\b",
|
| 639 |
+
r"\b(clean (air|water) act)\b",
|
| 640 |
+
r"\b(cercla|superfund)\b",
|
| 641 |
+
r"\b(rcra)\b",
|
| 642 |
+
r"\b(nepa)\b",
|
| 643 |
+
r"\b(endangered species act)\b",
|
| 644 |
+
r"\b((air|water) pollution)\b",
|
| 645 |
+
r"\b((toxic|hazardous) waste)\b",
|
| 646 |
+
r"\b(contamination|remediation)\b",
|
| 647 |
+
],
|
| 648 |
+
)
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def register_probate_complaint():
|
| 652 |
+
"""Register keywords and patterns for probate and estate law complaints."""
|
| 653 |
+
register_keywords(
|
| 654 |
+
"complaint",
|
| 655 |
+
[
|
| 656 |
+
# Probate process
|
| 657 |
+
"probate",
|
| 658 |
+
"probate court",
|
| 659 |
+
"probate proceeding",
|
| 660 |
+
"estate administration",
|
| 661 |
+
"estate proceeding",
|
| 662 |
+
"surrogate court",
|
| 663 |
+
"orphans court",
|
| 664 |
+
# Parties
|
| 665 |
+
"decedent",
|
| 666 |
+
"deceased",
|
| 667 |
+
"testator",
|
| 668 |
+
"testatrix",
|
| 669 |
+
"estate",
|
| 670 |
+
"estate of",
|
| 671 |
+
"probate estate",
|
| 672 |
+
"executor",
|
| 673 |
+
"executrix",
|
| 674 |
+
"personal representative",
|
| 675 |
+
"administrator",
|
| 676 |
+
"administratrix",
|
| 677 |
+
"beneficiary",
|
| 678 |
+
"heir",
|
| 679 |
+
"legatee",
|
| 680 |
+
"devisee",
|
| 681 |
+
"guardian",
|
| 682 |
+
"conservator",
|
| 683 |
+
"ward",
|
| 684 |
+
"trustee",
|
| 685 |
+
"trust beneficiary",
|
| 686 |
+
"settlor",
|
| 687 |
+
"grantor",
|
| 688 |
+
# Documents
|
| 689 |
+
"will",
|
| 690 |
+
"last will and testament",
|
| 691 |
+
"testament",
|
| 692 |
+
"codicil",
|
| 693 |
+
"holographic will",
|
| 694 |
+
"nuncupative will",
|
| 695 |
+
"living will",
|
| 696 |
+
"advance directive",
|
| 697 |
+
"trust",
|
| 698 |
+
"living trust",
|
| 699 |
+
"testamentary trust",
|
| 700 |
+
"revocable trust",
|
| 701 |
+
"irrevocable trust",
|
| 702 |
+
"trust agreement",
|
| 703 |
+
"trust instrument",
|
| 704 |
+
"letters testamentary",
|
| 705 |
+
"letters of administration",
|
| 706 |
+
# Estate types
|
| 707 |
+
"testate",
|
| 708 |
+
"intestate",
|
| 709 |
+
"intestacy",
|
| 710 |
+
"partial intestacy",
|
| 711 |
+
# Assets and property
|
| 712 |
+
"estate asset",
|
| 713 |
+
"probate asset",
|
| 714 |
+
"non-probate asset",
|
| 715 |
+
"real property",
|
| 716 |
+
"personal property",
|
| 717 |
+
"tangible property",
|
| 718 |
+
"intangible property",
|
| 719 |
+
"estate inventory",
|
| 720 |
+
"asset appraisal",
|
| 721 |
+
"estate account",
|
| 722 |
+
"estate accounting",
|
| 723 |
+
# Inheritance and distribution
|
| 724 |
+
"inheritance",
|
| 725 |
+
"inherit",
|
| 726 |
+
"heir",
|
| 727 |
+
"intestate succession",
|
| 728 |
+
"statutory share",
|
| 729 |
+
"elective share",
|
| 730 |
+
"forced share",
|
| 731 |
+
"distribution",
|
| 732 |
+
"final distribution",
|
| 733 |
+
"per stirpes",
|
| 734 |
+
"per capita",
|
| 735 |
+
"right of survivorship",
|
| 736 |
+
"joint tenancy",
|
| 737 |
+
"payable on death",
|
| 738 |
+
"pod",
|
| 739 |
+
"transfer on death",
|
| 740 |
+
"tod",
|
| 741 |
+
# Debts and taxes
|
| 742 |
+
"estate debt",
|
| 743 |
+
"estate claim",
|
| 744 |
+
"creditor claim",
|
| 745 |
+
"claim against estate",
|
| 746 |
+
"notice to creditors",
|
| 747 |
+
"estate tax",
|
| 748 |
+
"inheritance tax",
|
| 749 |
+
"death tax",
|
| 750 |
+
"estate expenses",
|
| 751 |
+
"administration expenses",
|
| 752 |
+
# Guardianship and conservatorship
|
| 753 |
+
"guardianship",
|
| 754 |
+
"guardian of the person",
|
| 755 |
+
"guardian of the estate",
|
| 756 |
+
"guardian ad litem",
|
| 757 |
+
"conservatorship",
|
| 758 |
+
"conservator",
|
| 759 |
+
"incapacitated person",
|
| 760 |
+
"protected person",
|
| 761 |
+
"ward",
|
| 762 |
+
"minor",
|
| 763 |
+
"adult guardianship",
|
| 764 |
+
"guardianship proceeding",
|
| 765 |
+
# Disputes and litigation
|
| 766 |
+
"will contest",
|
| 767 |
+
"challenge will",
|
| 768 |
+
"contested will",
|
| 769 |
+
"undue influence",
|
| 770 |
+
"lack of capacity",
|
| 771 |
+
"testamentary capacity",
|
| 772 |
+
"sound mind",
|
| 773 |
+
"fraud",
|
| 774 |
+
"forgery",
|
| 775 |
+
"duress",
|
| 776 |
+
"coercion",
|
| 777 |
+
"trust dispute",
|
| 778 |
+
"trust litigation",
|
| 779 |
+
"breach of fiduciary duty",
|
| 780 |
+
"fiduciary duty",
|
| 781 |
+
"removal of executor",
|
| 782 |
+
"removal of trustee",
|
| 783 |
+
"surcharge",
|
| 784 |
+
"accounting dispute",
|
| 785 |
+
"construction of will",
|
| 786 |
+
"interpretation of will",
|
| 787 |
+
# Trust types and issues
|
| 788 |
+
"charitable trust",
|
| 789 |
+
"special needs trust",
|
| 790 |
+
"spendthrift trust",
|
| 791 |
+
"discretionary trust",
|
| 792 |
+
"marital trust",
|
| 793 |
+
"bypass trust",
|
| 794 |
+
"credit shelter trust",
|
| 795 |
+
"qualified terminable interest property",
|
| 796 |
+
"qtip trust",
|
| 797 |
+
"trust modification",
|
| 798 |
+
"trust termination",
|
| 799 |
+
"trust reformation",
|
| 800 |
+
"trust amendment",
|
| 801 |
+
# Powers and authority
|
| 802 |
+
"power of attorney",
|
| 803 |
+
"durable power of attorney",
|
| 804 |
+
"springing power of attorney",
|
| 805 |
+
"healthcare power of attorney",
|
| 806 |
+
"attorney in fact",
|
| 807 |
+
"agent",
|
| 808 |
+
# Estate planning
|
| 809 |
+
"estate plan",
|
| 810 |
+
"estate planning",
|
| 811 |
+
"succession plan",
|
| 812 |
+
"wealth transfer",
|
| 813 |
+
"gift",
|
| 814 |
+
"inter vivos gift",
|
| 815 |
+
"gift causa mortis",
|
| 816 |
+
# Marital property
|
| 817 |
+
"community property",
|
| 818 |
+
"separate property",
|
| 819 |
+
"marital property",
|
| 820 |
+
"quasi-community property",
|
| 821 |
+
"surviving spouse",
|
| 822 |
+
"widow",
|
| 823 |
+
"widower",
|
| 824 |
+
# Small estate procedures
|
| 825 |
+
"small estate affidavit",
|
| 826 |
+
"summary administration",
|
| 827 |
+
"affidavit of heirship",
|
| 828 |
+
"muniment of title",
|
| 829 |
+
# Appeals and review
|
| 830 |
+
"probate appeal",
|
| 831 |
+
"estate litigation",
|
| 832 |
+
"accounting review",
|
| 833 |
+
"estate audit",
|
| 834 |
+
],
|
| 835 |
+
complaint_type="probate",
|
| 836 |
+
)
|
| 837 |
+
|
| 838 |
+
register_legal_terms(
|
| 839 |
+
"probate",
|
| 840 |
+
[
|
| 841 |
+
r"\b(probate( court| proceeding)?)\b",
|
| 842 |
+
r"\b(estate (administration|proceeding))\b",
|
| 843 |
+
r"\b(surrogate court|orphans court)\b",
|
| 844 |
+
r"\b(executor|executrix|personal representative)\b",
|
| 845 |
+
r"\b(administrator|administratrix)\b",
|
| 846 |
+
r"\b((last )?will and testament|testament)\b",
|
| 847 |
+
r"\b(codicil)\b",
|
| 848 |
+
r"\b(living trust|testamentary trust)\b",
|
| 849 |
+
r"\b(revocable trust|irrevocable trust)\b",
|
| 850 |
+
r"\b(letters testamentary)\b",
|
| 851 |
+
r"\b(letters of administration)\b",
|
| 852 |
+
r"\b(testate|intestate|intestacy)\b",
|
| 853 |
+
r"\b(beneficiary|heir|legatee|devisee)\b",
|
| 854 |
+
r"\b(guardianship|conservatorship)\b",
|
| 855 |
+
r"\b(guardian|conservator)\b",
|
| 856 |
+
r"\b(will contest)\b",
|
| 857 |
+
r"\b(undue influence)\b",
|
| 858 |
+
r"\b(testamentary capacity)\b",
|
| 859 |
+
r"\b(breach of fiduciary duty)\b",
|
| 860 |
+
r"\b(estate (tax|debt|claim))\b",
|
| 861 |
+
r"\b(inheritance tax)\b",
|
| 862 |
+
r"\b(per stirpes|per capita)\b",
|
| 863 |
+
r"\b(elective share|forced share)\b",
|
| 864 |
+
r"\b(power of attorney)\b",
|
| 865 |
+
r"\b(trust (dispute|litigation|modification|termination))\b",
|
| 866 |
+
r"\b(charitable trust|special needs trust)\b",
|
| 867 |
+
r"\b(small estate affidavit)\b",
|
| 868 |
+
r"\b(summary administration)\b",
|
| 869 |
+
],
|
| 870 |
+
)
|
| 871 |
+
|
| 872 |
+
|
| 873 |
+
def register_dei_complaint():
|
| 874 |
+
"""
|
| 875 |
+
Register keywords and patterns for DEI (Diversity, Equity, and Inclusion) complaints.
|
| 876 |
+
|
| 877 |
+
This encompasses discrimination, harassment, and civil rights violations across
|
| 878 |
+
multiple domains including housing, employment, and public accommodations.
|
| 879 |
+
Integrates comprehensive DEI keywords from HACC repository for policy analysis.
|
| 880 |
+
"""
|
| 881 |
+
# Core DEI keywords from HACC's index_and_tag.py
|
| 882 |
+
register_keywords(
|
| 883 |
+
"complaint",
|
| 884 |
+
[
|
| 885 |
+
# Core DEI terms
|
| 886 |
+
"diversity",
|
| 887 |
+
"diverse",
|
| 888 |
+
"equity",
|
| 889 |
+
"equitable",
|
| 890 |
+
"inclusion",
|
| 891 |
+
"inclusive",
|
| 892 |
+
"dei",
|
| 893 |
+
"deia",
|
| 894 |
+
"deib",
|
| 895 |
+
"deij",
|
| 896 |
+
# Justice frameworks
|
| 897 |
+
"racial justice",
|
| 898 |
+
"social justice",
|
| 899 |
+
"environmental justice",
|
| 900 |
+
"justice-centered",
|
| 901 |
+
"justice oriented",
|
| 902 |
+
"anti-racist",
|
| 903 |
+
"anti discrimination",
|
| 904 |
+
# Community descriptors
|
| 905 |
+
"marginalized",
|
| 906 |
+
"minority",
|
| 907 |
+
"minorities",
|
| 908 |
+
"bipoc",
|
| 909 |
+
"people of color",
|
| 910 |
+
"underrepresented",
|
| 911 |
+
"underrepresented groups",
|
| 912 |
+
"underserved",
|
| 913 |
+
"underserviced",
|
| 914 |
+
"historically underrepresented",
|
| 915 |
+
"marginalized communities",
|
| 916 |
+
"socially disadvantaged",
|
| 917 |
+
"economically disadvantaged",
|
| 918 |
+
# Equity frameworks
|
| 919 |
+
"equity lens",
|
| 920 |
+
"equity framework",
|
| 921 |
+
"equity initiatives",
|
| 922 |
+
"equity plan",
|
| 923 |
+
"cultural humility",
|
| 924 |
+
"cultural responsiveness",
|
| 925 |
+
"accessibility",
|
| 926 |
+
"barrier reduction",
|
| 927 |
+
"inclusive environment",
|
| 928 |
+
# Discrimination types
|
| 929 |
+
"discrimination",
|
| 930 |
+
"discriminate",
|
| 931 |
+
"discriminatory",
|
| 932 |
+
"harassment",
|
| 933 |
+
"hostile environment",
|
| 934 |
+
"retaliation",
|
| 935 |
+
"retaliate",
|
| 936 |
+
"retaliatory",
|
| 937 |
+
# Fair housing
|
| 938 |
+
"fair housing",
|
| 939 |
+
"housing discrimination",
|
| 940 |
+
"reasonable accommodation",
|
| 941 |
+
"reasonable modification",
|
| 942 |
+
"familial status",
|
| 943 |
+
"source of income",
|
| 944 |
+
# Protected classes
|
| 945 |
+
"protected class",
|
| 946 |
+
"protected classes",
|
| 947 |
+
"race",
|
| 948 |
+
"racial",
|
| 949 |
+
"color",
|
| 950 |
+
"national origin",
|
| 951 |
+
"nationality",
|
| 952 |
+
"religion",
|
| 953 |
+
"religious",
|
| 954 |
+
"sex",
|
| 955 |
+
"gender",
|
| 956 |
+
"disability",
|
| 957 |
+
"disabled",
|
| 958 |
+
"handicap",
|
| 959 |
+
"age",
|
| 960 |
+
"elderly",
|
| 961 |
+
"sexual orientation",
|
| 962 |
+
"gender identity",
|
| 963 |
+
# Legal impact
|
| 964 |
+
"disparate impact",
|
| 965 |
+
"disparate treatment",
|
| 966 |
+
"intentional discrimination",
|
| 967 |
+
"unintentional discrimination",
|
| 968 |
+
"adverse impact",
|
| 969 |
+
"adverse effect",
|
| 970 |
+
# Housing specific
|
| 971 |
+
"section 8",
|
| 972 |
+
"housing choice voucher",
|
| 973 |
+
"public housing",
|
| 974 |
+
"affordable housing",
|
| 975 |
+
"tenant",
|
| 976 |
+
"landlord",
|
| 977 |
+
"lease",
|
| 978 |
+
"rental",
|
| 979 |
+
"eviction",
|
| 980 |
+
"housing authority",
|
| 981 |
+
# Employment specific
|
| 982 |
+
"employment discrimination",
|
| 983 |
+
"workplace discrimination",
|
| 984 |
+
"equal employment opportunity",
|
| 985 |
+
"eeoc",
|
| 986 |
+
"title vii",
|
| 987 |
+
"ada",
|
| 988 |
+
"adea",
|
| 989 |
+
"fmla",
|
| 990 |
+
# Civil rights
|
| 991 |
+
"civil rights",
|
| 992 |
+
"equal protection",
|
| 993 |
+
"due process",
|
| 994 |
+
"constitutional rights",
|
| 995 |
+
"constitutional violation",
|
| 996 |
+
# Complaint process
|
| 997 |
+
"complainant",
|
| 998 |
+
"respondent",
|
| 999 |
+
"charging party",
|
| 1000 |
+
"aggrieved person",
|
| 1001 |
+
"complaint",
|
| 1002 |
+
"charge",
|
| 1003 |
+
# Community benefits
|
| 1004 |
+
"community benefit",
|
| 1005 |
+
"community benefits",
|
| 1006 |
+
"section 3",
|
| 1007 |
+
"equal opportunity",
|
| 1008 |
+
],
|
| 1009 |
+
complaint_type="dei",
|
| 1010 |
+
)
|
| 1011 |
+
|
| 1012 |
+
# DEI proxy keywords from HACC (euphemisms and indirect references)
|
| 1013 |
+
register_keywords(
|
| 1014 |
+
"dei_proxy",
|
| 1015 |
+
[
|
| 1016 |
+
"cultural competence",
|
| 1017 |
+
"cultural competency",
|
| 1018 |
+
"lived experience",
|
| 1019 |
+
"diversity statement",
|
| 1020 |
+
"safe space",
|
| 1021 |
+
"minority-only",
|
| 1022 |
+
"first-generation",
|
| 1023 |
+
"low-income targeting",
|
| 1024 |
+
"overcoming obstacles",
|
| 1025 |
+
"implicit bias",
|
| 1026 |
+
"unconscious bias",
|
| 1027 |
+
"affirmative action",
|
| 1028 |
+
],
|
| 1029 |
+
complaint_type="dei",
|
| 1030 |
+
)
|
| 1031 |
+
|
| 1032 |
+
# Evidence-related keywords
|
| 1033 |
+
register_keywords(
|
| 1034 |
+
"evidence",
|
| 1035 |
+
[
|
| 1036 |
+
"evidence",
|
| 1037 |
+
"proof",
|
| 1038 |
+
"documentation",
|
| 1039 |
+
"witness",
|
| 1040 |
+
"testimony",
|
| 1041 |
+
"statement",
|
| 1042 |
+
"document",
|
| 1043 |
+
"record",
|
| 1044 |
+
"file",
|
| 1045 |
+
"exhibit",
|
| 1046 |
+
"attachment",
|
| 1047 |
+
"appendix",
|
| 1048 |
+
"correspondence",
|
| 1049 |
+
"email",
|
| 1050 |
+
"letter",
|
| 1051 |
+
"notice",
|
| 1052 |
+
"communication",
|
| 1053 |
+
"photograph",
|
| 1054 |
+
"image",
|
| 1055 |
+
"video",
|
| 1056 |
+
"recording",
|
| 1057 |
+
"audio",
|
| 1058 |
+
"contract",
|
| 1059 |
+
"agreement",
|
| 1060 |
+
"lease",
|
| 1061 |
+
"policy",
|
| 1062 |
+
"procedure",
|
| 1063 |
+
"manual",
|
| 1064 |
+
"complaint form",
|
| 1065 |
+
"intake form",
|
| 1066 |
+
"medical record",
|
| 1067 |
+
"doctor note",
|
| 1068 |
+
"police report",
|
| 1069 |
+
"incident report",
|
| 1070 |
+
],
|
| 1071 |
+
complaint_type="dei",
|
| 1072 |
+
)
|
| 1073 |
+
|
| 1074 |
+
# Legal authority keywords
|
| 1075 |
+
register_keywords(
|
| 1076 |
+
"legal",
|
| 1077 |
+
[
|
| 1078 |
+
"statute",
|
| 1079 |
+
"law",
|
| 1080 |
+
"code",
|
| 1081 |
+
"regulation",
|
| 1082 |
+
"ordinance",
|
| 1083 |
+
"rule",
|
| 1084 |
+
"act",
|
| 1085 |
+
"u.s.c.",
|
| 1086 |
+
"c.f.r.",
|
| 1087 |
+
"federal register",
|
| 1088 |
+
"case law",
|
| 1089 |
+
"precedent",
|
| 1090 |
+
"holding",
|
| 1091 |
+
"opinion",
|
| 1092 |
+
"decision",
|
| 1093 |
+
"ruling",
|
| 1094 |
+
"court order",
|
| 1095 |
+
"judgment",
|
| 1096 |
+
"decree",
|
| 1097 |
+
"constitution",
|
| 1098 |
+
"constitutional",
|
| 1099 |
+
"amendment",
|
| 1100 |
+
"provision",
|
| 1101 |
+
"section",
|
| 1102 |
+
"subsection",
|
| 1103 |
+
"clause",
|
| 1104 |
+
"paragraph",
|
| 1105 |
+
"title",
|
| 1106 |
+
"chapter",
|
| 1107 |
+
"article",
|
| 1108 |
+
],
|
| 1109 |
+
complaint_type="dei",
|
| 1110 |
+
)
|
| 1111 |
+
|
| 1112 |
+
# Binding/enforceable indicators
|
| 1113 |
+
register_keywords(
|
| 1114 |
+
"binding",
|
| 1115 |
+
[
|
| 1116 |
+
"policy",
|
| 1117 |
+
"ordinance",
|
| 1118 |
+
"statewide",
|
| 1119 |
+
"model policy",
|
| 1120 |
+
"contract",
|
| 1121 |
+
"agreement",
|
| 1122 |
+
"standard",
|
| 1123 |
+
"required",
|
| 1124 |
+
"must",
|
| 1125 |
+
"shall",
|
| 1126 |
+
"mandatory",
|
| 1127 |
+
"applicable to",
|
| 1128 |
+
"applicability",
|
| 1129 |
+
"enforceable",
|
| 1130 |
+
"governing",
|
| 1131 |
+
"binding",
|
| 1132 |
+
"regulation",
|
| 1133 |
+
"rule",
|
| 1134 |
+
"directive",
|
| 1135 |
+
"compliance",
|
| 1136 |
+
"obligated",
|
| 1137 |
+
"stipulation",
|
| 1138 |
+
],
|
| 1139 |
+
complaint_type="dei",
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
# Severity/risk indicators
|
| 1143 |
+
register_keywords(
|
| 1144 |
+
"severity_high",
|
| 1145 |
+
[
|
| 1146 |
+
"systemic",
|
| 1147 |
+
"pattern",
|
| 1148 |
+
"practice",
|
| 1149 |
+
"intentional",
|
| 1150 |
+
"willful",
|
| 1151 |
+
"deliberate",
|
| 1152 |
+
"egregious",
|
| 1153 |
+
"severe",
|
| 1154 |
+
"pervasive",
|
| 1155 |
+
"ongoing",
|
| 1156 |
+
"repeated",
|
| 1157 |
+
"continuous",
|
| 1158 |
+
"punitive damages",
|
| 1159 |
+
"injunctive relief",
|
| 1160 |
+
],
|
| 1161 |
+
complaint_type="dei",
|
| 1162 |
+
)
|
| 1163 |
+
|
| 1164 |
+
register_keywords(
|
| 1165 |
+
"severity_medium",
|
| 1166 |
+
[
|
| 1167 |
+
"violation",
|
| 1168 |
+
"breach",
|
| 1169 |
+
"failure",
|
| 1170 |
+
"inadequate",
|
| 1171 |
+
"insufficient",
|
| 1172 |
+
"disparate impact",
|
| 1173 |
+
"adverse effect",
|
| 1174 |
+
"compensatory damages",
|
| 1175 |
+
],
|
| 1176 |
+
complaint_type="dei",
|
| 1177 |
+
)
|
| 1178 |
+
|
| 1179 |
+
register_keywords(
|
| 1180 |
+
"severity_low",
|
| 1181 |
+
[
|
| 1182 |
+
"potential",
|
| 1183 |
+
"possible",
|
| 1184 |
+
"may",
|
| 1185 |
+
"unintentional",
|
| 1186 |
+
"inadvertent",
|
| 1187 |
+
"technical",
|
| 1188 |
+
"procedural",
|
| 1189 |
+
"correctable",
|
| 1190 |
+
"remediable",
|
| 1191 |
+
],
|
| 1192 |
+
complaint_type="dei",
|
| 1193 |
+
)
|
| 1194 |
+
|
| 1195 |
+
# Applicability keywords - DEI context covers these domains
|
| 1196 |
+
register_keywords(
|
| 1197 |
+
"applicability_housing",
|
| 1198 |
+
[
|
| 1199 |
+
"housing",
|
| 1200 |
+
"lease",
|
| 1201 |
+
"tenant",
|
| 1202 |
+
"landlord",
|
| 1203 |
+
"rental",
|
| 1204 |
+
"dwelling",
|
| 1205 |
+
"residence",
|
| 1206 |
+
"apartment",
|
| 1207 |
+
"unit",
|
| 1208 |
+
"eviction",
|
| 1209 |
+
"termination",
|
| 1210 |
+
"nonrenewal",
|
| 1211 |
+
"affordable",
|
| 1212 |
+
"public housing",
|
| 1213 |
+
"section 8",
|
| 1214 |
+
"housing authority",
|
| 1215 |
+
"housing choice voucher",
|
| 1216 |
+
"reasonable accommodation",
|
| 1217 |
+
"accessibility",
|
| 1218 |
+
],
|
| 1219 |
+
complaint_type="dei",
|
| 1220 |
+
)
|
| 1221 |
+
|
| 1222 |
+
register_keywords(
|
| 1223 |
+
"applicability_employment",
|
| 1224 |
+
[
|
| 1225 |
+
"employment",
|
| 1226 |
+
"workplace",
|
| 1227 |
+
"job",
|
| 1228 |
+
"work",
|
| 1229 |
+
"hire",
|
| 1230 |
+
"hiring",
|
| 1231 |
+
"recruit",
|
| 1232 |
+
"recruitment",
|
| 1233 |
+
"fire",
|
| 1234 |
+
"firing",
|
| 1235 |
+
"terminate",
|
| 1236 |
+
"termination",
|
| 1237 |
+
"promote",
|
| 1238 |
+
"promotion",
|
| 1239 |
+
"demote",
|
| 1240 |
+
"demotion",
|
| 1241 |
+
"employee",
|
| 1242 |
+
"employer",
|
| 1243 |
+
"supervisor",
|
| 1244 |
+
"wages",
|
| 1245 |
+
"salary",
|
| 1246 |
+
"compensation",
|
| 1247 |
+
"benefits",
|
| 1248 |
+
"fmla",
|
| 1249 |
+
"leave",
|
| 1250 |
+
"accommodation",
|
| 1251 |
+
],
|
| 1252 |
+
complaint_type="dei",
|
| 1253 |
+
)
|
| 1254 |
+
|
| 1255 |
+
register_keywords(
|
| 1256 |
+
"applicability_public_accommodation",
|
| 1257 |
+
[
|
| 1258 |
+
"public accommodation",
|
| 1259 |
+
"place of public accommodation",
|
| 1260 |
+
"service",
|
| 1261 |
+
"facility",
|
| 1262 |
+
"establishment",
|
| 1263 |
+
"access",
|
| 1264 |
+
"accessibility",
|
| 1265 |
+
"barrier",
|
| 1266 |
+
"restaurant",
|
| 1267 |
+
"hotel",
|
| 1268 |
+
"store",
|
| 1269 |
+
"shop",
|
| 1270 |
+
"theater",
|
| 1271 |
+
"stadium",
|
| 1272 |
+
"park",
|
| 1273 |
+
"transportation",
|
| 1274 |
+
"bus",
|
| 1275 |
+
"train",
|
| 1276 |
+
],
|
| 1277 |
+
complaint_type="dei",
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
register_keywords(
|
| 1281 |
+
"applicability_lending",
|
| 1282 |
+
[
|
| 1283 |
+
"lending",
|
| 1284 |
+
"loan",
|
| 1285 |
+
"mortgage",
|
| 1286 |
+
"credit",
|
| 1287 |
+
"financing",
|
| 1288 |
+
"financial",
|
| 1289 |
+
"bank",
|
| 1290 |
+
"lender",
|
| 1291 |
+
"interest rate",
|
| 1292 |
+
"terms",
|
| 1293 |
+
"approval",
|
| 1294 |
+
"denial",
|
| 1295 |
+
"redlining",
|
| 1296 |
+
"appraisal",
|
| 1297 |
+
],
|
| 1298 |
+
complaint_type="dei",
|
| 1299 |
+
)
|
| 1300 |
+
|
| 1301 |
+
register_keywords(
|
| 1302 |
+
"applicability_education",
|
| 1303 |
+
[
|
| 1304 |
+
"education",
|
| 1305 |
+
"school",
|
| 1306 |
+
"university",
|
| 1307 |
+
"college",
|
| 1308 |
+
"student",
|
| 1309 |
+
"enrollment",
|
| 1310 |
+
"admission",
|
| 1311 |
+
"classroom",
|
| 1312 |
+
"teacher",
|
| 1313 |
+
"faculty",
|
| 1314 |
+
"curriculum",
|
| 1315 |
+
"program",
|
| 1316 |
+
"degree",
|
| 1317 |
+
"disability services",
|
| 1318 |
+
"accommodations",
|
| 1319 |
+
],
|
| 1320 |
+
complaint_type="dei",
|
| 1321 |
+
)
|
| 1322 |
+
|
| 1323 |
+
register_keywords(
|
| 1324 |
+
"applicability_government_services",
|
| 1325 |
+
[
|
| 1326 |
+
"government",
|
| 1327 |
+
"agency",
|
| 1328 |
+
"department",
|
| 1329 |
+
"public service",
|
| 1330 |
+
"benefits",
|
| 1331 |
+
"assistance",
|
| 1332 |
+
"program",
|
| 1333 |
+
"eligibility",
|
| 1334 |
+
"application",
|
| 1335 |
+
"permit",
|
| 1336 |
+
"license",
|
| 1337 |
+
"approval",
|
| 1338 |
+
],
|
| 1339 |
+
complaint_type="dei",
|
| 1340 |
+
)
|
| 1341 |
+
|
| 1342 |
+
# Procurement and contracting (from HACC DEI research)
|
| 1343 |
+
register_keywords(
|
| 1344 |
+
"applicability_procurement",
|
| 1345 |
+
[
|
| 1346 |
+
"procurement",
|
| 1347 |
+
"contract",
|
| 1348 |
+
"contracting",
|
| 1349 |
+
"vendor",
|
| 1350 |
+
"supplier",
|
| 1351 |
+
"bid",
|
| 1352 |
+
"bidding",
|
| 1353 |
+
"rfp",
|
| 1354 |
+
"request for proposal",
|
| 1355 |
+
"award",
|
| 1356 |
+
"purchase",
|
| 1357 |
+
"purchasing",
|
| 1358 |
+
"disadvantaged business enterprise",
|
| 1359 |
+
"dbe",
|
| 1360 |
+
"minority-owned business",
|
| 1361 |
+
"mbe",
|
| 1362 |
+
"women-owned business",
|
| 1363 |
+
"wbe",
|
| 1364 |
+
"mwesb",
|
| 1365 |
+
"esb",
|
| 1366 |
+
"socially disadvantaged",
|
| 1367 |
+
"economically disadvantaged",
|
| 1368 |
+
"small business",
|
| 1369 |
+
"certification",
|
| 1370 |
+
"subcontractor",
|
| 1371 |
+
"subcontracting",
|
| 1372 |
+
],
|
| 1373 |
+
complaint_type="dei",
|
| 1374 |
+
)
|
| 1375 |
+
|
| 1376 |
+
# Training and development (from HACC index_and_tag.py)
|
| 1377 |
+
register_keywords(
|
| 1378 |
+
"applicability_training",
|
| 1379 |
+
[
|
| 1380 |
+
"training",
|
| 1381 |
+
"workshop",
|
| 1382 |
+
"course",
|
| 1383 |
+
"curriculum",
|
| 1384 |
+
"education",
|
| 1385 |
+
"seminar",
|
| 1386 |
+
"professional development",
|
| 1387 |
+
"orientation",
|
| 1388 |
+
"onboarding",
|
| 1389 |
+
"certification",
|
| 1390 |
+
"cultural competency training",
|
| 1391 |
+
"implicit bias training",
|
| 1392 |
+
"diversity training",
|
| 1393 |
+
"sensitivity training",
|
| 1394 |
+
],
|
| 1395 |
+
complaint_type="dei",
|
| 1396 |
+
)
|
| 1397 |
+
|
| 1398 |
+
# Community engagement (from HACC)
|
| 1399 |
+
register_keywords(
|
| 1400 |
+
"applicability_community_engagement",
|
| 1401 |
+
[
|
| 1402 |
+
"community engagement",
|
| 1403 |
+
"public input",
|
| 1404 |
+
"stakeholder",
|
| 1405 |
+
"outreach",
|
| 1406 |
+
"consultation",
|
| 1407 |
+
"community participation",
|
| 1408 |
+
"public comment",
|
| 1409 |
+
"engagement plan",
|
| 1410 |
+
"community benefits",
|
| 1411 |
+
],
|
| 1412 |
+
complaint_type="dei",
|
| 1413 |
+
)
|
| 1414 |
+
|
| 1415 |
+
# DEI-specific legal patterns
|
| 1416 |
+
# DEI-specific legal patterns (unique patterns only, avoiding duplicates)
|
| 1417 |
+
# Note: Common patterns like "discrimination", "fair housing", etc. are already
|
| 1418 |
+
# registered in other categories and will be loaded by LegalPatternExtractor
|
| 1419 |
+
register_legal_terms(
|
| 1420 |
+
"dei",
|
| 1421 |
+
[
|
| 1422 |
+
# DEI Core Terms (unique to DEI taxonomy)
|
| 1423 |
+
r"\b(diversity|diverse)\b",
|
| 1424 |
+
r"\b(equity|equitable)\b",
|
| 1425 |
+
r"\b(inclusion|inclusive)\b",
|
| 1426 |
+
r"\b(underrepresented minorit(y|ies))\b",
|
| 1427 |
+
r"\b(underserved communit(y|ies))\b",
|
| 1428 |
+
r"\b(disadvantaged business enterprise|DBE)\b",
|
| 1429 |
+
r"\b(minority[- ]owned business|MBE)\b",
|
| 1430 |
+
r"\b(wom[ae]n[- ]owned business|WBE)\b",
|
| 1431 |
+
r"\b(MWESB|ESB)\b",
|
| 1432 |
+
r"\b(affirmative action)\b",
|
| 1433 |
+
r"\b(cultural competen(cy|ce))\b",
|
| 1434 |
+
r"\b(implicit bias|unconscious bias)\b",
|
| 1435 |
+
r"\b(racial equity)\b",
|
| 1436 |
+
r"\b(social equity)\b",
|
| 1437 |
+
r"\b(environmental justice)\b",
|
| 1438 |
+
r"\b(historically underrepresented)\b",
|
| 1439 |
+
r"\b(marginalized communit(y|ies))\b",
|
| 1440 |
+
r"\b(BIPOC)\b",
|
| 1441 |
+
r"\b(equal opportunity)\b",
|
| 1442 |
+
r"\b(Section 3)\b",
|
| 1443 |
+
r"\b(community benefit(s)?)\b",
|
| 1444 |
+
r"\b(socially disadvantaged)\b",
|
| 1445 |
+
r"\b(economically disadvantaged)\b",
|
| 1446 |
+
r"\b(racial justice)\b",
|
| 1447 |
+
r"\b(social justice)\b",
|
| 1448 |
+
r"\b(people of color)\b",
|
| 1449 |
+
r"\b(underserved|underserviced)\b",
|
| 1450 |
+
r"\b(equity (lens|framework|initiative))\b",
|
| 1451 |
+
r"\b(cultural (humility|responsiveness))\b",
|
| 1452 |
+
r"\b(justice[- ]centered|justice[- ]oriented)\b",
|
| 1453 |
+
r"\b(anti[- ]racist)\b",
|
| 1454 |
+
r"\b(lived experience)\b",
|
| 1455 |
+
r"\b(safe space)\b",
|
| 1456 |
+
r"\b(first[- ]generation)\b",
|
| 1457 |
+
],
|
| 1458 |
+
)
|
| 1459 |
+
|
| 1460 |
+
|
| 1461 |
+
def get_registered_types() -> List[str]:
|
| 1462 |
+
"""
|
| 1463 |
+
Get all registered complaint types.
|
| 1464 |
+
|
| 1465 |
+
Returns:
|
| 1466 |
+
List of complaint type names
|
| 1467 |
+
"""
|
| 1468 |
+
from .keywords import _global_registry
|
| 1469 |
+
|
| 1470 |
+
return _global_registry.get_complaint_types()
|
| 1471 |
+
|
| 1472 |
+
|
| 1473 |
+
def get_complaint_type(complaint_type: str) -> Optional[Dict[str, Any]]:
|
| 1474 |
+
"""Return basic metadata for a registered complaint type.
|
| 1475 |
+
|
| 1476 |
+
This is used by mediator hooks (e.g., LegalCorpusRAGHook) to retrieve
|
| 1477 |
+
type-scoped keyword categories.
|
| 1478 |
+
|
| 1479 |
+
Returns None when the type is unknown.
|
| 1480 |
+
"""
|
| 1481 |
+
|
| 1482 |
+
if not isinstance(complaint_type, str):
|
| 1483 |
+
return None
|
| 1484 |
+
|
| 1485 |
+
name = complaint_type.strip()
|
| 1486 |
+
if not name:
|
| 1487 |
+
return None
|
| 1488 |
+
|
| 1489 |
+
from .keywords import _global_registry
|
| 1490 |
+
|
| 1491 |
+
if name not in _global_registry.get_complaint_types():
|
| 1492 |
+
return None
|
| 1493 |
+
|
| 1494 |
+
categories = _global_registry.get_all_categories(name)
|
| 1495 |
+
primary_category = "complaint"
|
| 1496 |
+
if categories:
|
| 1497 |
+
primary_category = "complaint" if "complaint" in categories else categories[0]
|
| 1498 |
+
|
| 1499 |
+
return {
|
| 1500 |
+
"name": name,
|
| 1501 |
+
"category": primary_category,
|
| 1502 |
+
"categories": categories,
|
| 1503 |
+
}
|
| 1504 |
+
|
| 1505 |
+
|
| 1506 |
+
# Register default types on module import
|
| 1507 |
+
register_housing_complaint()
|
| 1508 |
+
register_employment_complaint()
|
| 1509 |
+
register_civil_rights_complaint()
|
| 1510 |
+
register_consumer_complaint()
|
| 1511 |
+
register_healthcare_complaint()
|
| 1512 |
+
register_free_speech_complaint()
|
| 1513 |
+
register_immigration_complaint()
|
| 1514 |
+
register_family_law_complaint()
|
| 1515 |
+
register_criminal_defense_complaint()
|
| 1516 |
+
register_tax_law_complaint()
|
| 1517 |
+
register_intellectual_property_complaint()
|
| 1518 |
+
register_environmental_law_complaint()
|
| 1519 |
+
register_probate_complaint() # Probate and estate law
|
| 1520 |
+
register_dei_complaint() # DEI taxonomy (formerly hacc_integration)
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/common/legal_patterns.py
ADDED
|
@@ -0,0 +1,489 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 1 |
+
"""
|
| 2 |
+
Legal Pattern Extraction for Complaints
|
| 3 |
+
|
| 4 |
+
Extensible framework for extracting complaint-relevant legal provisions from text.
|
| 5 |
+
Uses a registry pattern to allow adding new complaint types and legal term patterns.
|
| 6 |
+
|
| 7 |
+
This module includes default patterns for:
|
| 8 |
+
- Fair housing law
|
| 9 |
+
- Employment discrimination
|
| 10 |
+
- Civil rights violations
|
| 11 |
+
- Protected class references
|
| 12 |
+
- Legal remedies and relief
|
| 13 |
+
|
| 14 |
+
New complaint types can be added by registering additional patterns.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import re
|
| 18 |
+
from typing import List, Dict, Optional, Any
|
| 19 |
+
from datetime import datetime
|
| 20 |
+
from .base import BaseLegalPatternExtractor
|
| 21 |
+
|
| 22 |
+
# Constants for complaint categorization
|
| 23 |
+
# Minimum keyword matches required to categorize a complaint as a specific type
|
| 24 |
+
DEFAULT_KEYWORD_MATCH_THRESHOLD = 2
|
| 25 |
+
# Minimum number of keywords a type must have before applying the threshold
|
| 26 |
+
# (types with fewer keywords use threshold of 1 to avoid being too strict)
|
| 27 |
+
MIN_KEYWORDS_FOR_THRESHOLD = 10
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# Registry for legal term patterns by category
|
| 31 |
+
LEGAL_TERMS_REGISTRY: Dict[str, List[str]] = {}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def register_legal_terms(category: str, patterns: List[str]) -> None:
|
| 35 |
+
"""
|
| 36 |
+
Register legal term patterns for a category.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
category: Category name (e.g., 'housing', 'employment', 'civil_rights')
|
| 40 |
+
patterns: List of regex patterns
|
| 41 |
+
"""
|
| 42 |
+
if category not in LEGAL_TERMS_REGISTRY:
|
| 43 |
+
LEGAL_TERMS_REGISTRY[category] = []
|
| 44 |
+
LEGAL_TERMS_REGISTRY[category].extend(patterns)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def get_legal_terms(category: Optional[str] = None) -> List[str]:
|
| 48 |
+
"""
|
| 49 |
+
Get legal term patterns for a category.
|
| 50 |
+
|
| 51 |
+
Args:
|
| 52 |
+
category: Category name, or None for all patterns
|
| 53 |
+
|
| 54 |
+
Returns:
|
| 55 |
+
List of regex patterns
|
| 56 |
+
"""
|
| 57 |
+
if category:
|
| 58 |
+
return LEGAL_TERMS_REGISTRY.get(category, [])
|
| 59 |
+
else:
|
| 60 |
+
# Return all patterns from all categories
|
| 61 |
+
all_patterns = []
|
| 62 |
+
for patterns in LEGAL_TERMS_REGISTRY.values():
|
| 63 |
+
all_patterns.extend(patterns)
|
| 64 |
+
return all_patterns
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# Default legal term patterns (maintained for backward compatibility)
|
| 68 |
+
COMPLAINT_LEGAL_TERMS = [
|
| 69 |
+
# Fair Housing & Discrimination
|
| 70 |
+
r"\b(fair housing)\b",
|
| 71 |
+
r"\b(Fair Housing Act)\b",
|
| 72 |
+
r"\b(FHA)\b",
|
| 73 |
+
r"\b(discrimination)\b",
|
| 74 |
+
r"\b(discriminate|discriminatory)\b",
|
| 75 |
+
r"\b(harassment)\b",
|
| 76 |
+
r"\b(retaliation|retaliate)\b",
|
| 77 |
+
r"\b(hostile environment)\b",
|
| 78 |
+
# Reasonable Accommodation
|
| 79 |
+
r"\b(reasonable accommodation)\b",
|
| 80 |
+
r"\b(reasonable modification)\b",
|
| 81 |
+
r"\b(disability accommodation)\b",
|
| 82 |
+
r"\b(auxiliary aids?)\b",
|
| 83 |
+
# Protected Classes
|
| 84 |
+
r"\b(protected class(es)?)\b",
|
| 85 |
+
r"\b(familial status)\b",
|
| 86 |
+
r"\b(disability|disabled)\b",
|
| 87 |
+
r"\b(race|racial)\b",
|
| 88 |
+
r"\b(color)\b",
|
| 89 |
+
r"\b(national origin)\b",
|
| 90 |
+
r"\b(religion|religious)\b",
|
| 91 |
+
r"\b(sex|gender)\b",
|
| 92 |
+
r"\b(sexual orientation)\b",
|
| 93 |
+
r"\b(gender identity)\b",
|
| 94 |
+
r"\b(source of income)\b",
|
| 95 |
+
r"\b(marital status)\b",
|
| 96 |
+
# Legal Impact
|
| 97 |
+
r"\b(disparate (impact|treatment))\b",
|
| 98 |
+
r"\b(intentional discrimination)\b",
|
| 99 |
+
r"\b(unintentional discrimination)\b",
|
| 100 |
+
r"\b(discriminatory effect)\b",
|
| 101 |
+
r"\b(adverse (impact|effect))\b",
|
| 102 |
+
# Housing Specific
|
| 103 |
+
r"\b(Section 8)\b",
|
| 104 |
+
r"\b(Housing Choice Voucher)\b",
|
| 105 |
+
r"\b(public housing)\b",
|
| 106 |
+
r"\b(affordable housing)\b",
|
| 107 |
+
r"\b(tenant|tenancy)\b",
|
| 108 |
+
r"\b(landlord)\b",
|
| 109 |
+
r"\b(lease|rental agreement)\b",
|
| 110 |
+
r"\b(eviction)\b",
|
| 111 |
+
r"\b(housing authority)\b",
|
| 112 |
+
# Employment Specific
|
| 113 |
+
r"\b(Title VII)\b",
|
| 114 |
+
r"\b(ADA)\b",
|
| 115 |
+
r"\b(Americans with Disabilities Act)\b",
|
| 116 |
+
r"\b(ADEA)\b",
|
| 117 |
+
r"\b(Age Discrimination in Employment Act)\b",
|
| 118 |
+
r"\b(FMLA)\b",
|
| 119 |
+
r"\b(Family and Medical Leave Act)\b",
|
| 120 |
+
r"\b(EEOC)\b",
|
| 121 |
+
r"\b(Equal Employment Opportunity)\b",
|
| 122 |
+
# Federal Law Citations
|
| 123 |
+
r"\b(42 U\.S\.C\.)\b",
|
| 124 |
+
r"\b(29 U\.S\.C\.)\b",
|
| 125 |
+
r"\b(C\.F\.R\.)\b",
|
| 126 |
+
r"\b(Federal Register)\b",
|
| 127 |
+
# Remedies & Relief
|
| 128 |
+
r"\b(damages)\b",
|
| 129 |
+
r"\b(compensatory damages)\b",
|
| 130 |
+
r"\b(punitive damages)\b",
|
| 131 |
+
r"\b(injunctive relief)\b",
|
| 132 |
+
r"\b(declaratory relief)\b",
|
| 133 |
+
r"\b(attorney('s)? fees)\b",
|
| 134 |
+
r"\b(equitable relief)\b",
|
| 135 |
+
r"\b(monetary relief)\b",
|
| 136 |
+
# Civil Rights
|
| 137 |
+
r"\b(civil rights)\b",
|
| 138 |
+
r"\b(equal protection)\b",
|
| 139 |
+
r"\b(due process)\b",
|
| 140 |
+
r"\b(constitutional (right|violation))\b",
|
| 141 |
+
# Complaint-Specific Terms
|
| 142 |
+
r"\b(complainant)\b",
|
| 143 |
+
r"\b(respondent)\b",
|
| 144 |
+
r"\b(charging party)\b",
|
| 145 |
+
r"\b(aggrieved person)\b",
|
| 146 |
+
r"\b(prima facie case)\b",
|
| 147 |
+
r"\b(burden of proof)\b",
|
| 148 |
+
r"\b(preponderance of evidence)\b",
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
# Register default patterns in categories
|
| 152 |
+
register_legal_terms(
|
| 153 |
+
"housing",
|
| 154 |
+
[
|
| 155 |
+
r"\b(fair housing)\b",
|
| 156 |
+
r"\b(Fair Housing Act)\b",
|
| 157 |
+
r"\b(FHA)\b",
|
| 158 |
+
r"\b(Section 8)\b",
|
| 159 |
+
r"\b(Housing Choice Voucher)\b",
|
| 160 |
+
r"\b(public housing)\b",
|
| 161 |
+
r"\b(affordable housing)\b",
|
| 162 |
+
r"\b(tenant|tenancy)\b",
|
| 163 |
+
r"\b(landlord)\b",
|
| 164 |
+
r"\b(lease|rental agreement)\b",
|
| 165 |
+
r"\b(eviction)\b",
|
| 166 |
+
r"\b(housing authority)\b",
|
| 167 |
+
],
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
register_legal_terms(
|
| 171 |
+
"employment",
|
| 172 |
+
[
|
| 173 |
+
r"\b(Title VII)\b",
|
| 174 |
+
r"\b(ADA)\b",
|
| 175 |
+
r"\b(Americans with Disabilities Act)\b",
|
| 176 |
+
r"\b(ADEA)\b",
|
| 177 |
+
r"\b(Age Discrimination in Employment Act)\b",
|
| 178 |
+
r"\b(FMLA)\b",
|
| 179 |
+
r"\b(Family and Medical Leave Act)\b",
|
| 180 |
+
r"\b(EEOC)\b",
|
| 181 |
+
r"\b(Equal Employment Opportunity)\b",
|
| 182 |
+
],
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
register_legal_terms(
|
| 186 |
+
"discrimination",
|
| 187 |
+
[
|
| 188 |
+
r"\b(discrimination)\b",
|
| 189 |
+
r"\b(discriminate|discriminatory)\b",
|
| 190 |
+
r"\b(harassment)\b",
|
| 191 |
+
r"\b(retaliation|retaliate)\b",
|
| 192 |
+
r"\b(hostile environment)\b",
|
| 193 |
+
r"\b(disparate (impact|treatment))\b",
|
| 194 |
+
r"\b(intentional discrimination)\b",
|
| 195 |
+
r"\b(unintentional discrimination)\b",
|
| 196 |
+
r"\b(discriminatory effect)\b",
|
| 197 |
+
r"\b(adverse (impact|effect))\b",
|
| 198 |
+
],
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
register_legal_terms(
|
| 202 |
+
"protected_classes",
|
| 203 |
+
[
|
| 204 |
+
r"\b(protected class(es)?)\b",
|
| 205 |
+
r"\b(familial status)\b",
|
| 206 |
+
r"\b(disability|disabled)\b",
|
| 207 |
+
r"\b(race|racial)\b",
|
| 208 |
+
r"\b(color)\b",
|
| 209 |
+
r"\b(national origin)\b",
|
| 210 |
+
r"\b(religion|religious)\b",
|
| 211 |
+
r"\b(sex|gender)\b",
|
| 212 |
+
r"\b(sexual orientation)\b",
|
| 213 |
+
r"\b(gender identity)\b",
|
| 214 |
+
r"\b(source of income)\b",
|
| 215 |
+
r"\b(marital status)\b",
|
| 216 |
+
],
|
| 217 |
+
)
|
| 218 |
+
|
| 219 |
+
register_legal_terms(
|
| 220 |
+
"accommodations",
|
| 221 |
+
[
|
| 222 |
+
r"\b(reasonable accommodation)\b",
|
| 223 |
+
r"\b(reasonable modification)\b",
|
| 224 |
+
r"\b(disability accommodation)\b",
|
| 225 |
+
r"\b(auxiliary aids?)\b",
|
| 226 |
+
],
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
register_legal_terms(
|
| 230 |
+
"remedies",
|
| 231 |
+
[
|
| 232 |
+
r"\b(damages)\b",
|
| 233 |
+
r"\b(compensatory damages)\b",
|
| 234 |
+
r"\b(punitive damages)\b",
|
| 235 |
+
r"\b(injunctive relief)\b",
|
| 236 |
+
r"\b(declaratory relief)\b",
|
| 237 |
+
r"\b(attorney('s)? fees)\b",
|
| 238 |
+
r"\b(equitable relief)\b",
|
| 239 |
+
r"\b(monetary relief)\b",
|
| 240 |
+
],
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
register_legal_terms(
|
| 244 |
+
"civil_rights",
|
| 245 |
+
[
|
| 246 |
+
r"\b(civil rights)\b",
|
| 247 |
+
r"\b(equal protection)\b",
|
| 248 |
+
r"\b(due process)\b",
|
| 249 |
+
r"\b(constitutional (right|violation))\b",
|
| 250 |
+
],
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
register_legal_terms(
|
| 254 |
+
"federal_law",
|
| 255 |
+
[
|
| 256 |
+
r"\b(42 U\.S\.C\.)\b",
|
| 257 |
+
r"\b(29 U\.S\.C\.)\b",
|
| 258 |
+
r"\b(C\.F\.R\.)\b",
|
| 259 |
+
r"\b(Federal Register)\b",
|
| 260 |
+
],
|
| 261 |
+
)
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
class LegalPatternExtractor(BaseLegalPatternExtractor):
|
| 265 |
+
"""
|
| 266 |
+
Extensible legal pattern extractor for complaints.
|
| 267 |
+
|
| 268 |
+
This class extracts legal provisions using regex patterns organized by category.
|
| 269 |
+
New complaint types can be added by registering additional patterns using
|
| 270 |
+
register_legal_terms().
|
| 271 |
+
|
| 272 |
+
Example:
|
| 273 |
+
>>> # Use default patterns
|
| 274 |
+
>>> extractor = LegalPatternExtractor()
|
| 275 |
+
>>> result = extractor.extract_provisions(document_text)
|
| 276 |
+
|
| 277 |
+
>>> # Add custom patterns for consumer protection
|
| 278 |
+
>>> register_legal_terms('consumer', [r'\b(consumer protection)\b'])
|
| 279 |
+
>>> extractor = LegalPatternExtractor(categories=['consumer', 'civil_rights'])
|
| 280 |
+
"""
|
| 281 |
+
|
| 282 |
+
def __init__(
|
| 283 |
+
self, categories: Optional[List[str]] = None, custom_patterns: Optional[List[str]] = None
|
| 284 |
+
):
|
| 285 |
+
"""
|
| 286 |
+
Initialize the legal pattern extractor.
|
| 287 |
+
|
| 288 |
+
Args:
|
| 289 |
+
categories: List of pattern categories to use (None = all registered)
|
| 290 |
+
custom_patterns: Optional additional regex patterns to include
|
| 291 |
+
"""
|
| 292 |
+
# Get patterns from specified categories or all if None
|
| 293 |
+
if categories:
|
| 294 |
+
patterns = []
|
| 295 |
+
for category in categories:
|
| 296 |
+
patterns.extend(get_legal_terms(category))
|
| 297 |
+
else:
|
| 298 |
+
patterns = get_legal_terms() # All patterns
|
| 299 |
+
|
| 300 |
+
# Add backwards compatibility with COMPLAINT_LEGAL_TERMS
|
| 301 |
+
if not patterns:
|
| 302 |
+
patterns = COMPLAINT_LEGAL_TERMS
|
| 303 |
+
|
| 304 |
+
self.patterns = [re.compile(p, re.IGNORECASE) for p in patterns]
|
| 305 |
+
|
| 306 |
+
if custom_patterns:
|
| 307 |
+
self.patterns.extend([re.compile(p, re.IGNORECASE) for p in custom_patterns])
|
| 308 |
+
|
| 309 |
+
def extract_provisions(self, text: str, context_chars: int = 200) -> Dict[str, Any]:
|
| 310 |
+
"""
|
| 311 |
+
Extract legal provisions with context from text.
|
| 312 |
+
|
| 313 |
+
Args:
|
| 314 |
+
text: Text to analyze
|
| 315 |
+
context_chars: Number of characters to include before/after match
|
| 316 |
+
|
| 317 |
+
Returns:
|
| 318 |
+
Dictionary containing:
|
| 319 |
+
- provisions: List of found provisions with context
|
| 320 |
+
- terms_found: Set of unique legal terms found
|
| 321 |
+
- citation_count: Number of legal citations found
|
| 322 |
+
- timestamp: When analysis was performed
|
| 323 |
+
"""
|
| 324 |
+
provisions = []
|
| 325 |
+
terms_found = set()
|
| 326 |
+
|
| 327 |
+
for pattern in self.patterns:
|
| 328 |
+
for match in pattern.finditer(text):
|
| 329 |
+
# Extract context around the match
|
| 330 |
+
start = max(0, match.start() - context_chars)
|
| 331 |
+
end = min(len(text), match.end() + context_chars)
|
| 332 |
+
context = text[start:end]
|
| 333 |
+
|
| 334 |
+
# Clean up context (remove extra whitespace)
|
| 335 |
+
context = " ".join(context.split())
|
| 336 |
+
|
| 337 |
+
term = match.group(0)
|
| 338 |
+
terms_found.add(term.lower())
|
| 339 |
+
|
| 340 |
+
provisions.append(
|
| 341 |
+
{
|
| 342 |
+
"term": term,
|
| 343 |
+
"context": context,
|
| 344 |
+
"position": match.start(),
|
| 345 |
+
"pattern": pattern.pattern,
|
| 346 |
+
}
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
# Sort by position in document
|
| 350 |
+
provisions.sort(key=lambda x: x["position"])
|
| 351 |
+
|
| 352 |
+
return {
|
| 353 |
+
"provisions": provisions,
|
| 354 |
+
"terms_found": list(terms_found),
|
| 355 |
+
"provision_count": len(provisions),
|
| 356 |
+
"unique_terms": len(terms_found),
|
| 357 |
+
"timestamp": datetime.now().isoformat(),
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
def extract_citations(self, text: str) -> List[Dict[str, str]]:
|
| 361 |
+
"""
|
| 362 |
+
Extract legal citations (e.g., 42 U.S.C. § 3604).
|
| 363 |
+
|
| 364 |
+
Args:
|
| 365 |
+
text: Text to analyze
|
| 366 |
+
|
| 367 |
+
Returns:
|
| 368 |
+
List of found citations with metadata
|
| 369 |
+
"""
|
| 370 |
+
citation_patterns = [
|
| 371 |
+
# Federal statutes (e.g., 42 U.S.C. § 3604)
|
| 372 |
+
(r"\b\d+\s+U\.S\.C\.\s+§\s*\d+[a-z]?(?:\(\w+\))?", "federal_statute"),
|
| 373 |
+
# Code of Federal Regulations (e.g., 24 C.F.R. § 100.70)
|
| 374 |
+
(r"\b\d+\s+C\.F\.R\.\s+§\s*\d+\.\d+", "cfr"),
|
| 375 |
+
# State statutes (e.g., Cal. Civ. Code § 51)
|
| 376 |
+
(r"\b[A-Z][a-z]+\.\s+[A-Z][a-z]+\.\s+Code\s+§\s*\d+", "state_statute"),
|
| 377 |
+
# Case citations (simplified)
|
| 378 |
+
(r"\b\d+\s+F\.\s*(?:2d|3d|Supp\.)?\s+\d+", "federal_case"),
|
| 379 |
+
]
|
| 380 |
+
|
| 381 |
+
citations = []
|
| 382 |
+
for pattern, citation_type in citation_patterns:
|
| 383 |
+
regex = re.compile(pattern, re.IGNORECASE)
|
| 384 |
+
for match in regex.finditer(text):
|
| 385 |
+
citations.append(
|
| 386 |
+
{"citation": match.group(0), "type": citation_type, "position": match.start()}
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
return citations
|
| 390 |
+
|
| 391 |
+
def categorize_complaint_type(self, text: str) -> List[str]:
|
| 392 |
+
"""
|
| 393 |
+
Categorize the complaint based on legal terms found.
|
| 394 |
+
|
| 395 |
+
Uses keyword matching with configurable thresholds to identify applicable
|
| 396 |
+
complaint categories. Requires multiple keyword matches to avoid false positives.
|
| 397 |
+
|
| 398 |
+
Args:
|
| 399 |
+
text: Text to analyze
|
| 400 |
+
|
| 401 |
+
Returns:
|
| 402 |
+
List of applicable complaint categories
|
| 403 |
+
"""
|
| 404 |
+
# Import here to avoid circular dependency issues during module initialization
|
| 405 |
+
from .keywords import get_type_specific_keywords, _global_registry
|
| 406 |
+
|
| 407 |
+
text_lower = text.lower()
|
| 408 |
+
categories = []
|
| 409 |
+
|
| 410 |
+
# Check each registered complaint type
|
| 411 |
+
complaint_types = _global_registry.get_complaint_types()
|
| 412 |
+
|
| 413 |
+
for complaint_type in complaint_types:
|
| 414 |
+
# Get type-specific keywords (excluding global keywords)
|
| 415 |
+
type_keywords = get_type_specific_keywords("complaint", complaint_type)
|
| 416 |
+
|
| 417 |
+
# Check if any type-specific keywords appear in text
|
| 418 |
+
# Use a threshold to avoid false positives
|
| 419 |
+
matches = sum(1 for kw in type_keywords if kw.lower() in text_lower)
|
| 420 |
+
|
| 421 |
+
# If at least threshold keywords match, include this type
|
| 422 |
+
# Use lower threshold for types with fewer keywords to avoid being too strict
|
| 423 |
+
threshold = (
|
| 424 |
+
DEFAULT_KEYWORD_MATCH_THRESHOLD
|
| 425 |
+
if len(type_keywords) > MIN_KEYWORDS_FOR_THRESHOLD
|
| 426 |
+
else 1
|
| 427 |
+
)
|
| 428 |
+
if matches >= threshold:
|
| 429 |
+
categories.append(complaint_type)
|
| 430 |
+
|
| 431 |
+
# Legacy categorization for backward compatibility
|
| 432 |
+
# Disability
|
| 433 |
+
if (
|
| 434 |
+
"disability" in text_lower
|
| 435 |
+
or "ada" in text_lower
|
| 436 |
+
or "reasonable accommodation" in text_lower
|
| 437 |
+
):
|
| 438 |
+
if "disability" not in categories:
|
| 439 |
+
categories.append("disability")
|
| 440 |
+
|
| 441 |
+
# Discrimination type
|
| 442 |
+
if "discrimination" in text_lower or "discriminate" in text_lower:
|
| 443 |
+
if "discrimination" not in categories:
|
| 444 |
+
categories.append("discrimination")
|
| 445 |
+
|
| 446 |
+
# Harassment
|
| 447 |
+
if "harassment" in text_lower or "hostile environment" in text_lower:
|
| 448 |
+
if "harassment" not in categories:
|
| 449 |
+
categories.append("harassment")
|
| 450 |
+
|
| 451 |
+
# Retaliation
|
| 452 |
+
if "retaliation" in text_lower or "retaliate" in text_lower:
|
| 453 |
+
if "retaliation" not in categories:
|
| 454 |
+
categories.append("retaliation")
|
| 455 |
+
|
| 456 |
+
return categories or ["general"]
|
| 457 |
+
|
| 458 |
+
def find_protected_classes(self, text: str) -> List[str]:
|
| 459 |
+
"""
|
| 460 |
+
Identify protected classes mentioned in the text.
|
| 461 |
+
|
| 462 |
+
Args:
|
| 463 |
+
text: Text to analyze
|
| 464 |
+
|
| 465 |
+
Returns:
|
| 466 |
+
List of protected classes found
|
| 467 |
+
"""
|
| 468 |
+
protected_classes = {
|
| 469 |
+
"race": ["race", "racial"],
|
| 470 |
+
"color": ["color"],
|
| 471 |
+
"national_origin": ["national origin", "nationality"],
|
| 472 |
+
"religion": ["religion", "religious", "creed"],
|
| 473 |
+
"sex": ["sex", "gender"],
|
| 474 |
+
"familial_status": ["familial status", "family status", "children"],
|
| 475 |
+
"disability": ["disability", "disabled", "handicap"],
|
| 476 |
+
"age": ["age", "elderly", "senior"],
|
| 477 |
+
"sexual_orientation": ["sexual orientation", "lgbt", "gay", "lesbian"],
|
| 478 |
+
"gender_identity": ["gender identity", "transgender"],
|
| 479 |
+
"source_of_income": ["source of income", "section 8", "voucher"],
|
| 480 |
+
}
|
| 481 |
+
|
| 482 |
+
text_lower = text.lower()
|
| 483 |
+
found_classes = []
|
| 484 |
+
|
| 485 |
+
for class_name, keywords in protected_classes.items():
|
| 486 |
+
if any(keyword in text_lower for keyword in keywords):
|
| 487 |
+
found_classes.append(class_name)
|
| 488 |
+
|
| 489 |
+
return found_classes
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/civil_rights_tree.json
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "civil_rights",
|
| 3 |
+
"category": "civil_rights",
|
| 4 |
+
"description": "Decision tree for civil rights complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2",
|
| 8 |
+
"q3"
|
| 9 |
+
],
|
| 10 |
+
"questions": {
|
| 11 |
+
"q1": {
|
| 12 |
+
"id": "q1",
|
| 13 |
+
"question": "Who violated your civil rights?",
|
| 14 |
+
"field_name": "violating_party",
|
| 15 |
+
"required": true,
|
| 16 |
+
"depends_on": [],
|
| 17 |
+
"follow_ups": [],
|
| 18 |
+
"keywords": [
|
| 19 |
+
"police",
|
| 20 |
+
"government",
|
| 21 |
+
"official",
|
| 22 |
+
"agency"
|
| 23 |
+
]
|
| 24 |
+
},
|
| 25 |
+
"q2": {
|
| 26 |
+
"id": "q2",
|
| 27 |
+
"question": "What right was violated?",
|
| 28 |
+
"field_name": "protected_right",
|
| 29 |
+
"required": true,
|
| 30 |
+
"depends_on": [],
|
| 31 |
+
"follow_ups": [],
|
| 32 |
+
"keywords": [
|
| 33 |
+
"speech",
|
| 34 |
+
"assembly",
|
| 35 |
+
"religion",
|
| 36 |
+
"privacy",
|
| 37 |
+
"due process"
|
| 38 |
+
]
|
| 39 |
+
},
|
| 40 |
+
"q3": {
|
| 41 |
+
"id": "q3",
|
| 42 |
+
"question": "What type of violation occurred?",
|
| 43 |
+
"field_name": "violation_type",
|
| 44 |
+
"required": true,
|
| 45 |
+
"depends_on": [
|
| 46 |
+
"protected_right"
|
| 47 |
+
],
|
| 48 |
+
"follow_ups": [],
|
| 49 |
+
"keywords": []
|
| 50 |
+
},
|
| 51 |
+
"q4": {
|
| 52 |
+
"id": "q4",
|
| 53 |
+
"question": "Please describe the incident in detail.",
|
| 54 |
+
"field_name": "incident_description",
|
| 55 |
+
"required": true,
|
| 56 |
+
"depends_on": [
|
| 57 |
+
"violation_type"
|
| 58 |
+
],
|
| 59 |
+
"follow_ups": [],
|
| 60 |
+
"keywords": []
|
| 61 |
+
},
|
| 62 |
+
"q5": {
|
| 63 |
+
"id": "q5",
|
| 64 |
+
"question": "When did this occur?",
|
| 65 |
+
"field_name": "date_of_incident",
|
| 66 |
+
"required": true,
|
| 67 |
+
"depends_on": [
|
| 68 |
+
"incident_description"
|
| 69 |
+
],
|
| 70 |
+
"follow_ups": [],
|
| 71 |
+
"keywords": []
|
| 72 |
+
},
|
| 73 |
+
"q6": {
|
| 74 |
+
"id": "q6",
|
| 75 |
+
"question": "What damages did you suffer?",
|
| 76 |
+
"field_name": "damages",
|
| 77 |
+
"required": false,
|
| 78 |
+
"depends_on": [
|
| 79 |
+
"incident_description"
|
| 80 |
+
],
|
| 81 |
+
"follow_ups": [],
|
| 82 |
+
"keywords": []
|
| 83 |
+
}
|
| 84 |
+
},
|
| 85 |
+
"required_fields": [
|
| 86 |
+
"protected_right",
|
| 87 |
+
"date_of_incident",
|
| 88 |
+
"violating_party",
|
| 89 |
+
"incident_description",
|
| 90 |
+
"violation_type"
|
| 91 |
+
],
|
| 92 |
+
"optional_fields": [
|
| 93 |
+
"damages"
|
| 94 |
+
]
|
| 95 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/consumer_tree.json
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "consumer",
|
| 3 |
+
"category": "consumer",
|
| 4 |
+
"description": "Decision tree for consumer complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2",
|
| 8 |
+
"q3"
|
| 9 |
+
],
|
| 10 |
+
"questions": {
|
| 11 |
+
"q1": {
|
| 12 |
+
"id": "q1",
|
| 13 |
+
"question": "What is the name of the business?",
|
| 14 |
+
"field_name": "business_name",
|
| 15 |
+
"required": true,
|
| 16 |
+
"depends_on": [],
|
| 17 |
+
"follow_ups": [],
|
| 18 |
+
"keywords": []
|
| 19 |
+
},
|
| 20 |
+
"q2": {
|
| 21 |
+
"id": "q2",
|
| 22 |
+
"question": "What product or service did you purchase?",
|
| 23 |
+
"field_name": "product_or_service",
|
| 24 |
+
"required": true,
|
| 25 |
+
"depends_on": [],
|
| 26 |
+
"follow_ups": [],
|
| 27 |
+
"keywords": []
|
| 28 |
+
},
|
| 29 |
+
"q3": {
|
| 30 |
+
"id": "q3",
|
| 31 |
+
"question": "What type of problem occurred?",
|
| 32 |
+
"field_name": "fraud_type",
|
| 33 |
+
"required": true,
|
| 34 |
+
"depends_on": [],
|
| 35 |
+
"follow_ups": [],
|
| 36 |
+
"keywords": [
|
| 37 |
+
"fraud",
|
| 38 |
+
"misrepresentation",
|
| 39 |
+
"defective",
|
| 40 |
+
"breach"
|
| 41 |
+
]
|
| 42 |
+
},
|
| 43 |
+
"q4": {
|
| 44 |
+
"id": "q4",
|
| 45 |
+
"question": "Please describe the issue in detail.",
|
| 46 |
+
"field_name": "issue_description",
|
| 47 |
+
"required": true,
|
| 48 |
+
"depends_on": [
|
| 49 |
+
"fraud_type"
|
| 50 |
+
],
|
| 51 |
+
"follow_ups": [],
|
| 52 |
+
"keywords": []
|
| 53 |
+
},
|
| 54 |
+
"q5": {
|
| 55 |
+
"id": "q5",
|
| 56 |
+
"question": "When did you make the purchase?",
|
| 57 |
+
"field_name": "date_of_purchase",
|
| 58 |
+
"required": true,
|
| 59 |
+
"depends_on": [],
|
| 60 |
+
"follow_ups": [],
|
| 61 |
+
"keywords": []
|
| 62 |
+
},
|
| 63 |
+
"q6": {
|
| 64 |
+
"id": "q6",
|
| 65 |
+
"question": "How much money did you lose?",
|
| 66 |
+
"field_name": "amount_lost",
|
| 67 |
+
"required": false,
|
| 68 |
+
"depends_on": [
|
| 69 |
+
"issue_description"
|
| 70 |
+
],
|
| 71 |
+
"follow_ups": [],
|
| 72 |
+
"keywords": []
|
| 73 |
+
},
|
| 74 |
+
"q7": {
|
| 75 |
+
"id": "q7",
|
| 76 |
+
"question": "Have you tried to resolve this with the business?",
|
| 77 |
+
"field_name": "attempts_to_resolve",
|
| 78 |
+
"required": false,
|
| 79 |
+
"depends_on": [
|
| 80 |
+
"issue_description"
|
| 81 |
+
],
|
| 82 |
+
"follow_ups": [],
|
| 83 |
+
"keywords": []
|
| 84 |
+
}
|
| 85 |
+
},
|
| 86 |
+
"required_fields": [
|
| 87 |
+
"issue_description",
|
| 88 |
+
"date_of_purchase",
|
| 89 |
+
"business_name",
|
| 90 |
+
"product_or_service",
|
| 91 |
+
"fraud_type"
|
| 92 |
+
],
|
| 93 |
+
"optional_fields": [
|
| 94 |
+
"amount_lost",
|
| 95 |
+
"attempts_to_resolve"
|
| 96 |
+
]
|
| 97 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/criminal_defense_tree.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "criminal_defense",
|
| 3 |
+
"category": "criminal",
|
| 4 |
+
"description": "Decision tree for criminal defense complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Which law enforcement agency was involved?",
|
| 13 |
+
"field_name": "law_enforcement_agency",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": []
|
| 18 |
+
},
|
| 19 |
+
"q2": {
|
| 20 |
+
"id": "q2",
|
| 21 |
+
"question": "What type of rights violation occurred?",
|
| 22 |
+
"field_name": "violation_type",
|
| 23 |
+
"required": true,
|
| 24 |
+
"depends_on": [],
|
| 25 |
+
"follow_ups": [],
|
| 26 |
+
"keywords": [
|
| 27 |
+
"search",
|
| 28 |
+
"seizure",
|
| 29 |
+
"miranda",
|
| 30 |
+
"counsel"
|
| 31 |
+
]
|
| 32 |
+
},
|
| 33 |
+
"q3": {
|
| 34 |
+
"id": "q3",
|
| 35 |
+
"question": "When were you arrested?",
|
| 36 |
+
"field_name": "date_of_arrest",
|
| 37 |
+
"required": false,
|
| 38 |
+
"depends_on": [],
|
| 39 |
+
"follow_ups": [],
|
| 40 |
+
"keywords": []
|
| 41 |
+
},
|
| 42 |
+
"q4": {
|
| 43 |
+
"id": "q4",
|
| 44 |
+
"question": "What charges were filed?",
|
| 45 |
+
"field_name": "charges",
|
| 46 |
+
"required": false,
|
| 47 |
+
"depends_on": [],
|
| 48 |
+
"follow_ups": [],
|
| 49 |
+
"keywords": []
|
| 50 |
+
},
|
| 51 |
+
"q5": {
|
| 52 |
+
"id": "q5",
|
| 53 |
+
"question": "Are there any issues with evidence?",
|
| 54 |
+
"field_name": "evidence_issues",
|
| 55 |
+
"required": false,
|
| 56 |
+
"depends_on": [
|
| 57 |
+
"violation_type"
|
| 58 |
+
],
|
| 59 |
+
"follow_ups": [],
|
| 60 |
+
"keywords": []
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"required_fields": [
|
| 64 |
+
"law_enforcement_agency",
|
| 65 |
+
"violation_type"
|
| 66 |
+
],
|
| 67 |
+
"optional_fields": [
|
| 68 |
+
"date_of_arrest",
|
| 69 |
+
"evidence_issues",
|
| 70 |
+
"charges"
|
| 71 |
+
]
|
| 72 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/dei_tree.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "dei",
|
| 3 |
+
"category": "employment",
|
| 4 |
+
"description": "Generic decision tree for dei complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Who is the other party involved?",
|
| 13 |
+
"field_name": "party_name",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": []
|
| 18 |
+
},
|
| 19 |
+
"q2": {
|
| 20 |
+
"id": "q2",
|
| 21 |
+
"question": "Please describe the issue.",
|
| 22 |
+
"field_name": "issue_description",
|
| 23 |
+
"required": true,
|
| 24 |
+
"depends_on": [],
|
| 25 |
+
"follow_ups": [],
|
| 26 |
+
"keywords": []
|
| 27 |
+
},
|
| 28 |
+
"q3": {
|
| 29 |
+
"id": "q3",
|
| 30 |
+
"question": "When did this occur?",
|
| 31 |
+
"field_name": "date_of_incident",
|
| 32 |
+
"required": true,
|
| 33 |
+
"depends_on": [],
|
| 34 |
+
"follow_ups": [],
|
| 35 |
+
"keywords": []
|
| 36 |
+
},
|
| 37 |
+
"q4": {
|
| 38 |
+
"id": "q4",
|
| 39 |
+
"question": "What damages did you suffer?",
|
| 40 |
+
"field_name": "damages",
|
| 41 |
+
"required": false,
|
| 42 |
+
"depends_on": [],
|
| 43 |
+
"follow_ups": [],
|
| 44 |
+
"keywords": []
|
| 45 |
+
}
|
| 46 |
+
},
|
| 47 |
+
"required_fields": [
|
| 48 |
+
"issue_description",
|
| 49 |
+
"date_of_incident",
|
| 50 |
+
"party_name"
|
| 51 |
+
],
|
| 52 |
+
"optional_fields": [
|
| 53 |
+
"damages"
|
| 54 |
+
]
|
| 55 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/employment_tree.json
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "employment",
|
| 3 |
+
"category": "employment",
|
| 4 |
+
"description": "Decision tree for employment complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2",
|
| 8 |
+
"q3"
|
| 9 |
+
],
|
| 10 |
+
"questions": {
|
| 11 |
+
"q1": {
|
| 12 |
+
"id": "q1",
|
| 13 |
+
"question": "What is the name of your employer?",
|
| 14 |
+
"field_name": "employer_name",
|
| 15 |
+
"required": true,
|
| 16 |
+
"depends_on": [],
|
| 17 |
+
"follow_ups": [],
|
| 18 |
+
"keywords": []
|
| 19 |
+
},
|
| 20 |
+
"q2": {
|
| 21 |
+
"id": "q2",
|
| 22 |
+
"question": "What was/is your position or job title?",
|
| 23 |
+
"field_name": "position",
|
| 24 |
+
"required": true,
|
| 25 |
+
"depends_on": [],
|
| 26 |
+
"follow_ups": [],
|
| 27 |
+
"keywords": []
|
| 28 |
+
},
|
| 29 |
+
"q3": {
|
| 30 |
+
"id": "q3",
|
| 31 |
+
"question": "What type of employment issue are you experiencing?",
|
| 32 |
+
"field_name": "issue_type",
|
| 33 |
+
"required": true,
|
| 34 |
+
"depends_on": [],
|
| 35 |
+
"follow_ups": [],
|
| 36 |
+
"keywords": [
|
| 37 |
+
"discrimination",
|
| 38 |
+
"termination",
|
| 39 |
+
"harassment",
|
| 40 |
+
"wage"
|
| 41 |
+
]
|
| 42 |
+
},
|
| 43 |
+
"q4": {
|
| 44 |
+
"id": "q4",
|
| 45 |
+
"question": "Can you describe what happened in detail?",
|
| 46 |
+
"field_name": "incident_description",
|
| 47 |
+
"required": true,
|
| 48 |
+
"depends_on": [
|
| 49 |
+
"issue_type"
|
| 50 |
+
],
|
| 51 |
+
"follow_ups": [],
|
| 52 |
+
"keywords": []
|
| 53 |
+
},
|
| 54 |
+
"q5": {
|
| 55 |
+
"id": "q5",
|
| 56 |
+
"question": "When did this occur?",
|
| 57 |
+
"field_name": "date_of_incident",
|
| 58 |
+
"required": true,
|
| 59 |
+
"depends_on": [
|
| 60 |
+
"incident_description"
|
| 61 |
+
],
|
| 62 |
+
"follow_ups": [],
|
| 63 |
+
"keywords": []
|
| 64 |
+
},
|
| 65 |
+
"q6": {
|
| 66 |
+
"id": "q6",
|
| 67 |
+
"question": "Did you report this to HR or management?",
|
| 68 |
+
"field_name": "hr_complaints",
|
| 69 |
+
"required": false,
|
| 70 |
+
"depends_on": [
|
| 71 |
+
"incident_description"
|
| 72 |
+
],
|
| 73 |
+
"follow_ups": [],
|
| 74 |
+
"keywords": []
|
| 75 |
+
},
|
| 76 |
+
"q7": {
|
| 77 |
+
"id": "q7",
|
| 78 |
+
"question": "Were there any witnesses?",
|
| 79 |
+
"field_name": "witnesses",
|
| 80 |
+
"required": false,
|
| 81 |
+
"depends_on": [
|
| 82 |
+
"incident_description"
|
| 83 |
+
],
|
| 84 |
+
"follow_ups": [],
|
| 85 |
+
"keywords": []
|
| 86 |
+
},
|
| 87 |
+
"q8": {
|
| 88 |
+
"id": "q8",
|
| 89 |
+
"question": "If this involves discrimination, what protected class are you a member of?",
|
| 90 |
+
"field_name": "protected_class",
|
| 91 |
+
"required": false,
|
| 92 |
+
"depends_on": [
|
| 93 |
+
"issue_type"
|
| 94 |
+
],
|
| 95 |
+
"follow_ups": [],
|
| 96 |
+
"keywords": [
|
| 97 |
+
"race",
|
| 98 |
+
"age",
|
| 99 |
+
"gender",
|
| 100 |
+
"disability",
|
| 101 |
+
"religion"
|
| 102 |
+
]
|
| 103 |
+
},
|
| 104 |
+
"q9": {
|
| 105 |
+
"id": "q9",
|
| 106 |
+
"question": "How long were you employed there?",
|
| 107 |
+
"field_name": "years_employed",
|
| 108 |
+
"required": false,
|
| 109 |
+
"depends_on": [
|
| 110 |
+
"employer_name"
|
| 111 |
+
],
|
| 112 |
+
"follow_ups": [],
|
| 113 |
+
"keywords": []
|
| 114 |
+
}
|
| 115 |
+
},
|
| 116 |
+
"required_fields": [
|
| 117 |
+
"issue_type",
|
| 118 |
+
"date_of_incident",
|
| 119 |
+
"incident_description",
|
| 120 |
+
"position",
|
| 121 |
+
"employer_name"
|
| 122 |
+
],
|
| 123 |
+
"optional_fields": [
|
| 124 |
+
"witnesses",
|
| 125 |
+
"hr_complaints",
|
| 126 |
+
"protected_class",
|
| 127 |
+
"years_employed"
|
| 128 |
+
]
|
| 129 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/environmental_law_tree.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "environmental_law",
|
| 3 |
+
"category": "environmental",
|
| 4 |
+
"description": "Decision tree for environmental law complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Who is violating environmental law?",
|
| 13 |
+
"field_name": "violating_party",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": []
|
| 18 |
+
},
|
| 19 |
+
"q2": {
|
| 20 |
+
"id": "q2",
|
| 21 |
+
"question": "What type of violation is occurring?",
|
| 22 |
+
"field_name": "violation_type",
|
| 23 |
+
"required": true,
|
| 24 |
+
"depends_on": [],
|
| 25 |
+
"follow_ups": [],
|
| 26 |
+
"keywords": [
|
| 27 |
+
"pollution",
|
| 28 |
+
"contamination",
|
| 29 |
+
"hazardous waste"
|
| 30 |
+
]
|
| 31 |
+
},
|
| 32 |
+
"q3": {
|
| 33 |
+
"id": "q3",
|
| 34 |
+
"question": "Where is the violation occurring?",
|
| 35 |
+
"field_name": "location",
|
| 36 |
+
"required": false,
|
| 37 |
+
"depends_on": [],
|
| 38 |
+
"follow_ups": [],
|
| 39 |
+
"keywords": []
|
| 40 |
+
},
|
| 41 |
+
"q4": {
|
| 42 |
+
"id": "q4",
|
| 43 |
+
"question": "When did you discover the violation?",
|
| 44 |
+
"field_name": "date_discovered",
|
| 45 |
+
"required": true,
|
| 46 |
+
"depends_on": [],
|
| 47 |
+
"follow_ups": [],
|
| 48 |
+
"keywords": []
|
| 49 |
+
},
|
| 50 |
+
"q5": {
|
| 51 |
+
"id": "q5",
|
| 52 |
+
"question": "What is the environmental impact?",
|
| 53 |
+
"field_name": "environmental_impact",
|
| 54 |
+
"required": false,
|
| 55 |
+
"depends_on": [
|
| 56 |
+
"violation_type"
|
| 57 |
+
],
|
| 58 |
+
"follow_ups": [],
|
| 59 |
+
"keywords": []
|
| 60 |
+
}
|
| 61 |
+
},
|
| 62 |
+
"required_fields": [
|
| 63 |
+
"violating_party",
|
| 64 |
+
"date_discovered",
|
| 65 |
+
"violation_type"
|
| 66 |
+
],
|
| 67 |
+
"optional_fields": [
|
| 68 |
+
"environmental_impact",
|
| 69 |
+
"location"
|
| 70 |
+
]
|
| 71 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/family_law_tree.json
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "family_law",
|
| 3 |
+
"category": "family_law",
|
| 4 |
+
"description": "Decision tree for family law complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Who is the other party involved?",
|
| 13 |
+
"field_name": "other_party",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": []
|
| 18 |
+
},
|
| 19 |
+
"q2": {
|
| 20 |
+
"id": "q2",
|
| 21 |
+
"question": "What is the nature of the issue?",
|
| 22 |
+
"field_name": "issue_description",
|
| 23 |
+
"required": true,
|
| 24 |
+
"depends_on": [],
|
| 25 |
+
"follow_ups": [],
|
| 26 |
+
"keywords": [
|
| 27 |
+
"custody",
|
| 28 |
+
"support",
|
| 29 |
+
"visitation",
|
| 30 |
+
"divorce"
|
| 31 |
+
]
|
| 32 |
+
},
|
| 33 |
+
"q3": {
|
| 34 |
+
"id": "q3",
|
| 35 |
+
"question": "If children are involved, please list their names and ages.",
|
| 36 |
+
"field_name": "children",
|
| 37 |
+
"required": false,
|
| 38 |
+
"depends_on": [
|
| 39 |
+
"issue_description"
|
| 40 |
+
],
|
| 41 |
+
"follow_ups": [],
|
| 42 |
+
"keywords": []
|
| 43 |
+
},
|
| 44 |
+
"q4": {
|
| 45 |
+
"id": "q4",
|
| 46 |
+
"question": "What is the current custody or support arrangement?",
|
| 47 |
+
"field_name": "custody_arrangement",
|
| 48 |
+
"required": false,
|
| 49 |
+
"depends_on": [
|
| 50 |
+
"children"
|
| 51 |
+
],
|
| 52 |
+
"follow_ups": [],
|
| 53 |
+
"keywords": []
|
| 54 |
+
},
|
| 55 |
+
"q5": {
|
| 56 |
+
"id": "q5",
|
| 57 |
+
"question": "Are there any prior court orders in this matter?",
|
| 58 |
+
"field_name": "prior_orders",
|
| 59 |
+
"required": false,
|
| 60 |
+
"depends_on": [],
|
| 61 |
+
"follow_ups": [],
|
| 62 |
+
"keywords": []
|
| 63 |
+
}
|
| 64 |
+
},
|
| 65 |
+
"required_fields": [
|
| 66 |
+
"other_party",
|
| 67 |
+
"issue_description"
|
| 68 |
+
],
|
| 69 |
+
"optional_fields": [
|
| 70 |
+
"children",
|
| 71 |
+
"prior_orders",
|
| 72 |
+
"custody_arrangement"
|
| 73 |
+
]
|
| 74 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/free_speech_tree.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "free_speech",
|
| 3 |
+
"category": "civil_rights",
|
| 4 |
+
"description": "Decision tree for free speech complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q3"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Who censored or suppressed your speech?",
|
| 13 |
+
"field_name": "censoring_party",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": [
|
| 18 |
+
"platform",
|
| 19 |
+
"government",
|
| 20 |
+
"school",
|
| 21 |
+
"employer"
|
| 22 |
+
]
|
| 23 |
+
},
|
| 24 |
+
"q2": {
|
| 25 |
+
"id": "q2",
|
| 26 |
+
"question": "What platform or venue was involved?",
|
| 27 |
+
"field_name": "platform_or_venue",
|
| 28 |
+
"required": false,
|
| 29 |
+
"depends_on": [],
|
| 30 |
+
"follow_ups": [],
|
| 31 |
+
"keywords": []
|
| 32 |
+
},
|
| 33 |
+
"q3": {
|
| 34 |
+
"id": "q3",
|
| 35 |
+
"question": "What content was censored?",
|
| 36 |
+
"field_name": "content_censored",
|
| 37 |
+
"required": true,
|
| 38 |
+
"depends_on": [],
|
| 39 |
+
"follow_ups": [],
|
| 40 |
+
"keywords": []
|
| 41 |
+
},
|
| 42 |
+
"q4": {
|
| 43 |
+
"id": "q4",
|
| 44 |
+
"question": "When did the censorship occur?",
|
| 45 |
+
"field_name": "date_of_censorship",
|
| 46 |
+
"required": true,
|
| 47 |
+
"depends_on": [],
|
| 48 |
+
"follow_ups": [],
|
| 49 |
+
"keywords": []
|
| 50 |
+
},
|
| 51 |
+
"q5": {
|
| 52 |
+
"id": "q5",
|
| 53 |
+
"question": "What reason was given for the censorship, if any?",
|
| 54 |
+
"field_name": "reason_given",
|
| 55 |
+
"required": false,
|
| 56 |
+
"depends_on": [
|
| 57 |
+
"date_of_censorship"
|
| 58 |
+
],
|
| 59 |
+
"follow_ups": [],
|
| 60 |
+
"keywords": []
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"required_fields": [
|
| 64 |
+
"censoring_party",
|
| 65 |
+
"content_censored",
|
| 66 |
+
"date_of_censorship"
|
| 67 |
+
],
|
| 68 |
+
"optional_fields": [
|
| 69 |
+
"platform_or_venue",
|
| 70 |
+
"reason_given"
|
| 71 |
+
]
|
| 72 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/healthcare_tree.json
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "healthcare",
|
| 3 |
+
"category": "healthcare",
|
| 4 |
+
"description": "Decision tree for healthcare complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q3"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Who was the healthcare provider?",
|
| 13 |
+
"field_name": "healthcare_provider",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": []
|
| 18 |
+
},
|
| 19 |
+
"q2": {
|
| 20 |
+
"id": "q2",
|
| 21 |
+
"question": "What facility did this occur at?",
|
| 22 |
+
"field_name": "facility_name",
|
| 23 |
+
"required": false,
|
| 24 |
+
"depends_on": [],
|
| 25 |
+
"follow_ups": [],
|
| 26 |
+
"keywords": []
|
| 27 |
+
},
|
| 28 |
+
"q3": {
|
| 29 |
+
"id": "q3",
|
| 30 |
+
"question": "What type of negligence or malpractice occurred?",
|
| 31 |
+
"field_name": "type_of_negligence",
|
| 32 |
+
"required": true,
|
| 33 |
+
"depends_on": [],
|
| 34 |
+
"follow_ups": [],
|
| 35 |
+
"keywords": [
|
| 36 |
+
"misdiagnosis",
|
| 37 |
+
"surgical error",
|
| 38 |
+
"medication error"
|
| 39 |
+
]
|
| 40 |
+
},
|
| 41 |
+
"q4": {
|
| 42 |
+
"id": "q4",
|
| 43 |
+
"question": "Please describe what happened.",
|
| 44 |
+
"field_name": "incident_description",
|
| 45 |
+
"required": true,
|
| 46 |
+
"depends_on": [
|
| 47 |
+
"type_of_negligence"
|
| 48 |
+
],
|
| 49 |
+
"follow_ups": [],
|
| 50 |
+
"keywords": []
|
| 51 |
+
},
|
| 52 |
+
"q5": {
|
| 53 |
+
"id": "q5",
|
| 54 |
+
"question": "When did this occur?",
|
| 55 |
+
"field_name": "date_of_incident",
|
| 56 |
+
"required": true,
|
| 57 |
+
"depends_on": [],
|
| 58 |
+
"follow_ups": [],
|
| 59 |
+
"keywords": []
|
| 60 |
+
},
|
| 61 |
+
"q6": {
|
| 62 |
+
"id": "q6",
|
| 63 |
+
"question": "What injuries or harm resulted?",
|
| 64 |
+
"field_name": "injuries_sustained",
|
| 65 |
+
"required": false,
|
| 66 |
+
"depends_on": [
|
| 67 |
+
"incident_description"
|
| 68 |
+
],
|
| 69 |
+
"follow_ups": [],
|
| 70 |
+
"keywords": []
|
| 71 |
+
}
|
| 72 |
+
},
|
| 73 |
+
"required_fields": [
|
| 74 |
+
"healthcare_provider",
|
| 75 |
+
"date_of_incident",
|
| 76 |
+
"incident_description",
|
| 77 |
+
"type_of_negligence"
|
| 78 |
+
],
|
| 79 |
+
"optional_fields": [
|
| 80 |
+
"facility_name",
|
| 81 |
+
"injuries_sustained"
|
| 82 |
+
]
|
| 83 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/housing_tree.json
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "housing",
|
| 3 |
+
"category": "housing",
|
| 4 |
+
"description": "Decision tree for housing complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2",
|
| 8 |
+
"q3"
|
| 9 |
+
],
|
| 10 |
+
"questions": {
|
| 11 |
+
"q1": {
|
| 12 |
+
"id": "q1",
|
| 13 |
+
"question": "Who is the landlord or property owner?",
|
| 14 |
+
"field_name": "landlord_name",
|
| 15 |
+
"required": true,
|
| 16 |
+
"depends_on": [],
|
| 17 |
+
"follow_ups": [],
|
| 18 |
+
"keywords": [
|
| 19 |
+
"landlord",
|
| 20 |
+
"owner",
|
| 21 |
+
"property manager"
|
| 22 |
+
]
|
| 23 |
+
},
|
| 24 |
+
"q2": {
|
| 25 |
+
"id": "q2",
|
| 26 |
+
"question": "What is the address of the property?",
|
| 27 |
+
"field_name": "property_address",
|
| 28 |
+
"required": true,
|
| 29 |
+
"depends_on": [],
|
| 30 |
+
"follow_ups": [],
|
| 31 |
+
"keywords": [
|
| 32 |
+
"address",
|
| 33 |
+
"property",
|
| 34 |
+
"location"
|
| 35 |
+
]
|
| 36 |
+
},
|
| 37 |
+
"q3": {
|
| 38 |
+
"id": "q3",
|
| 39 |
+
"question": "What type of issue are you experiencing?",
|
| 40 |
+
"field_name": "issue_type",
|
| 41 |
+
"required": true,
|
| 42 |
+
"depends_on": [],
|
| 43 |
+
"follow_ups": [],
|
| 44 |
+
"keywords": [
|
| 45 |
+
"discrimination",
|
| 46 |
+
"eviction",
|
| 47 |
+
"harassment",
|
| 48 |
+
"repair"
|
| 49 |
+
]
|
| 50 |
+
},
|
| 51 |
+
"q4": {
|
| 52 |
+
"id": "q4",
|
| 53 |
+
"question": "Can you describe the specific incident or action that occurred?",
|
| 54 |
+
"field_name": "incident_description",
|
| 55 |
+
"required": true,
|
| 56 |
+
"depends_on": [
|
| 57 |
+
"issue_type"
|
| 58 |
+
],
|
| 59 |
+
"follow_ups": [],
|
| 60 |
+
"keywords": [
|
| 61 |
+
"affordable housing",
|
| 62 |
+
"eviction",
|
| 63 |
+
"fair housing",
|
| 64 |
+
"familial status",
|
| 65 |
+
"housing authority",
|
| 66 |
+
"housing choice voucher",
|
| 67 |
+
"housing discrimination",
|
| 68 |
+
"landlord",
|
| 69 |
+
"lease",
|
| 70 |
+
"public housing",
|
| 71 |
+
"reasonable accommodation",
|
| 72 |
+
"reasonable modification",
|
| 73 |
+
"rental",
|
| 74 |
+
"section 8",
|
| 75 |
+
"source of income",
|
| 76 |
+
"tenant"
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
"q5": {
|
| 80 |
+
"id": "q5",
|
| 81 |
+
"question": "When did this incident occur?",
|
| 82 |
+
"field_name": "date_of_incident",
|
| 83 |
+
"required": true,
|
| 84 |
+
"depends_on": [
|
| 85 |
+
"incident_description"
|
| 86 |
+
],
|
| 87 |
+
"follow_ups": [],
|
| 88 |
+
"keywords": []
|
| 89 |
+
},
|
| 90 |
+
"q6": {
|
| 91 |
+
"id": "q6",
|
| 92 |
+
"question": "Were there any witnesses to this incident?",
|
| 93 |
+
"field_name": "witnesses",
|
| 94 |
+
"required": false,
|
| 95 |
+
"depends_on": [
|
| 96 |
+
"incident_description"
|
| 97 |
+
],
|
| 98 |
+
"follow_ups": [],
|
| 99 |
+
"keywords": []
|
| 100 |
+
},
|
| 101 |
+
"q7": {
|
| 102 |
+
"id": "q7",
|
| 103 |
+
"question": "Have you filed any prior complaints about this issue?",
|
| 104 |
+
"field_name": "prior_complaints",
|
| 105 |
+
"required": false,
|
| 106 |
+
"depends_on": [
|
| 107 |
+
"incident_description"
|
| 108 |
+
],
|
| 109 |
+
"follow_ups": [],
|
| 110 |
+
"keywords": []
|
| 111 |
+
},
|
| 112 |
+
"q8": {
|
| 113 |
+
"id": "q8",
|
| 114 |
+
"question": "If this involves discrimination, what protected class are you a member of?",
|
| 115 |
+
"field_name": "protected_class",
|
| 116 |
+
"required": false,
|
| 117 |
+
"depends_on": [
|
| 118 |
+
"issue_type"
|
| 119 |
+
],
|
| 120 |
+
"follow_ups": [],
|
| 121 |
+
"keywords": [
|
| 122 |
+
"race",
|
| 123 |
+
"gender",
|
| 124 |
+
"disability",
|
| 125 |
+
"religion"
|
| 126 |
+
]
|
| 127 |
+
}
|
| 128 |
+
},
|
| 129 |
+
"required_fields": [
|
| 130 |
+
"issue_type",
|
| 131 |
+
"date_of_incident",
|
| 132 |
+
"incident_description",
|
| 133 |
+
"landlord_name",
|
| 134 |
+
"property_address"
|
| 135 |
+
],
|
| 136 |
+
"optional_fields": [
|
| 137 |
+
"witnesses",
|
| 138 |
+
"protected_class",
|
| 139 |
+
"prior_complaints"
|
| 140 |
+
]
|
| 141 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/immigration_tree.json
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "immigration",
|
| 3 |
+
"category": "immigration",
|
| 4 |
+
"description": "Decision tree for immigration complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Which government agency is involved?",
|
| 13 |
+
"field_name": "government_agency",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": [
|
| 18 |
+
"uscis",
|
| 19 |
+
"ice",
|
| 20 |
+
"cbp",
|
| 21 |
+
"immigration"
|
| 22 |
+
]
|
| 23 |
+
},
|
| 24 |
+
"q2": {
|
| 25 |
+
"id": "q2",
|
| 26 |
+
"question": "What type of violation occurred?",
|
| 27 |
+
"field_name": "violation_type",
|
| 28 |
+
"required": true,
|
| 29 |
+
"depends_on": [],
|
| 30 |
+
"follow_ups": [],
|
| 31 |
+
"keywords": []
|
| 32 |
+
},
|
| 33 |
+
"q3": {
|
| 34 |
+
"id": "q3",
|
| 35 |
+
"question": "What is your current immigration status?",
|
| 36 |
+
"field_name": "immigration_status",
|
| 37 |
+
"required": false,
|
| 38 |
+
"depends_on": [],
|
| 39 |
+
"follow_ups": [],
|
| 40 |
+
"keywords": []
|
| 41 |
+
},
|
| 42 |
+
"q4": {
|
| 43 |
+
"id": "q4",
|
| 44 |
+
"question": "When did this occur?",
|
| 45 |
+
"field_name": "date_of_incident",
|
| 46 |
+
"required": true,
|
| 47 |
+
"depends_on": [],
|
| 48 |
+
"follow_ups": [],
|
| 49 |
+
"keywords": []
|
| 50 |
+
},
|
| 51 |
+
"q5": {
|
| 52 |
+
"id": "q5",
|
| 53 |
+
"question": "What relief or remedy are you seeking?",
|
| 54 |
+
"field_name": "relief_sought",
|
| 55 |
+
"required": false,
|
| 56 |
+
"depends_on": [],
|
| 57 |
+
"follow_ups": [],
|
| 58 |
+
"keywords": []
|
| 59 |
+
}
|
| 60 |
+
},
|
| 61 |
+
"required_fields": [
|
| 62 |
+
"government_agency",
|
| 63 |
+
"date_of_incident",
|
| 64 |
+
"violation_type"
|
| 65 |
+
],
|
| 66 |
+
"optional_fields": [
|
| 67 |
+
"immigration_status",
|
| 68 |
+
"relief_sought"
|
| 69 |
+
]
|
| 70 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/intellectual_property_tree.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "intellectual_property",
|
| 3 |
+
"category": "intellectual_property",
|
| 4 |
+
"description": "Decision tree for intellectual property complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Who is infringing on your intellectual property?",
|
| 13 |
+
"field_name": "infringing_party",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": []
|
| 18 |
+
},
|
| 19 |
+
"q2": {
|
| 20 |
+
"id": "q2",
|
| 21 |
+
"question": "What type of IP is involved?",
|
| 22 |
+
"field_name": "ip_type",
|
| 23 |
+
"required": true,
|
| 24 |
+
"depends_on": [],
|
| 25 |
+
"follow_ups": [],
|
| 26 |
+
"keywords": [
|
| 27 |
+
"patent",
|
| 28 |
+
"trademark",
|
| 29 |
+
"copyright",
|
| 30 |
+
"trade secret"
|
| 31 |
+
]
|
| 32 |
+
},
|
| 33 |
+
"q3": {
|
| 34 |
+
"id": "q3",
|
| 35 |
+
"question": "What is the registration number, if applicable?",
|
| 36 |
+
"field_name": "registration_number",
|
| 37 |
+
"required": false,
|
| 38 |
+
"depends_on": [
|
| 39 |
+
"ip_type"
|
| 40 |
+
],
|
| 41 |
+
"follow_ups": [],
|
| 42 |
+
"keywords": []
|
| 43 |
+
},
|
| 44 |
+
"q4": {
|
| 45 |
+
"id": "q4",
|
| 46 |
+
"question": "When did you discover the infringement?",
|
| 47 |
+
"field_name": "date_of_infringement",
|
| 48 |
+
"required": true,
|
| 49 |
+
"depends_on": [],
|
| 50 |
+
"follow_ups": [],
|
| 51 |
+
"keywords": []
|
| 52 |
+
},
|
| 53 |
+
"q5": {
|
| 54 |
+
"id": "q5",
|
| 55 |
+
"question": "What are your estimated damages?",
|
| 56 |
+
"field_name": "damages_estimate",
|
| 57 |
+
"required": false,
|
| 58 |
+
"depends_on": [],
|
| 59 |
+
"follow_ups": [],
|
| 60 |
+
"keywords": []
|
| 61 |
+
}
|
| 62 |
+
},
|
| 63 |
+
"required_fields": [
|
| 64 |
+
"date_of_infringement",
|
| 65 |
+
"ip_type",
|
| 66 |
+
"infringing_party"
|
| 67 |
+
],
|
| 68 |
+
"optional_fields": [
|
| 69 |
+
"damages_estimate",
|
| 70 |
+
"registration_number"
|
| 71 |
+
]
|
| 72 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/probate_tree.json
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "probate",
|
| 3 |
+
"category": "probate",
|
| 4 |
+
"description": "Decision tree for probate and estate law complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2",
|
| 8 |
+
"q3"
|
| 9 |
+
],
|
| 10 |
+
"questions": {
|
| 11 |
+
"q1": {
|
| 12 |
+
"id": "q1",
|
| 13 |
+
"question": "What is the name of the decedent (deceased person)?",
|
| 14 |
+
"field_name": "decedent_name",
|
| 15 |
+
"required": true,
|
| 16 |
+
"depends_on": [],
|
| 17 |
+
"follow_ups": ["q4"],
|
| 18 |
+
"keywords": ["decedent", "deceased", "testator"]
|
| 19 |
+
},
|
| 20 |
+
"q2": {
|
| 21 |
+
"id": "q2",
|
| 22 |
+
"question": "What is the date of death?",
|
| 23 |
+
"field_name": "date_of_death",
|
| 24 |
+
"required": true,
|
| 25 |
+
"depends_on": [],
|
| 26 |
+
"follow_ups": [],
|
| 27 |
+
"keywords": ["death", "died", "deceased"]
|
| 28 |
+
},
|
| 29 |
+
"q3": {
|
| 30 |
+
"id": "q3",
|
| 31 |
+
"question": "What type of probate issue are you experiencing? (e.g., will contest, executor dispute, trust dispute, guardianship, estate administration)",
|
| 32 |
+
"field_name": "probate_issue_type",
|
| 33 |
+
"required": true,
|
| 34 |
+
"depends_on": [],
|
| 35 |
+
"follow_ups": ["q5", "q6"],
|
| 36 |
+
"keywords": ["will contest", "executor", "trustee", "guardianship", "conservatorship", "estate administration"]
|
| 37 |
+
},
|
| 38 |
+
"q4": {
|
| 39 |
+
"id": "q4",
|
| 40 |
+
"question": "In which county and state did the decedent reside at the time of death?",
|
| 41 |
+
"field_name": "decedent_residence",
|
| 42 |
+
"required": true,
|
| 43 |
+
"depends_on": ["q1"],
|
| 44 |
+
"follow_ups": [],
|
| 45 |
+
"keywords": ["residence", "domicile", "county", "state"]
|
| 46 |
+
},
|
| 47 |
+
"q5": {
|
| 48 |
+
"id": "q5",
|
| 49 |
+
"question": "Did the decedent leave a will or trust?",
|
| 50 |
+
"field_name": "will_or_trust_exists",
|
| 51 |
+
"required": true,
|
| 52 |
+
"depends_on": ["q3"],
|
| 53 |
+
"follow_ups": ["q7"],
|
| 54 |
+
"keywords": ["will", "testament", "trust", "testate", "intestate"]
|
| 55 |
+
},
|
| 56 |
+
"q6": {
|
| 57 |
+
"id": "q6",
|
| 58 |
+
"question": "Who is the executor, administrator, or trustee involved?",
|
| 59 |
+
"field_name": "fiduciary_name",
|
| 60 |
+
"required": false,
|
| 61 |
+
"depends_on": ["q3"],
|
| 62 |
+
"follow_ups": [],
|
| 63 |
+
"keywords": ["executor", "administrator", "trustee", "personal representative"]
|
| 64 |
+
},
|
| 65 |
+
"q7": {
|
| 66 |
+
"id": "q7",
|
| 67 |
+
"question": "What are the specific issues or disputes? (e.g., undue influence, lack of capacity, breach of fiduciary duty, improper distribution)",
|
| 68 |
+
"field_name": "specific_issues",
|
| 69 |
+
"required": true,
|
| 70 |
+
"depends_on": ["q5"],
|
| 71 |
+
"follow_ups": ["q8"],
|
| 72 |
+
"keywords": ["undue influence", "capacity", "fraud", "breach", "fiduciary duty", "distribution"]
|
| 73 |
+
},
|
| 74 |
+
"q8": {
|
| 75 |
+
"id": "q8",
|
| 76 |
+
"question": "What are the estate assets involved? (e.g., real property, bank accounts, investments, personal property)",
|
| 77 |
+
"field_name": "estate_assets",
|
| 78 |
+
"required": false,
|
| 79 |
+
"depends_on": ["q7"],
|
| 80 |
+
"follow_ups": [],
|
| 81 |
+
"keywords": ["assets", "property", "real estate", "bank account", "investment"]
|
| 82 |
+
},
|
| 83 |
+
"q9": {
|
| 84 |
+
"id": "q9",
|
| 85 |
+
"question": "What is your relationship to the decedent? (e.g., spouse, child, heir, beneficiary, creditor)",
|
| 86 |
+
"field_name": "relationship_to_decedent",
|
| 87 |
+
"required": true,
|
| 88 |
+
"depends_on": [],
|
| 89 |
+
"follow_ups": [],
|
| 90 |
+
"keywords": ["spouse", "heir", "beneficiary", "child", "family", "creditor"]
|
| 91 |
+
},
|
| 92 |
+
"q10": {
|
| 93 |
+
"id": "q10",
|
| 94 |
+
"question": "Has probate been opened, and if so, in which court?",
|
| 95 |
+
"field_name": "probate_court_info",
|
| 96 |
+
"required": false,
|
| 97 |
+
"depends_on": [],
|
| 98 |
+
"follow_ups": [],
|
| 99 |
+
"keywords": ["probate court", "case number", "proceeding", "filed"]
|
| 100 |
+
}
|
| 101 |
+
},
|
| 102 |
+
"required_fields": [
|
| 103 |
+
"decedent_name",
|
| 104 |
+
"date_of_death",
|
| 105 |
+
"probate_issue_type",
|
| 106 |
+
"decedent_residence",
|
| 107 |
+
"will_or_trust_exists",
|
| 108 |
+
"specific_issues",
|
| 109 |
+
"relationship_to_decedent"
|
| 110 |
+
],
|
| 111 |
+
"optional_fields": [
|
| 112 |
+
"fiduciary_name",
|
| 113 |
+
"estate_assets",
|
| 114 |
+
"probate_court_info"
|
| 115 |
+
]
|
| 116 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/complaint_analysis/decision_trees/tax_law_tree.json
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"complaint_type": "tax_law",
|
| 3 |
+
"category": "tax",
|
| 4 |
+
"description": "Decision tree for tax law complaints",
|
| 5 |
+
"root_questions": [
|
| 6 |
+
"q1",
|
| 7 |
+
"q2"
|
| 8 |
+
],
|
| 9 |
+
"questions": {
|
| 10 |
+
"q1": {
|
| 11 |
+
"id": "q1",
|
| 12 |
+
"question": "Which tax authority is involved?",
|
| 13 |
+
"field_name": "tax_authority",
|
| 14 |
+
"required": true,
|
| 15 |
+
"depends_on": [],
|
| 16 |
+
"follow_ups": [],
|
| 17 |
+
"keywords": [
|
| 18 |
+
"irs",
|
| 19 |
+
"state",
|
| 20 |
+
"local"
|
| 21 |
+
]
|
| 22 |
+
},
|
| 23 |
+
"q2": {
|
| 24 |
+
"id": "q2",
|
| 25 |
+
"question": "What type of dispute is this?",
|
| 26 |
+
"field_name": "dispute_type",
|
| 27 |
+
"required": true,
|
| 28 |
+
"depends_on": [],
|
| 29 |
+
"follow_ups": [],
|
| 30 |
+
"keywords": [
|
| 31 |
+
"assessment",
|
| 32 |
+
"collection",
|
| 33 |
+
"refund",
|
| 34 |
+
"audit"
|
| 35 |
+
]
|
| 36 |
+
},
|
| 37 |
+
"q3": {
|
| 38 |
+
"id": "q3",
|
| 39 |
+
"question": "What tax year is involved?",
|
| 40 |
+
"field_name": "tax_year",
|
| 41 |
+
"required": false,
|
| 42 |
+
"depends_on": [],
|
| 43 |
+
"follow_ups": [],
|
| 44 |
+
"keywords": []
|
| 45 |
+
},
|
| 46 |
+
"q4": {
|
| 47 |
+
"id": "q4",
|
| 48 |
+
"question": "What is the amount in dispute?",
|
| 49 |
+
"field_name": "amount_in_dispute",
|
| 50 |
+
"required": false,
|
| 51 |
+
"depends_on": [],
|
| 52 |
+
"follow_ups": [],
|
| 53 |
+
"keywords": []
|
| 54 |
+
},
|
| 55 |
+
"q5": {
|
| 56 |
+
"id": "q5",
|
| 57 |
+
"question": "Have you filed any prior appeals?",
|
| 58 |
+
"field_name": "prior_appeals",
|
| 59 |
+
"required": false,
|
| 60 |
+
"depends_on": [],
|
| 61 |
+
"follow_ups": [],
|
| 62 |
+
"keywords": []
|
| 63 |
+
}
|
| 64 |
+
},
|
| 65 |
+
"required_fields": [
|
| 66 |
+
"tax_authority",
|
| 67 |
+
"dispute_type"
|
| 68 |
+
],
|
| 69 |
+
"optional_fields": [
|
| 70 |
+
"tax_year",
|
| 71 |
+
"prior_appeals",
|
| 72 |
+
"amount_in_dispute"
|
| 73 |
+
]
|
| 74 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Country-law CID-keyed sparse GraphRAG packager (SkillCenter / publicus-ir family)."""
|
| 2 |
+
|
| 3 |
+
__version__ = "0.5.0"
|
| 4 |
+
# Layout matches SkillCenter HF release / publicus-ir family; schema string is domain-specific.
|
| 5 |
+
SCHEMA_VERSION = "country-laws-ir-graphrag/v1"
|
| 6 |
+
LAYOUT_FAMILY = "skillcenter-huggingface-release/v3"
|
| 7 |
+
ENTRY_IDENTITY_SCHEMA = "country-laws-entry/v1"
|
| 8 |
+
LAW_IDENTITY_SCHEMA = "country-laws-law/v1"
|
| 9 |
+
FACET_IDENTITY_SCHEMA = "country-laws-facet/v1"
|
| 10 |
+
EDGE_IDENTITY_SCHEMA = "country-laws-edge/v1"
|
| 11 |
+
MAX_ROWS_PER_FILE = 4096
|
| 12 |
+
TARGET_ORG = "justicedao"
|
| 13 |
+
|
| 14 |
+
# CID payload: UTF-8 bytes of json.dumps(obj, sort_keys=True, ensure_ascii=False,
|
| 15 |
+
# separators=(",", ":")) hashed as CIDv1 codec=raw (0x55) hash=sha2-256 (0x12)
|
| 16 |
+
# multibase base32 (`bafkrei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
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def main(argv: list[str] | None = None) -> int:
|
| 12 |
+
ap = argparse.ArgumentParser(prog="country_laws_ir")
|
| 13 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 14 |
+
|
| 15 |
+
p_build = sub.add_parser("build")
|
| 16 |
+
p_build.add_argument("--source-repo", "--source", dest="source", default="malta",
|
| 17 |
+
help="Hub dataset id (endomorphosis/ipfs_<slug>_laws), country slug, or local pack dir")
|
| 18 |
+
p_build.add_argument("--out", default=None)
|
| 19 |
+
p_build.add_argument(
|
| 20 |
+
"--device",
|
| 21 |
+
default="cuda",
|
| 22 |
+
help="Embedding device (cuda by default, like US Code / Open US Law; falls back to cpu)",
|
| 23 |
+
)
|
| 24 |
+
p_build.add_argument("--neighbor-k", type=int, default=8)
|
| 25 |
+
p_build.add_argument("--skip-vectors", action="store_true")
|
| 26 |
+
p_build.add_argument("--upload", action="store_true",
|
| 27 |
+
help="Publish the packaged release to justicedao/ipfs_<slug>_laws_ir (requires HF_TOKEN)")
|
| 28 |
+
p_build.add_argument("--mode", default="auto", choices=["auto", "full", "delta"],
|
| 29 |
+
help="auto skips unchanged Hub revisions and reuses embeddings by entry_cid")
|
| 30 |
+
p_build.add_argument("--force", action="store_true", help="Ignore source fingerprint skip and reuse caches")
|
| 31 |
+
p_build.add_argument("--prior-dir", default=None, help="Prior GraphRAG release to delta against")
|
| 32 |
+
|
| 33 |
+
p_batch = sub.add_parser("batch")
|
| 34 |
+
p_batch.add_argument("--slugs", nargs="*", default=None)
|
| 35 |
+
p_batch.add_argument("--upload", action="store_true")
|
| 36 |
+
p_batch.add_argument("--no-skip-done", action="store_true",
|
| 37 |
+
help="Force a full rebuild of every country (ignore unchanged fingerprints)")
|
| 38 |
+
p_batch.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
|
| 39 |
+
p_batch.add_argument("--skip-vectors", action="store_true")
|
| 40 |
+
|
| 41 |
+
p_q = sub.add_parser("query")
|
| 42 |
+
p_q.add_argument("--local-dir", required=True)
|
| 43 |
+
p_q.add_argument("rest", nargs=argparse.REMAINDER)
|
| 44 |
+
|
| 45 |
+
p_norm = sub.add_parser("normalize")
|
| 46 |
+
p_norm.add_argument("--source-repo", "--source", dest="source", default="malta")
|
| 47 |
+
p_norm.add_argument("--out", default=None, help="Optional JSON report path")
|
| 48 |
+
|
| 49 |
+
p_cat = sub.add_parser("catalog")
|
| 50 |
+
p_cat.add_argument("--refresh", action="store_true",
|
| 51 |
+
help="List public endomorphosis/ipfs_*_laws datasets and persist new slugs")
|
| 52 |
+
|
| 53 |
+
p_cov = sub.add_parser("coverage", help="Compare endomorphosis sources vs justicedao GraphRAG releases")
|
| 54 |
+
p_cov.add_argument("--gaps", action="store_true",
|
| 55 |
+
help="Scan Hub for missing, stale, and incomplete IR (downloads manifests)")
|
| 56 |
+
p_cov.add_argument("--workers", type=int, default=8)
|
| 57 |
+
|
| 58 |
+
p_re = sub.add_parser(
|
| 59 |
+
"reindex",
|
| 60 |
+
help="Scan endomorphosis vs justicedao and incrementally rebuild stale/missing IR",
|
| 61 |
+
)
|
| 62 |
+
p_re.add_argument("--upload", action="store_true",
|
| 63 |
+
help="Publish rebuilt packs to justicedao (requires HF_TOKEN)")
|
| 64 |
+
p_re.add_argument("--slugs", nargs="*", default=None)
|
| 65 |
+
p_re.add_argument("--limit", type=int, default=None)
|
| 66 |
+
p_re.add_argument("--max-corpus-rows", type=int, default=20000,
|
| 67 |
+
help="Skip IR larger than this many rows (0 = no cap)")
|
| 68 |
+
p_re.add_argument("--skip-vectors", action="store_true")
|
| 69 |
+
p_re.add_argument("--workers", type=int, default=2,
|
| 70 |
+
help="Ceiling for adaptive workers. Memory, disk, and free GPU memory shrink it and back off when the host is full")
|
| 71 |
+
p_re.add_argument("--device", default="cuda")
|
| 72 |
+
p_re.add_argument("--mode", default="auto", choices=["auto", "full", "delta"])
|
| 73 |
+
p_re.add_argument("--all", action="store_true",
|
| 74 |
+
help="Process every indexable catalog country (not only Hub gaps)")
|
| 75 |
+
p_re.add_argument("--force", action="store_true",
|
| 76 |
+
help="Rebuild even when the source SHA matches, and re-encode every row")
|
| 77 |
+
p_re.add_argument("--renormalize", action="store_true",
|
| 78 |
+
help="Rerun normalization, then reindex only packs whose entry rows changed")
|
| 79 |
+
|
| 80 |
+
p_ver = sub.add_parser(
|
| 81 |
+
"verify",
|
| 82 |
+
help="Normalize a country pack and run admission verifiers (no GraphRAG)",
|
| 83 |
+
)
|
| 84 |
+
p_ver.add_argument("--source-repo", "--source", dest="source", default=None)
|
| 85 |
+
p_ver.add_argument("--all", action="store_true", help="Verify every indexable catalog country")
|
| 86 |
+
p_ver.add_argument("--limit", type=int, default=None)
|
| 87 |
+
|
| 88 |
+
p_loop = sub.add_parser(
|
| 89 |
+
"normalize-loop",
|
| 90 |
+
help="scan residuals, improve the normalizer script with llm_router, or apply that script",
|
| 91 |
+
)
|
| 92 |
+
p_loop.add_argument("stage", choices=["scan", "improve", "apply", "run"])
|
| 93 |
+
p_loop.add_argument("--cache", default=None)
|
| 94 |
+
p_loop.add_argument("--out", default=None)
|
| 95 |
+
p_loop.add_argument("--reports", default=None, help="Per-country residual JSON directory")
|
| 96 |
+
p_loop.add_argument("--slug", default=None, help="One country, for a subprocess")
|
| 97 |
+
p_loop.add_argument("--workers", type=int, default=None, help="Country processes (default: one per CPU)")
|
| 98 |
+
p_loop.add_argument("--limit", type=int, default=None)
|
| 99 |
+
p_loop.add_argument("--passes", type=int, default=40, help="Improve batches sent to llm_router")
|
| 100 |
+
p_loop.add_argument("--force", action="store_true", help="Redo finished countries and retry unresolved lines")
|
| 101 |
+
p_loop.add_argument("--progress", default=None, help="JSONL file appended as each country or improve pass finishes")
|
| 102 |
+
|
| 103 |
+
p_raw = sub.add_parser("package-raw")
|
| 104 |
+
p_raw.add_argument("--slug", required=True, help="Country slug used in justicedao/ipfs_<slug>_laws_ir")
|
| 105 |
+
p_raw.add_argument("--instruments-dir", default=None,
|
| 106 |
+
help="Collector JSON directory (default: $LEGAL_CORPORA_ROOT/<iso-or-slug>/instruments)")
|
| 107 |
+
p_raw.add_argument("--iso", default=None, help="Collector ISO directory name if different from slug")
|
| 108 |
+
p_raw.add_argument("--out", default=None, help="Local pack directory (laws.parquet + pack_meta.json)")
|
| 109 |
+
p_raw.add_argument("--source-dataset", default=None,
|
| 110 |
+
help="Raw Hub id (default endomorphosis/ipfs_<slug>_laws)")
|
| 111 |
+
p_raw.add_argument("--prior-pack", default=None, help="Existing parquet pack to merge into")
|
| 112 |
+
|
| 113 |
+
p_pack = sub.add_parser(
|
| 114 |
+
"pack-shards",
|
| 115 |
+
help="Concatenate local data/laws-*.parquet into data/laws.parquet. Does not upload.",
|
| 116 |
+
)
|
| 117 |
+
p_pack.add_argument("--source", required=True)
|
| 118 |
+
p_pack.add_argument("--out", required=True)
|
| 119 |
+
p_pack.add_argument("--slug", required=True)
|
| 120 |
+
p_pack.add_argument("--revision", required=True)
|
| 121 |
+
p_pack.add_argument("--source-dataset", default=None)
|
| 122 |
+
|
| 123 |
+
args = ap.parse_args(argv)
|
| 124 |
+
if args.cmd == "build":
|
| 125 |
+
from .build import build_country
|
| 126 |
+
|
| 127 |
+
result = build_country(
|
| 128 |
+
args.source,
|
| 129 |
+
out=Path(args.out) if args.out else None,
|
| 130 |
+
upload=args.upload,
|
| 131 |
+
device=args.device,
|
| 132 |
+
neighbor_k=args.neighbor_k,
|
| 133 |
+
skip_vectors=args.skip_vectors,
|
| 134 |
+
mode=args.mode,
|
| 135 |
+
force=args.force,
|
| 136 |
+
prior_dir=Path(args.prior_dir) if args.prior_dir else None,
|
| 137 |
+
)
|
| 138 |
+
print(json.dumps({k: result[k] for k in result if k != "normalization"}, indent=2, default=str))
|
| 139 |
+
print(json.dumps({"normalization": result["normalization"]}, indent=2, default=str))
|
| 140 |
+
return 0
|
| 141 |
+
if args.cmd == "batch":
|
| 142 |
+
from .build import batch
|
| 143 |
+
|
| 144 |
+
results = batch(
|
| 145 |
+
slugs=args.slugs,
|
| 146 |
+
upload=args.upload,
|
| 147 |
+
skip_done=not args.no_skip_done,
|
| 148 |
+
mode=args.mode,
|
| 149 |
+
skip_vectors=args.skip_vectors,
|
| 150 |
+
)
|
| 151 |
+
print(json.dumps(
|
| 152 |
+
[{"country": r["country"], "out": r["out"], "skipped": r.get("skipped", False)} for r in results],
|
| 153 |
+
indent=2,
|
| 154 |
+
))
|
| 155 |
+
return 0
|
| 156 |
+
if args.cmd == "query":
|
| 157 |
+
from .query import main as qmain
|
| 158 |
+
|
| 159 |
+
argv2 = ["--local-dir", args.local_dir] + [a for a in args.rest if a != "--"]
|
| 160 |
+
return qmain(argv2)
|
| 161 |
+
if args.cmd == "normalize":
|
| 162 |
+
from .build import CACHE, REPORTS
|
| 163 |
+
from .catalog import get_country
|
| 164 |
+
from .normalize import build_corpus, load_source
|
| 165 |
+
|
| 166 |
+
country = get_country(args.source)
|
| 167 |
+
local = country.get("local_source_dir")
|
| 168 |
+
laws, articles, source_meta = load_source(local or country["repo"], CACHE)
|
| 169 |
+
corpus, report = build_corpus(laws, articles, source_meta)
|
| 170 |
+
out = Path(args.out) if args.out else REPORTS / f"{country['slug']}_normalization.json"
|
| 171 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 172 |
+
out.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 173 |
+
print(json.dumps({"out": str(out), "n_out": report["n_out"], "unit": report["unit"], "drops": report["drops"]}, indent=2))
|
| 174 |
+
return 0
|
| 175 |
+
if args.cmd == "catalog":
|
| 176 |
+
from .catalog import all_countries, refresh_from_hub
|
| 177 |
+
|
| 178 |
+
countries = refresh_from_hub() if args.refresh else all_countries()
|
| 179 |
+
print(json.dumps(
|
| 180 |
+
{"n": len(countries), "indexable": len([c for c in countries if c.get("indexable")]), "countries": countries},
|
| 181 |
+
indent=2,
|
| 182 |
+
))
|
| 183 |
+
return 0
|
| 184 |
+
if args.cmd == "coverage":
|
| 185 |
+
from .coverage import coverage_report, gap_report
|
| 186 |
+
|
| 187 |
+
report = gap_report(workers=args.workers) if args.gaps else coverage_report()
|
| 188 |
+
print(json.dumps(report, indent=2, default=str))
|
| 189 |
+
return 0
|
| 190 |
+
if args.cmd == "reindex":
|
| 191 |
+
from .build import reindex_from_gaps
|
| 192 |
+
|
| 193 |
+
cap = None if args.all or int(args.max_corpus_rows or 0) <= 0 else int(args.max_corpus_rows)
|
| 194 |
+
results = reindex_from_gaps(
|
| 195 |
+
upload=args.upload,
|
| 196 |
+
slugs=args.slugs or None,
|
| 197 |
+
limit=args.limit,
|
| 198 |
+
max_corpus_rows=cap,
|
| 199 |
+
skip_vectors=args.skip_vectors,
|
| 200 |
+
workers=args.workers,
|
| 201 |
+
mode=args.mode,
|
| 202 |
+
force=args.force,
|
| 203 |
+
all_indexable=args.all,
|
| 204 |
+
device=args.device,
|
| 205 |
+
renormalize=args.renormalize,
|
| 206 |
+
)
|
| 207 |
+
print(json.dumps(
|
| 208 |
+
[
|
| 209 |
+
{
|
| 210 |
+
"country": r.get("country"),
|
| 211 |
+
"skipped": r.get("skipped", False),
|
| 212 |
+
"out": r.get("out"),
|
| 213 |
+
"hub": (r.get("hub") or {}).get("url") if isinstance(r.get("hub"), dict) else r.get("hub"),
|
| 214 |
+
"error": r.get("error"),
|
| 215 |
+
"kind": (r.get("incremental") or {}).get("kind"),
|
| 216 |
+
"n_added": ((r.get("incremental") or {}).get("delta") or {}).get("n_added"),
|
| 217 |
+
"n_unchanged": ((r.get("incremental") or {}).get("delta") or {}).get("n_unchanged"),
|
| 218 |
+
}
|
| 219 |
+
for r in results
|
| 220 |
+
],
|
| 221 |
+
indent=2,
|
| 222 |
+
default=str,
|
| 223 |
+
))
|
| 224 |
+
return 1 if any(r.get("error") for r in results) else 0
|
| 225 |
+
if args.cmd == "verify":
|
| 226 |
+
from .catalog import indexable_countries
|
| 227 |
+
from .verify import verify_source
|
| 228 |
+
|
| 229 |
+
slugs = []
|
| 230 |
+
if args.all:
|
| 231 |
+
slugs = [c["slug"] for c in indexable_countries()]
|
| 232 |
+
if args.limit:
|
| 233 |
+
slugs = slugs[: int(args.limit)]
|
| 234 |
+
elif args.source:
|
| 235 |
+
slugs = [args.source]
|
| 236 |
+
else:
|
| 237 |
+
print(json.dumps({"error": "pass --source or --all"}, indent=2))
|
| 238 |
+
return 2
|
| 239 |
+
rows = []
|
| 240 |
+
failed = 0
|
| 241 |
+
for slug in slugs:
|
| 242 |
+
try:
|
| 243 |
+
row = verify_source(slug)
|
| 244 |
+
except Exception as exc:
|
| 245 |
+
row = {"slug": slug, "error": str(exc), "verification": {"admitted": False}}
|
| 246 |
+
rows.append(row)
|
| 247 |
+
if not (row.get("verification") or {}).get("admitted", False):
|
| 248 |
+
failed += 1
|
| 249 |
+
from collections import Counter
|
| 250 |
+
|
| 251 |
+
units = Counter(str(r.get("unit") or "") for r in rows)
|
| 252 |
+
mismatch = []
|
| 253 |
+
latin_blocked = []
|
| 254 |
+
for r in rows:
|
| 255 |
+
for chk in (r.get("verification") or {}).get("checks") or []:
|
| 256 |
+
if chk.get("id") != "heading_language":
|
| 257 |
+
continue
|
| 258 |
+
ev = chk.get("evidence") or {}
|
| 259 |
+
if chk.get("severity") == "fail" and not chk.get("passed"):
|
| 260 |
+
latin_blocked.append(r.get("slug"))
|
| 261 |
+
if "review samples" in str(chk.get("message") or ""):
|
| 262 |
+
mismatch.append(
|
| 263 |
+
{
|
| 264 |
+
"slug": r.get("slug"),
|
| 265 |
+
"document_language": ev.get("document_language"),
|
| 266 |
+
"heading_language": ev.get("heading_language"),
|
| 267 |
+
}
|
| 268 |
+
)
|
| 269 |
+
print(
|
| 270 |
+
json.dumps(
|
| 271 |
+
{
|
| 272 |
+
"n": len(rows),
|
| 273 |
+
"n_failed": failed,
|
| 274 |
+
"by_unit": dict(units),
|
| 275 |
+
"heading_mismatch": mismatch,
|
| 276 |
+
"latin_split_blocked": latin_blocked,
|
| 277 |
+
"countries": rows,
|
| 278 |
+
},
|
| 279 |
+
indent=2,
|
| 280 |
+
default=str,
|
| 281 |
+
)
|
| 282 |
+
)
|
| 283 |
+
return 1 if failed else 0
|
| 284 |
+
if args.cmd == "normalize-loop":
|
| 285 |
+
from .build import CACHE, ROOT
|
| 286 |
+
from .normalize_loop import (
|
| 287 |
+
_apply_job,
|
| 288 |
+
_scan_job,
|
| 289 |
+
append_progress,
|
| 290 |
+
apply_done,
|
| 291 |
+
cache_packs,
|
| 292 |
+
improve_from_reports,
|
| 293 |
+
load_generate_text,
|
| 294 |
+
run_parallel,
|
| 295 |
+
scan_done,
|
| 296 |
+
worker_count,
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
cache = Path(args.cache) if args.cache else CACHE
|
| 300 |
+
reports = Path(args.reports) if args.reports else ROOT / "reports" / "residuals"
|
| 301 |
+
out = Path(args.out) if args.out else ROOT / "llm-normalized"
|
| 302 |
+
packs = cache_packs(cache, slug=args.slug)
|
| 303 |
+
if args.limit:
|
| 304 |
+
packs = packs[: int(args.limit)]
|
| 305 |
+
workers = worker_count(args.workers)
|
| 306 |
+
progress = Path(args.progress) if args.progress else ROOT / "reports" / f"normalize_{args.stage}.jsonl"
|
| 307 |
+
|
| 308 |
+
def _pending(stage: str) -> tuple[list[tuple[str, str, str]], list[str]]:
|
| 309 |
+
jobs: list[tuple[str, str, str]] = []
|
| 310 |
+
skipped: list[str] = []
|
| 311 |
+
for slug, path in packs:
|
| 312 |
+
done = scan_done(reports, slug) if stage == "scan" else apply_done(out, slug)
|
| 313 |
+
if done and not args.force:
|
| 314 |
+
skipped.append(slug)
|
| 315 |
+
continue
|
| 316 |
+
dest = reports if stage == "scan" else out
|
| 317 |
+
jobs.append((slug, str(path), str(dest)))
|
| 318 |
+
return jobs, skipped
|
| 319 |
+
|
| 320 |
+
def _run(stage: str, worker) -> list[dict]:
|
| 321 |
+
jobs, skipped = _pending(stage)
|
| 322 |
+
total = len(jobs) + len(skipped)
|
| 323 |
+
done = len(skipped)
|
| 324 |
+
print(json.dumps({
|
| 325 |
+
"event": "start",
|
| 326 |
+
"stage": stage,
|
| 327 |
+
"workers": workers,
|
| 328 |
+
"done": done,
|
| 329 |
+
"pending": len(jobs),
|
| 330 |
+
"total": total,
|
| 331 |
+
"progress": str(progress),
|
| 332 |
+
}), flush=True)
|
| 333 |
+
state = {"done": done}
|
| 334 |
+
|
| 335 |
+
def _on_done(row: dict) -> None:
|
| 336 |
+
state["done"] += 1
|
| 337 |
+
print(json.dumps({
|
| 338 |
+
"event": stage,
|
| 339 |
+
"done": state["done"],
|
| 340 |
+
"total": total,
|
| 341 |
+
**row,
|
| 342 |
+
}), flush=True)
|
| 343 |
+
|
| 344 |
+
return run_parallel(jobs, worker, workers, progress_path=progress, on_done=_on_done)
|
| 345 |
+
|
| 346 |
+
if args.stage == "scan":
|
| 347 |
+
rows = _run("scan", _scan_job)
|
| 348 |
+
failed = [row for row in rows if row.get("error")]
|
| 349 |
+
print(json.dumps({"stage": "scan", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2))
|
| 350 |
+
return 1 if failed else 0
|
| 351 |
+
if args.stage == "apply":
|
| 352 |
+
rows = _run("apply", _apply_job)
|
| 353 |
+
failed = [row for row in rows if row.get("error")]
|
| 354 |
+
print(json.dumps({"stage": "apply", "workers": workers, "n": len(rows), "n_failed": len(failed)}, indent=2))
|
| 355 |
+
return 1 if failed else 0
|
| 356 |
+
def _on_pass(row: dict) -> None:
|
| 357 |
+
print(json.dumps({"event": "improve", **row}, ensure_ascii=False), flush=True)
|
| 358 |
+
append_progress(progress, {"event": "improve", **row})
|
| 359 |
+
|
| 360 |
+
def _improve():
|
| 361 |
+
print(json.dumps({
|
| 362 |
+
"event": "start",
|
| 363 |
+
"stage": "improve",
|
| 364 |
+
"passes": args.passes,
|
| 365 |
+
"reports": str(reports),
|
| 366 |
+
}), flush=True)
|
| 367 |
+
try:
|
| 368 |
+
generate = load_generate_text()
|
| 369 |
+
except Exception as exc:
|
| 370 |
+
print(json.dumps({"error": f"llm_router unavailable: {exc}"}), flush=True)
|
| 371 |
+
return None
|
| 372 |
+
return improve_from_reports(
|
| 373 |
+
reports,
|
| 374 |
+
generate,
|
| 375 |
+
max_passes=args.passes,
|
| 376 |
+
on_pass=_on_pass,
|
| 377 |
+
reset_unresolved=bool(args.force),
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
if args.stage == "improve":
|
| 381 |
+
result = _improve()
|
| 382 |
+
if result is None:
|
| 383 |
+
return 1
|
| 384 |
+
print(json.dumps({"stage": "improve", **result}, indent=2, ensure_ascii=False))
|
| 385 |
+
return 0
|
| 386 |
+
# run scans, then improves the script. Applying the script to every
|
| 387 |
+
# pack is the separate ``apply`` stage.
|
| 388 |
+
scan_rows = _run("scan", _scan_job)
|
| 389 |
+
failed = [row for row in scan_rows if row.get("error")]
|
| 390 |
+
if failed:
|
| 391 |
+
print(json.dumps({"stage": "run", "n_scanned": len(scan_rows), "n_failed": len(failed)}, indent=2))
|
| 392 |
+
return 1
|
| 393 |
+
improved = _improve()
|
| 394 |
+
if improved is None:
|
| 395 |
+
return 1
|
| 396 |
+
print(json.dumps(
|
| 397 |
+
{"stage": "run", "workers": workers, "improve": improved, "n_scanned": len(scan_rows)},
|
| 398 |
+
indent=2,
|
| 399 |
+
ensure_ascii=False,
|
| 400 |
+
default=str,
|
| 401 |
+
))
|
| 402 |
+
return 0
|
| 403 |
+
if args.cmd == "package-raw":
|
| 404 |
+
from .build import RELEASES
|
| 405 |
+
from .raw_package import default_instruments_dir, package_instruments
|
| 406 |
+
|
| 407 |
+
instruments = (
|
| 408 |
+
Path(args.instruments_dir)
|
| 409 |
+
if args.instruments_dir
|
| 410 |
+
else default_instruments_dir(args.iso or args.slug)
|
| 411 |
+
)
|
| 412 |
+
out = Path(args.out) if args.out else RELEASES / "raw-packs" / args.slug
|
| 413 |
+
meta = package_instruments(
|
| 414 |
+
instruments_dir=instruments,
|
| 415 |
+
out=out,
|
| 416 |
+
slug=args.slug,
|
| 417 |
+
source_dataset=args.source_dataset,
|
| 418 |
+
prior_pack=Path(args.prior_pack) if args.prior_pack else None,
|
| 419 |
+
)
|
| 420 |
+
print(json.dumps(meta, indent=2, default=str))
|
| 421 |
+
return 0
|
| 422 |
+
if args.cmd == "pack-shards":
|
| 423 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.export_norm import (
|
| 424 |
+
ExportRefused,
|
| 425 |
+
choose_export_command,
|
| 426 |
+
)
|
| 427 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.load_sharded_laws import (
|
| 428 |
+
load_sharded_laws,
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
source = Path(args.source)
|
| 432 |
+
siblings = [str(path.relative_to(source)) for path in source.rglob("*") if path.is_file()]
|
| 433 |
+
try:
|
| 434 |
+
command = choose_export_command(args.slug, siblings)
|
| 435 |
+
except ExportRefused as exc:
|
| 436 |
+
print(json.dumps({"error": str(exc), "slug": args.slug}))
|
| 437 |
+
return 2
|
| 438 |
+
if command != "load_sharded_laws":
|
| 439 |
+
print(json.dumps({
|
| 440 |
+
"error": "pack-shards only accepts sharded laws parquet",
|
| 441 |
+
"command": command,
|
| 442 |
+
"slug": args.slug,
|
| 443 |
+
}))
|
| 444 |
+
return 2
|
| 445 |
+
dataset = args.source_dataset or f"endomorphosis/ipfs_{args.slug}_laws"
|
| 446 |
+
try:
|
| 447 |
+
written = load_sharded_laws(
|
| 448 |
+
source,
|
| 449 |
+
Path(args.out),
|
| 450 |
+
slug=args.slug,
|
| 451 |
+
source_dataset=dataset,
|
| 452 |
+
source_revision=args.revision,
|
| 453 |
+
)
|
| 454 |
+
except (OSError, ValueError) as exc:
|
| 455 |
+
print(json.dumps({"error": str(exc), "slug": args.slug}))
|
| 456 |
+
return 2
|
| 457 |
+
print(json.dumps(written, indent=2))
|
| 458 |
+
return 0
|
| 459 |
+
return 1
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
if __name__ == "__main__":
|
| 463 |
+
raise SystemExit(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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Admit endomorphosis country-law rows that can fill a national gap.
|
| 2 |
+
|
| 3 |
+
``world_national_law`` stays thin for some countries while
|
| 4 |
+
``endomorphosis/ipfs_<slug>_laws`` already holds the statute text. A fill
|
| 5 |
+
may copy only a row that is still a queryable law after cleaning. Metadata
|
| 6 |
+
cards, website pages, newsletters, chrome, chapter captions, label tables,
|
| 7 |
+
municipal and other sub-national corpora, and the excluded national harvests
|
| 8 |
+
are refused. A shared
|
| 9 |
+
numeric document id is not a citation. One leading article or section heading
|
| 10 |
+
is copied onto the locator so the row can be queried. This module does not
|
| 11 |
+
download, does not upload, and does not rewrite statute text.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import re
|
| 18 |
+
from collections import Counter
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Iterable, Mapping
|
| 22 |
+
|
| 23 |
+
from ipfs_datasets_py.processors.legal_data.iso_slug_crosswalk import (
|
| 24 |
+
national_slug,
|
| 25 |
+
resolve_jurisdiction,
|
| 26 |
+
)
|
| 27 |
+
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.catalog import (
|
| 28 |
+
EXCLUDED_SLUGS,
|
| 29 |
+
)
|
| 30 |
+
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.structure import (
|
| 31 |
+
normalize_legal_text,
|
| 32 |
+
segment_exclusive,
|
| 33 |
+
)
|
| 34 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.atomic_corpus import (
|
| 35 |
+
expand_legal_record,
|
| 36 |
+
render_atomic,
|
| 37 |
+
)
|
| 38 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.schema import (
|
| 39 |
+
LEGAL_RECORD_FIELDS,
|
| 40 |
+
)
|
| 41 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.textutil import (
|
| 42 |
+
sha256_text,
|
| 43 |
+
)
|
| 44 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.document_role import (
|
| 45 |
+
classify_document_role,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
THIN_NATIONAL_DOCS = 10
|
| 49 |
+
FILL_NORMALIZER = "country-source-admit/v1"
|
| 50 |
+
_MAX_FILL_BYTES = 64 * 1024 * 1024
|
| 51 |
+
_NON_NATIONAL_MARKERS = ("_municipal", "_provincial", "_governorate", "_local")
|
| 52 |
+
_FILL_COLUMNS = (
|
| 53 |
+
"id",
|
| 54 |
+
"cid",
|
| 55 |
+
"entry_cid",
|
| 56 |
+
"title",
|
| 57 |
+
"instrument_title",
|
| 58 |
+
"text",
|
| 59 |
+
"body",
|
| 60 |
+
"language",
|
| 61 |
+
"jurisdiction",
|
| 62 |
+
"country",
|
| 63 |
+
"source_url",
|
| 64 |
+
"article_number",
|
| 65 |
+
"official_identifier",
|
| 66 |
+
"metadata_json",
|
| 67 |
+
"doc_type",
|
| 68 |
+
"source_official",
|
| 69 |
+
"source_policy",
|
| 70 |
+
"source_revision",
|
| 71 |
+
)
|
| 72 |
+
_LOCATORS = ("title", "chapter", "part", "article", "section")
|
| 73 |
+
_STRUCTURAL = frozenset({"title", "chapter", "part", "article", "section"})
|
| 74 |
+
_PROVISION_NUMBER = re.compile(
|
| 75 |
+
r"(?i)^(?:art(?:icle)?\.?|neni|nen|član|clan|section|sec\.?|paragraph|§|มาตรา)?\s*"
|
| 76 |
+
r"([0-9]{1,5}|[IVXLCDM]{1,8})\.?$"
|
| 77 |
+
)
|
| 78 |
+
_CAPTION_HEADING = re.compile(
|
| 79 |
+
r"(?i)^(cap[ií]tulo|chapter|titre|title|t[ií]tulo|secci[oó]n|section|part(?:ie)?|teil)\b"
|
| 80 |
+
)
|
| 81 |
+
_SENTENCE_END = re.compile(r"[.!?。؟](?:\s|$)")
|
| 82 |
+
_LEADING_ARTICLE = re.compile(
|
| 83 |
+
r"(?i)^(?:article|art\.?|neni|section|sec\.?)\s*([0-9]{1,5})\b"
|
| 84 |
+
)
|
| 85 |
+
_DROP_POLICIES = frozenset({
|
| 86 |
+
"archived_robots_disallowed",
|
| 87 |
+
"noarchive_meta",
|
| 88 |
+
"noindex_meta",
|
| 89 |
+
"robots_unreachable",
|
| 90 |
+
})
|
| 91 |
+
_NOTICE_RE = re.compile(
|
| 92 |
+
r"(?i)(\bnewsletter\b|\bblog\b|press release|communiqu[eé]|"
|
| 93 |
+
r"\bnews item\b|\bnotice board\b|^lista\s+\d)"
|
| 94 |
+
)
|
| 95 |
+
_CITATION_MARK = re.compile(
|
| 96 |
+
r"(?i)\b(?:nr|no|act|law|ordinance|gazette|loi|legge|gesetz|decree|code)\b"
|
| 97 |
+
)
|
| 98 |
+
_NOTICE_TYPES = frozenset({
|
| 99 |
+
"newsletter",
|
| 100 |
+
"blog",
|
| 101 |
+
"press",
|
| 102 |
+
"press_release",
|
| 103 |
+
"notice",
|
| 104 |
+
})
|
| 105 |
+
_STATUTORY = re.compile(
|
| 106 |
+
r"(?i)\b(?:shall|hereby|s'applique|gilt|enacted|pursuant)\b|يجب|بموجب"
|
| 107 |
+
)
|
| 108 |
+
_MIN_PROVISION = 40
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
@dataclass(frozen=True)
|
| 112 |
+
class SourceAdmission:
|
| 113 |
+
admitted: bool
|
| 114 |
+
reason: str
|
| 115 |
+
records: tuple[dict[str, object], ...]
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def admit_source_law(
|
| 119 |
+
row: Mapping[str, object],
|
| 120 |
+
*,
|
| 121 |
+
source_dataset: str,
|
| 122 |
+
source_revision: str,
|
| 123 |
+
) -> SourceAdmission:
|
| 124 |
+
"""Return queryable legal-record atoms, or a refusal with no text."""
|
| 125 |
+
|
| 126 |
+
slug = _slug(source_dataset)
|
| 127 |
+
if slug in EXCLUDED_SLUGS or _jurisdiction_slug(row) in EXCLUDED_SLUGS:
|
| 128 |
+
return _refuse("excluded")
|
| 129 |
+
if _non_national(slug):
|
| 130 |
+
return _refuse("not_national")
|
| 131 |
+
policy = row.get("source_policy")
|
| 132 |
+
if isinstance(policy, str) and policy in _DROP_POLICIES:
|
| 133 |
+
return _refuse("source_policy")
|
| 134 |
+
if row.get("source_official") is False:
|
| 135 |
+
return _refuse("unofficial")
|
| 136 |
+
raw_text = row.get("text") if isinstance(row.get("text"), str) else row.get("body")
|
| 137 |
+
cleaned = normalize_legal_text(raw_text if isinstance(raw_text, str) else "")
|
| 138 |
+
if not cleaned:
|
| 139 |
+
return _refuse("empty")
|
| 140 |
+
meta = _metadata(row.get("metadata_json"))
|
| 141 |
+
document_type = str(meta.get("document_type") or row.get("doc_type") or "")
|
| 142 |
+
title = _string(row.get("title"))
|
| 143 |
+
if _NOTICE_RE.search(title) or document_type.strip().casefold() in _NOTICE_TYPES:
|
| 144 |
+
return _refuse("notice")
|
| 145 |
+
language = _string(row.get("language"))
|
| 146 |
+
source_url = _string(row.get("source_url"))
|
| 147 |
+
labeled = {
|
| 148 |
+
"title": title,
|
| 149 |
+
"language": language,
|
| 150 |
+
"source_url": source_url,
|
| 151 |
+
"doc_type": document_type,
|
| 152 |
+
}
|
| 153 |
+
raw_role, _raw_reason = classify_document_role(
|
| 154 |
+
{**labeled, "text": raw_text if isinstance(raw_text, str) else cleaned}
|
| 155 |
+
)
|
| 156 |
+
if raw_role != "law":
|
| 157 |
+
return _refuse(raw_role)
|
| 158 |
+
role, _reason = classify_document_role({**labeled, "text": cleaned})
|
| 159 |
+
if role != "law":
|
| 160 |
+
return _refuse(role)
|
| 161 |
+
if not _provision_prose(cleaned):
|
| 162 |
+
return _refuse("not_queryable")
|
| 163 |
+
citation = _record_citation(row)
|
| 164 |
+
jurisdiction = _jurisdiction_code(row)
|
| 165 |
+
record = {
|
| 166 |
+
"entry_cid": _string(row.get("id")) or _string(row.get("cid")),
|
| 167 |
+
"title": title,
|
| 168 |
+
"text": cleaned,
|
| 169 |
+
"language": language,
|
| 170 |
+
"jurisdiction": jurisdiction,
|
| 171 |
+
"citation": citation or None,
|
| 172 |
+
"source_url": source_url or None,
|
| 173 |
+
"instrument_type": "statute",
|
| 174 |
+
"source_repo": source_dataset,
|
| 175 |
+
"source_revision": source_revision,
|
| 176 |
+
"provenance": {},
|
| 177 |
+
}
|
| 178 |
+
atoms = tuple(expand_legal_record(record))
|
| 179 |
+
kept = tuple(atom for atom in atoms if _law_atom(atom))
|
| 180 |
+
if not kept:
|
| 181 |
+
return _refuse("not_queryable")
|
| 182 |
+
stamped = tuple(_with_leading_heading(atom, language) for atom in kept)
|
| 183 |
+
if not _queryable(stamped, cleaned, citation):
|
| 184 |
+
return _refuse("not_queryable")
|
| 185 |
+
return SourceAdmission(True, "law", stamped)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def fill_source_rows(
|
| 189 |
+
rows: Iterable[Mapping[str, object]],
|
| 190 |
+
*,
|
| 191 |
+
source_dataset: str,
|
| 192 |
+
source_revision: str,
|
| 193 |
+
) -> dict[str, object]:
|
| 194 |
+
"""Admit a local batch. Refused rows contribute a reason and no text."""
|
| 195 |
+
|
| 196 |
+
admitted: list[dict[str, object]] = []
|
| 197 |
+
reasons: Counter[str] = Counter()
|
| 198 |
+
for row in rows:
|
| 199 |
+
decision = admit_source_law(
|
| 200 |
+
row,
|
| 201 |
+
source_dataset=source_dataset,
|
| 202 |
+
source_revision=source_revision,
|
| 203 |
+
)
|
| 204 |
+
reasons[decision.reason] += 1
|
| 205 |
+
if decision.admitted:
|
| 206 |
+
admitted.extend(decision.records)
|
| 207 |
+
return {
|
| 208 |
+
"source_dataset": source_dataset,
|
| 209 |
+
"source_revision": source_revision,
|
| 210 |
+
"admitted": admitted,
|
| 211 |
+
"reasons": dict(reasons),
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def national_gap_plan(card_docs: Mapping[str, int]) -> list[dict[str, object]]:
|
| 216 |
+
"""Name the country dataset that can fill a thin national card.
|
| 217 |
+
|
| 218 |
+
A card with more than 10 documents is not a gap. Belgium, Portugal,
|
| 219 |
+
Lithuania, and Ghana are listed as skipped. Nothing is downloaded.
|
| 220 |
+
"""
|
| 221 |
+
|
| 222 |
+
plan: list[dict[str, object]] = []
|
| 223 |
+
for code, docs in sorted(card_docs.items()):
|
| 224 |
+
if not isinstance(docs, int):
|
| 225 |
+
continue
|
| 226 |
+
token = str(code or "").strip().upper()
|
| 227 |
+
slug = national_slug(token) if token else None
|
| 228 |
+
if docs > THIN_NATIONAL_DOCS or not slug:
|
| 229 |
+
continue
|
| 230 |
+
source = f"endomorphosis/ipfs_{slug}_laws"
|
| 231 |
+
if slug in EXCLUDED_SLUGS:
|
| 232 |
+
plan.append(
|
| 233 |
+
{
|
| 234 |
+
"code": token,
|
| 235 |
+
"slug": slug,
|
| 236 |
+
"source_dataset": source,
|
| 237 |
+
"card_docs": docs,
|
| 238 |
+
"action": "skip",
|
| 239 |
+
"reason": "excluded",
|
| 240 |
+
}
|
| 241 |
+
)
|
| 242 |
+
continue
|
| 243 |
+
plan.append(
|
| 244 |
+
{
|
| 245 |
+
"code": token,
|
| 246 |
+
"slug": slug,
|
| 247 |
+
"source_dataset": source,
|
| 248 |
+
"card_docs": docs,
|
| 249 |
+
"action": "fill",
|
| 250 |
+
"reason": "thin_docs",
|
| 251 |
+
}
|
| 252 |
+
)
|
| 253 |
+
return plan
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def fill_country_parquet(
|
| 257 |
+
source_path: Path | str,
|
| 258 |
+
dest_dir: Path | str,
|
| 259 |
+
*,
|
| 260 |
+
source_dataset: str,
|
| 261 |
+
source_revision: str,
|
| 262 |
+
) -> dict[str, object]:
|
| 263 |
+
"""Write admitted legal-record rows from one local country parquet.
|
| 264 |
+
|
| 265 |
+
The file must already be on disk. A municipal corpus, an excluded
|
| 266 |
+
national harvest, or a file over 64 MiB is refused before any row is
|
| 267 |
+
read. Refused rows are counted and their text is not written.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
return fill_country_corpus(
|
| 271 |
+
[source_path],
|
| 272 |
+
dest_dir,
|
| 273 |
+
source_dataset=source_dataset,
|
| 274 |
+
source_revision=source_revision,
|
| 275 |
+
flush_atoms=10**12,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def fill_country_corpus(
|
| 280 |
+
source_paths: Iterable[Path | str],
|
| 281 |
+
dest_dir: Path | str,
|
| 282 |
+
*,
|
| 283 |
+
source_dataset: str,
|
| 284 |
+
source_revision: str,
|
| 285 |
+
flush_atoms: int = 8192,
|
| 286 |
+
) -> dict[str, object]:
|
| 287 |
+
"""Admit every local corpus part into queryable legal-record shards.
|
| 288 |
+
|
| 289 |
+
Files must already be on disk. An excluded harvest, a municipal or
|
| 290 |
+
other sub-national corpus, a missing file, or a part over 64 MiB is
|
| 291 |
+
refused before any row is read. Atoms are written in numbered parts so
|
| 292 |
+
a whole country is not held in memory. Refused rows are counted and
|
| 293 |
+
their text is not written. This function does not download or upload.
|
| 294 |
+
"""
|
| 295 |
+
|
| 296 |
+
slug = _slug(source_dataset)
|
| 297 |
+
if slug in EXCLUDED_SLUGS:
|
| 298 |
+
raise ValueError("excluded")
|
| 299 |
+
if _non_national(slug):
|
| 300 |
+
raise ValueError("not_national")
|
| 301 |
+
if not _is_sha(source_revision):
|
| 302 |
+
raise ValueError("source_revision")
|
| 303 |
+
if flush_atoms < 1:
|
| 304 |
+
raise ValueError("flush_atoms")
|
| 305 |
+
sources = [Path(path) for path in source_paths]
|
| 306 |
+
if not sources:
|
| 307 |
+
raise ValueError("source")
|
| 308 |
+
total_bytes = 0
|
| 309 |
+
for source in sources:
|
| 310 |
+
if not source.is_file():
|
| 311 |
+
raise ValueError("source")
|
| 312 |
+
size = source.stat().st_size
|
| 313 |
+
if size > _MAX_FILL_BYTES:
|
| 314 |
+
raise ValueError("source")
|
| 315 |
+
total_bytes += size
|
| 316 |
+
destination = Path(dest_dir) / slug
|
| 317 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 318 |
+
stale_report = destination / "report.json"
|
| 319 |
+
if stale_report.exists():
|
| 320 |
+
stale_report.unlink()
|
| 321 |
+
for stale in destination.glob("part-*.parquet"):
|
| 322 |
+
stale.unlink()
|
| 323 |
+
reasons: Counter[str] = Counter()
|
| 324 |
+
revisions: set[str] = set()
|
| 325 |
+
rows_read = 0
|
| 326 |
+
located = 0
|
| 327 |
+
atoms_written = 0
|
| 328 |
+
pending: list[dict[str, str | None]] = []
|
| 329 |
+
written: list[str] = []
|
| 330 |
+
|
| 331 |
+
def flush() -> None:
|
| 332 |
+
nonlocal pending
|
| 333 |
+
if not pending:
|
| 334 |
+
return
|
| 335 |
+
written.append(_write_fill_part(destination, len(written), pending))
|
| 336 |
+
pending = []
|
| 337 |
+
|
| 338 |
+
for source in sources:
|
| 339 |
+
for revision, decision in _iter_source_decisions(
|
| 340 |
+
source,
|
| 341 |
+
source_dataset=source_dataset,
|
| 342 |
+
source_revision=source_revision,
|
| 343 |
+
):
|
| 344 |
+
rows_read += 1
|
| 345 |
+
if isinstance(revision, str):
|
| 346 |
+
revisions.add(revision)
|
| 347 |
+
reasons[decision.reason] += 1
|
| 348 |
+
if not decision.admitted:
|
| 349 |
+
continue
|
| 350 |
+
for atom in decision.records:
|
| 351 |
+
pending.append(_encode_fill_atom(atom))
|
| 352 |
+
provenance = atom.get("provenance")
|
| 353 |
+
if isinstance(provenance, dict) and _located(provenance):
|
| 354 |
+
located += 1
|
| 355 |
+
atoms_written += 1
|
| 356 |
+
if len(pending) >= flush_atoms:
|
| 357 |
+
flush()
|
| 358 |
+
flush()
|
| 359 |
+
report = {
|
| 360 |
+
"source_dataset": source_dataset,
|
| 361 |
+
"source_revision": source_revision,
|
| 362 |
+
"source_path": str(sources[0]),
|
| 363 |
+
"source_files": [path.name for path in sources],
|
| 364 |
+
"source_bytes": total_bytes,
|
| 365 |
+
"slug": slug,
|
| 366 |
+
"rows_read": rows_read,
|
| 367 |
+
"atoms_written": atoms_written,
|
| 368 |
+
"atoms_with_locator": located,
|
| 369 |
+
"revisions": sorted(revisions),
|
| 370 |
+
"reasons": dict(reasons),
|
| 371 |
+
"coverage": "snapshot" if atoms_written else "not_published",
|
| 372 |
+
"corpus_complete": True,
|
| 373 |
+
"normalizer_version": FILL_NORMALIZER,
|
| 374 |
+
"files": written,
|
| 375 |
+
}
|
| 376 |
+
(destination / "report.json").write_text(
|
| 377 |
+
json.dumps(report, indent=2, sort_keys=True) + "\n",
|
| 378 |
+
encoding="utf-8",
|
| 379 |
+
)
|
| 380 |
+
return report
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def _fill_row(row: Mapping[str, object]) -> dict[str, object]:
|
| 384 |
+
title = row.get("title") if isinstance(row.get("title"), str) else row.get("instrument_title")
|
| 385 |
+
text = row.get("text") if isinstance(row.get("text"), str) else row.get("body")
|
| 386 |
+
entry = row.get("id") if isinstance(row.get("id"), str) else row.get("entry_cid")
|
| 387 |
+
if not isinstance(entry, str):
|
| 388 |
+
entry = row.get("cid")
|
| 389 |
+
return {
|
| 390 |
+
"id": entry if isinstance(entry, str) else "",
|
| 391 |
+
"title": title if isinstance(title, str) else "",
|
| 392 |
+
"text": text if isinstance(text, str) else "",
|
| 393 |
+
"language": row.get("language") if isinstance(row.get("language"), str) else "",
|
| 394 |
+
"jurisdiction": row.get("jurisdiction") if isinstance(row.get("jurisdiction"), str) else "",
|
| 395 |
+
"country": row.get("country") if isinstance(row.get("country"), str) else "",
|
| 396 |
+
"source_url": row.get("source_url") if isinstance(row.get("source_url"), str) else "",
|
| 397 |
+
"article_number": row.get("article_number") if isinstance(row.get("article_number"), str) else "",
|
| 398 |
+
"official_identifier": row.get("official_identifier")
|
| 399 |
+
if isinstance(row.get("official_identifier"), str)
|
| 400 |
+
else "",
|
| 401 |
+
"metadata_json": row.get("metadata_json") if isinstance(row.get("metadata_json"), str) else "",
|
| 402 |
+
"doc_type": row.get("doc_type") if isinstance(row.get("doc_type"), str) else "",
|
| 403 |
+
"source_official": row.get("source_official"),
|
| 404 |
+
"source_policy": row.get("source_policy"),
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _encode_fill_atom(atom: Mapping[str, object]) -> dict[str, str | None]:
|
| 409 |
+
provenance = atom.get("provenance")
|
| 410 |
+
copied = dict(provenance) if isinstance(provenance, dict) else {}
|
| 411 |
+
record: dict[str, object] = {field: None for field in LEGAL_RECORD_FIELDS}
|
| 412 |
+
record.update(
|
| 413 |
+
{
|
| 414 |
+
"jurisdiction": atom.get("jurisdiction"),
|
| 415 |
+
"admin_level": "country",
|
| 416 |
+
"instrument_type": "statute",
|
| 417 |
+
"citation": atom.get("citation"),
|
| 418 |
+
"title": atom.get("title"),
|
| 419 |
+
"text": atom.get("text"),
|
| 420 |
+
"language": atom.get("language"),
|
| 421 |
+
"source_url": atom.get("source_url"),
|
| 422 |
+
"content_sha256": atom.get("content_sha256")
|
| 423 |
+
or sha256_text(atom.get("text") if isinstance(atom.get("text"), str) else None),
|
| 424 |
+
"scraper_id": "country_laws_ir",
|
| 425 |
+
"normalizer_version": FILL_NORMALIZER,
|
| 426 |
+
"source_repo": atom.get("source_repo"),
|
| 427 |
+
"source_revision": atom.get("source_revision"),
|
| 428 |
+
"entry_cid": atom.get("entry_cid"),
|
| 429 |
+
"provenance": copied,
|
| 430 |
+
}
|
| 431 |
+
)
|
| 432 |
+
copied["jsonld"] = render_atomic(record, "jsonld")
|
| 433 |
+
encoded: dict[str, str | None] = {}
|
| 434 |
+
for field in LEGAL_RECORD_FIELDS:
|
| 435 |
+
value = record.get(field)
|
| 436 |
+
if field == "provenance":
|
| 437 |
+
encoded[field] = json.dumps(copied, sort_keys=True, ensure_ascii=False)
|
| 438 |
+
elif value is None:
|
| 439 |
+
encoded[field] = None
|
| 440 |
+
else:
|
| 441 |
+
encoded[field] = str(value)
|
| 442 |
+
return encoded
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _fill_schema():
|
| 446 |
+
import pyarrow as pa
|
| 447 |
+
|
| 448 |
+
return pa.schema([pa.field(name, pa.string()) for name in LEGAL_RECORD_FIELDS])
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _is_sha(value: object) -> bool:
|
| 452 |
+
return (
|
| 453 |
+
isinstance(value, str)
|
| 454 |
+
and len(value) == 40
|
| 455 |
+
and all(char in "0123456789abcdef" for char in value)
|
| 456 |
+
)
|
| 457 |
+
|
| 458 |
+
|
| 459 |
+
def _refuse(reason: str) -> SourceAdmission:
|
| 460 |
+
return SourceAdmission(False, reason, ())
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def _iter_source_decisions(
|
| 464 |
+
source: Path,
|
| 465 |
+
*,
|
| 466 |
+
source_dataset: str,
|
| 467 |
+
source_revision: str,
|
| 468 |
+
):
|
| 469 |
+
import pyarrow.parquet as pq
|
| 470 |
+
|
| 471 |
+
columns = [name for name in _FILL_COLUMNS if name in pq.read_schema(source).names]
|
| 472 |
+
parquet = pq.ParquetFile(source)
|
| 473 |
+
for batch in parquet.iter_batches(batch_size=256, columns=columns):
|
| 474 |
+
for row in batch.to_pylist():
|
| 475 |
+
row_revision = row.get("source_revision")
|
| 476 |
+
revision = row_revision if _is_sha(row_revision) else source_revision
|
| 477 |
+
decision = admit_source_law(
|
| 478 |
+
_fill_row(row),
|
| 479 |
+
source_dataset=source_dataset,
|
| 480 |
+
source_revision=revision,
|
| 481 |
+
)
|
| 482 |
+
yield revision, decision
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def _write_fill_part(
|
| 486 |
+
destination: Path,
|
| 487 |
+
part_index: int,
|
| 488 |
+
encoded: list[dict[str, str | None]],
|
| 489 |
+
) -> str:
|
| 490 |
+
import pyarrow as pa
|
| 491 |
+
import pyarrow.parquet as pq
|
| 492 |
+
|
| 493 |
+
part = destination / f"part-{part_index:06d}.parquet"
|
| 494 |
+
table = pa.Table.from_pylist(encoded, schema=_fill_schema())
|
| 495 |
+
pq.write_table(table, part, compression="zstd")
|
| 496 |
+
return str(part)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def _non_national(slug: str) -> bool:
|
| 500 |
+
return (not slug) or any(marker in slug for marker in _NON_NATIONAL_MARKERS)
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
def _slug(source_dataset: str) -> str:
|
| 504 |
+
name = str(source_dataset or "").strip()
|
| 505 |
+
if name.startswith("endomorphosis/"):
|
| 506 |
+
name = name.split("/", 1)[1]
|
| 507 |
+
if name.startswith("ipfs_") and name.endswith("_laws"):
|
| 508 |
+
return name[len("ipfs_") : -len("_laws")]
|
| 509 |
+
return ""
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _jurisdiction_slug(row: Mapping[str, object]) -> str:
|
| 513 |
+
resolved = resolve_jurisdiction(_string(row.get("jurisdiction")) or _string(row.get("country")))
|
| 514 |
+
if resolved is None or resolved.admin_level != "country" or not resolved.slug:
|
| 515 |
+
return ""
|
| 516 |
+
return resolved.slug
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _jurisdiction_code(row: Mapping[str, object]) -> str | None:
|
| 520 |
+
resolved = resolve_jurisdiction(_string(row.get("jurisdiction")) or _string(row.get("country")))
|
| 521 |
+
if resolved is None or resolved.admin_level != "country":
|
| 522 |
+
return None
|
| 523 |
+
return resolved.code
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _metadata(value: object) -> dict[str, object]:
|
| 527 |
+
if isinstance(value, dict):
|
| 528 |
+
return value
|
| 529 |
+
if isinstance(value, str) and value.strip().startswith("{"):
|
| 530 |
+
try:
|
| 531 |
+
loaded = json.loads(value)
|
| 532 |
+
except json.JSONDecodeError:
|
| 533 |
+
return {}
|
| 534 |
+
if isinstance(loaded, dict):
|
| 535 |
+
return loaded
|
| 536 |
+
return {}
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def _string(value: object) -> str:
|
| 540 |
+
if isinstance(value, str):
|
| 541 |
+
return value.strip()
|
| 542 |
+
return ""
|
| 543 |
+
|
| 544 |
+
|
| 545 |
+
def _provision_number(value: object) -> str:
|
| 546 |
+
"""Article, section, or paragraph number. A chapter label is not one."""
|
| 547 |
+
|
| 548 |
+
match = _PROVISION_NUMBER.match(_string(value))
|
| 549 |
+
if match is None:
|
| 550 |
+
return ""
|
| 551 |
+
return match.group(1)
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def _record_citation(row: Mapping[str, object]) -> str:
|
| 555 |
+
"""Instrument citation, or the provision number when the id is only digits.
|
| 556 |
+
|
| 557 |
+
Country rows store a shared document number in ``official_identifier``.
|
| 558 |
+
That number is the same on every article, so it is not a provision citation.
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
official = _string(row.get("official_identifier"))
|
| 562 |
+
number = _provision_number(row.get("article_number"))
|
| 563 |
+
title = _string(row.get("title"))
|
| 564 |
+
if (
|
| 565 |
+
official
|
| 566 |
+
and official != title
|
| 567 |
+
and not official.isdigit()
|
| 568 |
+
and re.search(r"\d", official)
|
| 569 |
+
and _CITATION_MARK.search(official)
|
| 570 |
+
):
|
| 571 |
+
return official
|
| 572 |
+
return number
|
| 573 |
+
|
| 574 |
+
|
| 575 |
+
def _provision_prose(text: str) -> bool:
|
| 576 |
+
"""True when the cleaned row is a provision, not a caption or a label table."""
|
| 577 |
+
|
| 578 |
+
if _caption_shell(text):
|
| 579 |
+
return False
|
| 580 |
+
if _STATUTORY.search(text):
|
| 581 |
+
return True
|
| 582 |
+
for raw in text.splitlines():
|
| 583 |
+
line = raw.strip()
|
| 584 |
+
if not line or _CAPTION_HEADING.match(line):
|
| 585 |
+
continue
|
| 586 |
+
words = re.findall(r"[^\W\d_]{2,}", line)
|
| 587 |
+
if len(words) >= 8 and _SENTENCE_END.search(line):
|
| 588 |
+
return True
|
| 589 |
+
letters = re.findall(r"[^\W\d_]", line)
|
| 590 |
+
if len(letters) >= 40:
|
| 591 |
+
return True
|
| 592 |
+
return False
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _caption_shell(text: str) -> bool:
|
| 596 |
+
"""A chapter or title line plus a label, with no provision sentence."""
|
| 597 |
+
|
| 598 |
+
lines = [line.strip() for line in text.splitlines() if line.strip()]
|
| 599 |
+
if not lines or len(lines) > 4 or not _CAPTION_HEADING.match(lines[0]):
|
| 600 |
+
return False
|
| 601 |
+
if _STATUTORY.search(text):
|
| 602 |
+
return False
|
| 603 |
+
for line in lines:
|
| 604 |
+
words = re.findall(r"[^\W\d_]{2,}", line)
|
| 605 |
+
if len(words) >= 8 and _SENTENCE_END.search(line):
|
| 606 |
+
return False
|
| 607 |
+
return True
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def _with_leading_heading(atom: dict[str, object], language: str) -> dict[str, object]:
|
| 611 |
+
"""Copy one leading article or section number onto the unsplit atom."""
|
| 612 |
+
|
| 613 |
+
provenance = atom.get("provenance")
|
| 614 |
+
text = atom.get("text")
|
| 615 |
+
if not isinstance(provenance, dict) or not isinstance(text, str):
|
| 616 |
+
return atom
|
| 617 |
+
if _located(provenance):
|
| 618 |
+
return atom
|
| 619 |
+
leading = _LEADING_ARTICLE.match(text.lstrip())
|
| 620 |
+
if leading is not None:
|
| 621 |
+
number = leading.group(1)
|
| 622 |
+
provenance["article"] = number
|
| 623 |
+
provenance.setdefault("section", number)
|
| 624 |
+
provenance.setdefault("hierarchy_path", f"Article {number}")
|
| 625 |
+
statute = provenance.get("statute")
|
| 626 |
+
if not isinstance(statute, str) or not statute.strip():
|
| 627 |
+
provenance["statute"] = number
|
| 628 |
+
return atom
|
| 629 |
+
units = [
|
| 630 |
+
unit
|
| 631 |
+
for unit in segment_exclusive(text, language=language)
|
| 632 |
+
if unit.kind in _STRUCTURAL and unit.number and len(unit.body.strip()) >= 16
|
| 633 |
+
]
|
| 634 |
+
if not units:
|
| 635 |
+
return atom
|
| 636 |
+
numbers = {unit.number for unit in units}
|
| 637 |
+
if len(numbers) != 1:
|
| 638 |
+
return atom
|
| 639 |
+
lead = min(units, key=lambda unit: unit.char_start)
|
| 640 |
+
if lead.char_start > 80:
|
| 641 |
+
return atom
|
| 642 |
+
number = lead.number
|
| 643 |
+
kind = "article" if any(unit.kind == "article" for unit in units) else lead.kind
|
| 644 |
+
if kind == "article":
|
| 645 |
+
provenance["article"] = number
|
| 646 |
+
provenance.setdefault("section", number)
|
| 647 |
+
elif kind == "section":
|
| 648 |
+
provenance.setdefault("section", number)
|
| 649 |
+
elif kind in {"chapter", "part", "title"}:
|
| 650 |
+
provenance.setdefault(kind, number)
|
| 651 |
+
else:
|
| 652 |
+
return atom
|
| 653 |
+
if lead.hierarchy_path:
|
| 654 |
+
provenance.setdefault("hierarchy_path", lead.hierarchy_path)
|
| 655 |
+
statute = provenance.get("statute")
|
| 656 |
+
if not isinstance(statute, str) or not statute.strip():
|
| 657 |
+
provenance["statute"] = number
|
| 658 |
+
return atom
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def _located(provenance: Mapping[str, object]) -> bool:
|
| 662 |
+
for key in _LOCATORS:
|
| 663 |
+
value = provenance.get(key)
|
| 664 |
+
if isinstance(value, str) and value.strip():
|
| 665 |
+
return True
|
| 666 |
+
return False
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def _law_atom(atom: Mapping[str, object]) -> bool:
|
| 670 |
+
text = atom.get("text")
|
| 671 |
+
provenance = atom.get("provenance")
|
| 672 |
+
if not isinstance(text, str) or not text.strip():
|
| 673 |
+
return False
|
| 674 |
+
if not isinstance(provenance, dict):
|
| 675 |
+
return False
|
| 676 |
+
return provenance.get("document_role") == "law"
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def _queryable(
|
| 680 |
+
atoms: tuple[dict[str, object], ...],
|
| 681 |
+
cleaned: str,
|
| 682 |
+
citation: str,
|
| 683 |
+
) -> bool:
|
| 684 |
+
if any(_has_locator(atom) for atom in atoms):
|
| 685 |
+
return True
|
| 686 |
+
if len(cleaned) >= _MIN_PROVISION and _STATUTORY.search(cleaned):
|
| 687 |
+
return True
|
| 688 |
+
return bool(citation) and len(cleaned) >= _MIN_PROVISION
|
| 689 |
+
|
| 690 |
+
|
| 691 |
+
def _has_locator(atom: Mapping[str, object]) -> bool:
|
| 692 |
+
provenance = atom.get("provenance")
|
| 693 |
+
if not isinstance(provenance, dict):
|
| 694 |
+
return False
|
| 695 |
+
for key in _LOCATORS:
|
| 696 |
+
value = provenance.get(key)
|
| 697 |
+
if isinstance(value, str) and value.strip():
|
| 698 |
+
return True
|
| 699 |
+
path = provenance.get("hierarchy_path")
|
| 700 |
+
return isinstance(path, str) and any(
|
| 701 |
+
label in path for label in ("Title ", "Chapter ", "Part ", "Article ", "Section ")
|
| 702 |
+
)
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/auth.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Hugging Face auth helpers.
|
| 2 |
+
|
| 3 |
+
Default reads stay anonymous. Gap scans and JusticeDAO uploads may use the
|
| 4 |
+
operator token from the Hugging Face cache file or the environment. The token
|
| 5 |
+
is never logged.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import os
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def configure_hf() -> None:
|
| 15 |
+
"""Do not implicitly pick up ambient tokens for anonymous public reads."""
|
| 16 |
+
os.environ.setdefault("HF_HUB_DISABLE_IMPLICIT_TOKEN", "1")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def public_token() -> bool:
|
| 20 |
+
"""huggingface_hub `token=False` means anonymous (do not pick up env tokens)."""
|
| 21 |
+
return False
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def operator_token() -> str | bool:
|
| 25 |
+
"""Return a token for authenticated Hub reads/writes, or False if none."""
|
| 26 |
+
for key in ("HF_TOKEN", "HUGGING_FACE_HUB_TOKEN"):
|
| 27 |
+
value = (os.environ.get(key) or "").strip()
|
| 28 |
+
if value:
|
| 29 |
+
return value
|
| 30 |
+
path = Path.home() / ".cache" / "huggingface" / "token"
|
| 31 |
+
if path.is_file():
|
| 32 |
+
try:
|
| 33 |
+
value = path.read_text(encoding="utf-8").strip()
|
| 34 |
+
except OSError:
|
| 35 |
+
return False
|
| 36 |
+
if value:
|
| 37 |
+
return value
|
| 38 |
+
return False
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/bm25.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from collections import defaultdict
|
| 7 |
+
from typing import Any, Iterable
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 13 |
+
from .tokenize import tokenize
|
| 14 |
+
|
| 15 |
+
K1 = 1.2
|
| 16 |
+
B = 0.75
|
| 17 |
+
TITLE_WEIGHT = 5.0
|
| 18 |
+
BODY_WEIGHT = 1.0
|
| 19 |
+
POSTING_ROWS_PER_RECORD = 4096
|
| 20 |
+
TERMS_PER_SHARD = 4096
|
| 21 |
+
MAX_QUERY_TERMS = 64
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _idf(n_docs: int, df: int) -> float:
|
| 25 |
+
# rank_bm25 Okapi: ln((N - df + 0.5) / (df + 0.5) + 1)
|
| 26 |
+
return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def build_index(corpus: pd.DataFrame) -> dict[str, Any]:
|
| 30 |
+
n = len(corpus)
|
| 31 |
+
titles = corpus["title"].fillna("").astype(str).tolist()
|
| 32 |
+
bodies = corpus["body"].fillna("").astype(str).tolist()
|
| 33 |
+
title_toks = [tokenize(t) for t in titles]
|
| 34 |
+
body_toks = [tokenize(t) for t in bodies]
|
| 35 |
+
|
| 36 |
+
title_len = np.array([len(t) for t in title_toks], dtype=np.int32)
|
| 37 |
+
body_len = np.array([len(t) for t in body_toks], dtype=np.int32)
|
| 38 |
+
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
|
| 39 |
+
avgdl = float(doc_len.mean()) if n else 0.0
|
| 40 |
+
|
| 41 |
+
# term -> {doc: [title_tf, body_tf]}
|
| 42 |
+
postings: dict[str, dict[int, list[int]]] = defaultdict(dict)
|
| 43 |
+
for i, (tt, bt) in enumerate(zip(title_toks, body_toks)):
|
| 44 |
+
tf_t: dict[str, int] = defaultdict(int)
|
| 45 |
+
tf_b: dict[str, int] = defaultdict(int)
|
| 46 |
+
for tok in tt:
|
| 47 |
+
tf_t[tok] += 1
|
| 48 |
+
for tok in bt:
|
| 49 |
+
tf_b[tok] += 1
|
| 50 |
+
for tok in set(tf_t) | set(tf_b):
|
| 51 |
+
postings[tok][i] = [int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0))]
|
| 52 |
+
|
| 53 |
+
terms = sorted(postings)
|
| 54 |
+
idf = {t: _idf(n, len(postings[t])) for t in terms}
|
| 55 |
+
|
| 56 |
+
doc_rows = []
|
| 57 |
+
for i, row in corpus.iterrows():
|
| 58 |
+
idx = int(row["document_index"])
|
| 59 |
+
doc_rows.append(
|
| 60 |
+
{
|
| 61 |
+
"entry_cid": row["entry_cid"],
|
| 62 |
+
"document_index": idx,
|
| 63 |
+
"law_cid": row.get("law_cid", ""),
|
| 64 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 65 |
+
"law_id": row.get("law_id", row.get("instrument_id", "")),
|
| 66 |
+
"source_id": row["source_id"],
|
| 67 |
+
"title": row["title"],
|
| 68 |
+
"instrument_title": row.get("instrument_title", ""),
|
| 69 |
+
"article_number": row.get("article_number", ""),
|
| 70 |
+
"article_title": row.get("article_title", ""),
|
| 71 |
+
"record_type": row["record_type"],
|
| 72 |
+
"language": row.get("language", ""),
|
| 73 |
+
"jurisdiction": row.get("jurisdiction", ""),
|
| 74 |
+
"title_length": int(title_len[idx]),
|
| 75 |
+
"body_length": int(body_len[idx]),
|
| 76 |
+
"document_length": int(round(doc_len[idx])),
|
| 77 |
+
"schema_version": SCHEMA_VERSION,
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
documents = pd.DataFrame(doc_rows).sort_values("document_index").reset_index(drop=True)
|
| 81 |
+
|
| 82 |
+
posting_rows = []
|
| 83 |
+
for term in terms:
|
| 84 |
+
items = sorted(postings[term].items())
|
| 85 |
+
chunks = [
|
| 86 |
+
items[i : i + POSTING_ROWS_PER_RECORD]
|
| 87 |
+
for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD)
|
| 88 |
+
]
|
| 89 |
+
n_chunks = len(chunks)
|
| 90 |
+
dfreq = len(items)
|
| 91 |
+
cfreq = sum(v[0] + v[1] for _, v in items)
|
| 92 |
+
for cidx, chunk in enumerate(chunks):
|
| 93 |
+
posting_rows.append(
|
| 94 |
+
{
|
| 95 |
+
"term": term,
|
| 96 |
+
"document_indices": [d for d, _ in chunk],
|
| 97 |
+
"title_frequencies": [v[0] for _, v in chunk],
|
| 98 |
+
"body_frequencies": [v[1] for _, v in chunk],
|
| 99 |
+
"tfs": [TITLE_WEIGHT * v[0] + BODY_WEIGHT * v[1] for _, v in chunk],
|
| 100 |
+
"lengths": [int(round(doc_len[d])) for d, _ in chunk],
|
| 101 |
+
"document_lengths": [int(round(doc_len[d])) for d, _ in chunk],
|
| 102 |
+
"document_frequency": int(dfreq),
|
| 103 |
+
"corpus_frequency": int(cfreq),
|
| 104 |
+
"idf": float(idf[term]),
|
| 105 |
+
"posting_chunk_index": int(cidx),
|
| 106 |
+
"posting_chunk_count": int(n_chunks),
|
| 107 |
+
"schema_version": SCHEMA_VERSION,
|
| 108 |
+
}
|
| 109 |
+
)
|
| 110 |
+
postings_df = pd.DataFrame(posting_rows)
|
| 111 |
+
|
| 112 |
+
stats = {
|
| 113 |
+
"k1": K1,
|
| 114 |
+
"b": B,
|
| 115 |
+
"title_weight": TITLE_WEIGHT,
|
| 116 |
+
"body_weight": BODY_WEIGHT,
|
| 117 |
+
"average_document_length": avgdl,
|
| 118 |
+
"tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1",
|
| 119 |
+
"max_query_terms": MAX_QUERY_TERMS,
|
| 120 |
+
"posting_rows_per_record": POSTING_ROWS_PER_RECORD,
|
| 121 |
+
"terms_per_shard": TERMS_PER_SHARD,
|
| 122 |
+
"n_docs": n,
|
| 123 |
+
"n_terms": len(terms),
|
| 124 |
+
"n_posting_rows": int(len(postings_df)),
|
| 125 |
+
"n_postings": int(sum(len(postings[t]) for t in terms)),
|
| 126 |
+
}
|
| 127 |
+
return {
|
| 128 |
+
"documents": documents,
|
| 129 |
+
"postings": postings_df,
|
| 130 |
+
"postings_map": postings,
|
| 131 |
+
"idf": idf,
|
| 132 |
+
"doc_len": doc_len,
|
| 133 |
+
"avgdl": avgdl,
|
| 134 |
+
"title_toks": title_toks,
|
| 135 |
+
"body_toks": body_toks,
|
| 136 |
+
"stats": stats,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _tf_score(tf: float, dl: float, avgdl: float) -> float:
|
| 141 |
+
denom = tf + K1 * (1.0 - B + B * (dl / avgdl if avgdl else 0.0))
|
| 142 |
+
if denom == 0:
|
| 143 |
+
return 0.0
|
| 144 |
+
return (tf * (K1 + 1.0)) / denom
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def score_query(
|
| 148 |
+
query: str,
|
| 149 |
+
index: dict[str, Any],
|
| 150 |
+
top_k: int = 10,
|
| 151 |
+
) -> list[tuple[int, float]]:
|
| 152 |
+
q_terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 153 |
+
if not q_terms:
|
| 154 |
+
return []
|
| 155 |
+
postings = index["postings_map"]
|
| 156 |
+
idf = index["idf"]
|
| 157 |
+
doc_len = index["doc_len"]
|
| 158 |
+
avgdl = index["avgdl"] or 1.0
|
| 159 |
+
scores: dict[int, float] = defaultdict(float)
|
| 160 |
+
for term in q_terms:
|
| 161 |
+
plist = postings.get(term)
|
| 162 |
+
if not plist:
|
| 163 |
+
continue
|
| 164 |
+
w = idf.get(term, 0.0)
|
| 165 |
+
for doc, (ttf, btf) in plist.items():
|
| 166 |
+
tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf
|
| 167 |
+
scores[doc] += w * _tf_score(tf, float(doc_len[doc]), avgdl)
|
| 168 |
+
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)
|
| 169 |
+
return ranked[:top_k]
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def bm25_neighbors(index: dict[str, Any], k: int = 8) -> list[list[tuple[int, float, list[str]]]]:
|
| 173 |
+
"""Top-k BM25 neighbors from title tokens (body prefix only if title is empty).
|
| 174 |
+
|
| 175 |
+
Each neighbor is (document_index, score, matched_terms).
|
| 176 |
+
"""
|
| 177 |
+
import heapq
|
| 178 |
+
|
| 179 |
+
n = index["stats"]["n_docs"]
|
| 180 |
+
postings = index["postings_map"]
|
| 181 |
+
idf = index["idf"]
|
| 182 |
+
doc_len = index["doc_len"]
|
| 183 |
+
avgdl = index["avgdl"] or 1.0
|
| 184 |
+
title_toks = index["title_toks"]
|
| 185 |
+
body_toks = index["body_toks"]
|
| 186 |
+
df_cap = max(256, min(1500, n // 40 or 1))
|
| 187 |
+
term_docs: dict[str, np.ndarray] = {}
|
| 188 |
+
term_pay: dict[str, np.ndarray] = {}
|
| 189 |
+
for term, plist in postings.items():
|
| 190 |
+
if len(plist) > df_cap:
|
| 191 |
+
continue
|
| 192 |
+
docs = np.fromiter(plist.keys(), dtype=np.int32, count=len(plist))
|
| 193 |
+
tfs = np.empty(len(plist), dtype=np.float64)
|
| 194 |
+
for j, (doc, (ttf, btf)) in enumerate(plist.items()):
|
| 195 |
+
tf = TITLE_WEIGHT * ttf + BODY_WEIGHT * btf
|
| 196 |
+
tfs[j] = _tf_score(tf, float(doc_len[doc]), avgdl)
|
| 197 |
+
term_docs[term] = docs
|
| 198 |
+
term_pay[term] = tfs * float(idf.get(term, 0.0))
|
| 199 |
+
|
| 200 |
+
neighbors: list[list[tuple[int, float, list[str]]]] = [[] for _ in range(n)]
|
| 201 |
+
step = 20000 if n >= 40000 else max(n, 1)
|
| 202 |
+
for i in range(n):
|
| 203 |
+
if i and i % step == 0:
|
| 204 |
+
print(f"bm25 neighbors {i}/{n}", flush=True)
|
| 205 |
+
q_terms = title_toks[i][:16] or body_toks[i][:16]
|
| 206 |
+
if not q_terms:
|
| 207 |
+
continue
|
| 208 |
+
tf_q: dict[str, int] = defaultdict(int)
|
| 209 |
+
for tok in q_terms:
|
| 210 |
+
tf_q[tok] += 1
|
| 211 |
+
scores: dict[int, float] = defaultdict(float)
|
| 212 |
+
matched: dict[int, set[str]] = defaultdict(set)
|
| 213 |
+
for term, qtf in tf_q.items():
|
| 214 |
+
docs = term_docs.get(term)
|
| 215 |
+
if docs is None:
|
| 216 |
+
continue
|
| 217 |
+
pay = term_pay[term] * qtf
|
| 218 |
+
for doc, val in zip(docs, pay):
|
| 219 |
+
di = int(doc)
|
| 220 |
+
if di != i:
|
| 221 |
+
scores[di] += float(val)
|
| 222 |
+
matched[di].add(term)
|
| 223 |
+
if scores:
|
| 224 |
+
top = heapq.nlargest(k, scores.items(), key=lambda kv: kv[1])
|
| 225 |
+
neighbors[i] = [(doc, score, sorted(matched[doc])) for doc, score in top]
|
| 226 |
+
print(f"bm25 neighbors {n}/{n}", flush=True)
|
| 227 |
+
return neighbors
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/build.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end build: normalize → incremental vectors → BM25 → graph → package.
|
| 2 |
+
|
| 3 |
+
Default mode is ``auto``: skip when the endomorphosis source revision is
|
| 4 |
+
unchanged, otherwise delta-refresh embeddings by ``entry_cid`` and rebuild
|
| 5 |
+
BM25/graph from the current corpus. Publication to ``justicedao/*`` is opt-in
|
| 6 |
+
via ``upload=True``.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
import traceback
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
from .sparse import export_sparse_graphrag
|
| 22 |
+
from .mem import MemAbort, checkpoint, log_mem
|
| 23 |
+
from .spill import spill_dir_for, spill_pickle
|
| 24 |
+
from .package import package_from_spill, package_release
|
| 25 |
+
from .catalog import get_country, indexable_countries, is_local_law_pack, target_repo
|
| 26 |
+
|
| 27 |
+
from .incremental import (
|
| 28 |
+
fetch_hub_prior,
|
| 29 |
+
load_embedding_cache,
|
| 30 |
+
load_prior_release,
|
| 31 |
+
load_release_vectors_by_cid,
|
| 32 |
+
merge_embedding_maps,
|
| 33 |
+
plan_rebuild,
|
| 34 |
+
save_embedding_cache,
|
| 35 |
+
)
|
| 36 |
+
from .normalize import build_corpus, load_source
|
| 37 |
+
from .auth import configure_hf
|
| 38 |
+
from .vectors import (
|
| 39 |
+
DIMENSION,
|
| 40 |
+
MODEL_NAME,
|
| 41 |
+
assemble_embeddings,
|
| 42 |
+
embeddings_by_cid,
|
| 43 |
+
layout_stub_vectors,
|
| 44 |
+
layout_vectors,
|
| 45 |
+
select_device,
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
ROOT = Path(os.environ.get("COUNTRY_LAWS_IR_ROOT", str(Path.home() / ".ipfs_datasets" / "country-laws-ir")))
|
| 49 |
+
CACHE = ROOT / "cache"
|
| 50 |
+
RELEASES = ROOT / "releases"
|
| 51 |
+
REPORTS = ROOT / "reports"
|
| 52 |
+
PROGRESS = ROOT / "progress.jsonl"
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _log(msg: str) -> None:
|
| 56 |
+
ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 57 |
+
print(f"[{ts}] {msg}", flush=True)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def record_progress(event: dict[str, Any]) -> None:
|
| 61 |
+
event = dict(event)
|
| 62 |
+
event.setdefault("ts", datetime.now(timezone.utc).isoformat())
|
| 63 |
+
PROGRESS.parent.mkdir(parents=True, exist_ok=True)
|
| 64 |
+
lock_path = PROGRESS.with_suffix(".lock")
|
| 65 |
+
with lock_path.open("a", encoding="utf-8") as lock_fh:
|
| 66 |
+
try:
|
| 67 |
+
import fcntl
|
| 68 |
+
|
| 69 |
+
fcntl.flock(lock_fh.fileno(), fcntl.LOCK_EX)
|
| 70 |
+
except Exception:
|
| 71 |
+
pass
|
| 72 |
+
with PROGRESS.open("a", encoding="utf-8") as f:
|
| 73 |
+
f.write(json.dumps(event, ensure_ascii=False) + "\n")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _prior_dir_for(
|
| 77 |
+
slug: str,
|
| 78 |
+
out: Path,
|
| 79 |
+
prior_dir: Path | None,
|
| 80 |
+
*,
|
| 81 |
+
fetch_hub: bool = True,
|
| 82 |
+
) -> Path | None:
|
| 83 |
+
if prior_dir is not None:
|
| 84 |
+
return Path(prior_dir)
|
| 85 |
+
if out.is_dir() and (out / "manifest.json").is_file():
|
| 86 |
+
return out
|
| 87 |
+
default = RELEASES / f"ipfs_{slug}_laws_ir"
|
| 88 |
+
if default.is_dir() and (default / "manifest.json").is_file() and default.resolve() != out.resolve():
|
| 89 |
+
return default
|
| 90 |
+
if not fetch_hub:
|
| 91 |
+
return None
|
| 92 |
+
hub = fetch_hub_prior(slug, cache_root=CACHE / "hub-ir")
|
| 93 |
+
if hub is not None:
|
| 94 |
+
_log(f"using justicedao prior {hub}")
|
| 95 |
+
return hub
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _encode_vectors(
|
| 99 |
+
*,
|
| 100 |
+
corpus: pd.DataFrame,
|
| 101 |
+
country_slug: str,
|
| 102 |
+
prior,
|
| 103 |
+
plan,
|
| 104 |
+
skip_vectors: bool,
|
| 105 |
+
device: str,
|
| 106 |
+
) -> tuple[dict[str, Any], str | None, dict[str, Any]]:
|
| 107 |
+
import gc
|
| 108 |
+
|
| 109 |
+
vector_report: dict[str, Any] = {"status": "stub"}
|
| 110 |
+
vector_blocker = None
|
| 111 |
+
if skip_vectors:
|
| 112 |
+
vectors = layout_stub_vectors(corpus, reason="skip_vectors flag")
|
| 113 |
+
return vectors, "skip_vectors", {"status": "stub", "reason": "skip_vectors"}
|
| 114 |
+
|
| 115 |
+
cid_cache_path = CACHE / "embeddings" / f"{country_slug}_by_cid.parquet"
|
| 116 |
+
prior_by_cid = {}
|
| 117 |
+
if plan.reuse_embeddings:
|
| 118 |
+
prior_by_cid = merge_embedding_maps(
|
| 119 |
+
load_embedding_cache(cid_cache_path),
|
| 120 |
+
None if prior is None else load_release_vectors_by_cid(prior.directory),
|
| 121 |
+
)
|
| 122 |
+
_log(f"embedding cache reused_cids={len(prior_by_cid)}")
|
| 123 |
+
try:
|
| 124 |
+
positional = CACHE / "embeddings" / f"{country_slug}.npy"
|
| 125 |
+
resolved, fallback = select_device(device)
|
| 126 |
+
if fallback:
|
| 127 |
+
_log(f"embedding device fallback requested={device} using={resolved}")
|
| 128 |
+
embeddings, vector_report = assemble_embeddings(
|
| 129 |
+
corpus,
|
| 130 |
+
prior_by_cid,
|
| 131 |
+
encode_missing=True,
|
| 132 |
+
device=resolved,
|
| 133 |
+
checkpoint_path=str(positional),
|
| 134 |
+
)
|
| 135 |
+
if (
|
| 136 |
+
vector_report.get("status") in {"stub_missing_encoder", "incomplete"}
|
| 137 |
+
and not int(vector_report.get("n_reused") or 0)
|
| 138 |
+
):
|
| 139 |
+
vector_blocker = vector_report.get("reason") or vector_report.get("status")
|
| 140 |
+
vectors = layout_stub_vectors(corpus, reason=str(vector_blocker))
|
| 141 |
+
return vectors, vector_blocker, vector_report
|
| 142 |
+
vectors = layout_vectors(corpus, embeddings)
|
| 143 |
+
n_reused = int(vector_report.get("n_reused") or 0)
|
| 144 |
+
n_encoded = int(vector_report.get("n_encoded") or 0)
|
| 145 |
+
n_missing = int(vector_report.get("n_missing") or 0)
|
| 146 |
+
if n_reused:
|
| 147 |
+
vectors["stats"]["n_reused"] = n_reused
|
| 148 |
+
if n_encoded:
|
| 149 |
+
vectors["stats"]["n_encoded"] = n_encoded
|
| 150 |
+
# A complete 384-d table is embedded. partial is only a real gap.
|
| 151 |
+
complete = n_missing == 0 and (n_reused + n_encoded) >= len(corpus) and len(corpus) > 0
|
| 152 |
+
if not complete:
|
| 153 |
+
vectors["stats"]["status"] = "partial"
|
| 154 |
+
vectors["stats"]["n_missing"] = n_missing
|
| 155 |
+
save_embedding_cache(
|
| 156 |
+
cid_cache_path,
|
| 157 |
+
merge_embedding_maps(prior_by_cid, embeddings_by_cid(corpus, embeddings)),
|
| 158 |
+
model_name=MODEL_NAME,
|
| 159 |
+
dimension=DIMENSION,
|
| 160 |
+
)
|
| 161 |
+
del embeddings
|
| 162 |
+
gc.collect()
|
| 163 |
+
_log(
|
| 164 |
+
f"vectors n={vectors['stats']['n_vectors']} shards={vectors['stats']['shard_count']} "
|
| 165 |
+
f"reused={vector_report.get('n_reused')} encoded={vector_report.get('n_encoded')}"
|
| 166 |
+
)
|
| 167 |
+
return vectors, None, vector_report
|
| 168 |
+
except Exception as exc:
|
| 169 |
+
vector_blocker = f"embedding_failed: {exc}"
|
| 170 |
+
_log(f"vector embedding failed; writing stub ({exc})")
|
| 171 |
+
vectors = layout_stub_vectors(corpus, reason=vector_blocker)
|
| 172 |
+
return vectors, vector_blocker, {"status": "failed", "reason": str(exc)}
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def build_country(
|
| 176 |
+
source: str,
|
| 177 |
+
out: Path | None = None,
|
| 178 |
+
upload: bool = False,
|
| 179 |
+
device: str = "cuda",
|
| 180 |
+
neighbor_k: int = 8,
|
| 181 |
+
skip_vectors: bool = False,
|
| 182 |
+
mode: str = "auto",
|
| 183 |
+
force: bool = False,
|
| 184 |
+
prior_dir: Path | None = None,
|
| 185 |
+
fetch_hub_prior_ir: bool = True,
|
| 186 |
+
renormalize: bool = False,
|
| 187 |
+
) -> dict[str, Any]:
|
| 188 |
+
from .normalize import preflight_local_shard_source
|
| 189 |
+
|
| 190 |
+
preflight_local_shard_source(source)
|
| 191 |
+
country = get_country(source)
|
| 192 |
+
if not country.get("indexable", True):
|
| 193 |
+
raise RuntimeError(f"{country['repo']} is excluded: {country.get('skip_reason')}")
|
| 194 |
+
repo = country["repo"]
|
| 195 |
+
out = Path(out) if out else RELEASES / f"ipfs_{country['slug']}_laws_ir"
|
| 196 |
+
local_dir = country.get("local_source_dir") or (
|
| 197 |
+
str(Path(source).resolve()) if is_local_law_pack(Path(source)) else None
|
| 198 |
+
)
|
| 199 |
+
_log(
|
| 200 |
+
f"build start {repo} -> {out} "
|
| 201 |
+
f"(upload={upload} mode={mode} force={force} renormalize={renormalize}) local={local_dir}"
|
| 202 |
+
)
|
| 203 |
+
configure_hf()
|
| 204 |
+
CACHE.mkdir(parents=True, exist_ok=True)
|
| 205 |
+
REPORTS.mkdir(parents=True, exist_ok=True)
|
| 206 |
+
laws, articles, source_meta = load_source(local_dir or repo, CACHE)
|
| 207 |
+
_log(
|
| 208 |
+
f"source loaded laws={source_meta['n_laws_source']} "
|
| 209 |
+
f"articles={source_meta['n_articles_source']} rev={source_meta['source_revision']}"
|
| 210 |
+
)
|
| 211 |
+
prior = load_prior_release(
|
| 212 |
+
_prior_dir_for(
|
| 213 |
+
country["slug"],
|
| 214 |
+
out,
|
| 215 |
+
prior_dir,
|
| 216 |
+
fetch_hub=fetch_hub_prior_ir,
|
| 217 |
+
)
|
| 218 |
+
)
|
| 219 |
+
plan = plan_rebuild(
|
| 220 |
+
mode=mode,
|
| 221 |
+
source_meta=source_meta,
|
| 222 |
+
prior=prior,
|
| 223 |
+
force=force,
|
| 224 |
+
rebuild_stub_vectors=not skip_vectors,
|
| 225 |
+
)
|
| 226 |
+
if plan.skip_build and not renormalize:
|
| 227 |
+
_log(f"skip unchanged {country['slug']} rev={plan.source_revision}")
|
| 228 |
+
result = {
|
| 229 |
+
"country": country["slug"],
|
| 230 |
+
"source": repo,
|
| 231 |
+
"source_revision": source_meta["source_revision"],
|
| 232 |
+
"out": str(out),
|
| 233 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 234 |
+
"skipped": True,
|
| 235 |
+
"incremental": plan.to_dict(),
|
| 236 |
+
"normalization": {"n_out": plan.delta.current_count if plan.delta else 0},
|
| 237 |
+
"vector_blocker": None,
|
| 238 |
+
"neighbor_via": None,
|
| 239 |
+
"schema_version": "country-laws-ir-graphrag/v1",
|
| 240 |
+
}
|
| 241 |
+
record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 242 |
+
return result
|
| 243 |
+
|
| 244 |
+
corpus, norm_report = build_corpus(laws, articles, source_meta)
|
| 245 |
+
report_path = REPORTS / f"{country['slug']}_normalization.json"
|
| 246 |
+
report_path.write_text(json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 247 |
+
(REPORTS / "normalization.json").write_text(
|
| 248 |
+
json.dumps(norm_report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 249 |
+
)
|
| 250 |
+
_log(
|
| 251 |
+
f"normalized docs={len(corpus)} unit={norm_report['unit']} "
|
| 252 |
+
f"dropped={norm_report['n_dropped_total']} report={report_path}"
|
| 253 |
+
)
|
| 254 |
+
if corpus.empty:
|
| 255 |
+
raise RuntimeError("Normalized corpus is empty; refusing to package")
|
| 256 |
+
verdict = (norm_report or {}).get("verification") or {}
|
| 257 |
+
if verdict.get("blocks_graphrag") and not force:
|
| 258 |
+
from .verify import NormalizationAdmissionError
|
| 259 |
+
|
| 260 |
+
raise NormalizationAdmissionError(
|
| 261 |
+
f"{country['slug']} failed normalization verifiers: {verdict.get('failed_ids')}"
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
import gc
|
| 265 |
+
|
| 266 |
+
plan = plan_rebuild(
|
| 267 |
+
mode=mode,
|
| 268 |
+
source_meta=source_meta,
|
| 269 |
+
prior=prior,
|
| 270 |
+
current_corpus=corpus,
|
| 271 |
+
force=force,
|
| 272 |
+
rebuild_stub_vectors=not skip_vectors,
|
| 273 |
+
compare_normalized=renormalize and not force,
|
| 274 |
+
)
|
| 275 |
+
_log(
|
| 276 |
+
f"rebuild kind={plan.kind.value} reuse_embeddings={plan.reuse_embeddings} "
|
| 277 |
+
f"added={0 if plan.delta is None else plan.delta.n_added} "
|
| 278 |
+
f"removed={0 if plan.delta is None else plan.delta.n_removed}"
|
| 279 |
+
)
|
| 280 |
+
if plan.skip_build:
|
| 281 |
+
_log(f"skip unchanged after normalize {country['slug']}")
|
| 282 |
+
hub = _publish_unchanged_revision(
|
| 283 |
+
prior,
|
| 284 |
+
str(source_meta.get("source_revision") or ""),
|
| 285 |
+
country["slug"],
|
| 286 |
+
upload,
|
| 287 |
+
)
|
| 288 |
+
result = {
|
| 289 |
+
"country": country["slug"],
|
| 290 |
+
"source": repo,
|
| 291 |
+
"source_revision": source_meta["source_revision"],
|
| 292 |
+
"out": str(out),
|
| 293 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 294 |
+
"skipped": True,
|
| 295 |
+
"incremental": plan.to_dict(),
|
| 296 |
+
"normalization": {
|
| 297 |
+
"n_out": norm_report.get("n_out"),
|
| 298 |
+
"unit": norm_report.get("unit"),
|
| 299 |
+
"n_law_rows": norm_report.get("n_law_rows"),
|
| 300 |
+
"n_child_rows": norm_report.get("n_child_rows"),
|
| 301 |
+
},
|
| 302 |
+
"vector_blocker": None,
|
| 303 |
+
"neighbor_via": None,
|
| 304 |
+
"schema_version": "country-laws-ir-graphrag/v1",
|
| 305 |
+
}
|
| 306 |
+
if hub:
|
| 307 |
+
result["hub"] = hub
|
| 308 |
+
record_progress({"event": "skipped_unchanged", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 309 |
+
return result
|
| 310 |
+
|
| 311 |
+
n_docs = len(corpus)
|
| 312 |
+
spill = spill_dir_for(country["slug"], CACHE)
|
| 313 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 314 |
+
corpus_ckpt = CACHE / f"{country['slug']}_corpus.parquet"
|
| 315 |
+
corpus.to_parquet(corpus_ckpt, index=False)
|
| 316 |
+
checkpoint("after_normalize", log=_log)
|
| 317 |
+
|
| 318 |
+
vectors, vector_blocker, vector_report = _encode_vectors(
|
| 319 |
+
corpus=corpus,
|
| 320 |
+
country_slug=country["slug"],
|
| 321 |
+
prior=prior,
|
| 322 |
+
plan=plan,
|
| 323 |
+
skip_vectors=skip_vectors,
|
| 324 |
+
device=device,
|
| 325 |
+
)
|
| 326 |
+
spill_pickle(spill / "vectors.pkl", vectors)
|
| 327 |
+
del vectors
|
| 328 |
+
gc.collect()
|
| 329 |
+
checkpoint("vectors_spilled", log=_log)
|
| 330 |
+
extra_manifest = {"incremental": {**plan.to_dict(), "vectors": vector_report}}
|
| 331 |
+
|
| 332 |
+
neighbor_via = "hf_graphrag"
|
| 333 |
+
if out.exists():
|
| 334 |
+
import shutil as _shutil
|
| 335 |
+
|
| 336 |
+
_shutil.rmtree(out)
|
| 337 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 338 |
+
_log(f"sparse GraphRAG via hf_graphrag.bm25/graph parquet builders n={n_docs}")
|
| 339 |
+
sparse_report = export_sparse_graphrag(corpus, out)
|
| 340 |
+
extra_manifest["sparse"] = sparse_report
|
| 341 |
+
with open(spill / "vectors.pkl", "rb") as _vf:
|
| 342 |
+
import pickle as _pickle
|
| 343 |
+
|
| 344 |
+
vectors = _pickle.load(_vf)
|
| 345 |
+
dummy_bm25 = {
|
| 346 |
+
"documents": pd.DataFrame(),
|
| 347 |
+
"postings": pd.DataFrame(),
|
| 348 |
+
"stats": (sparse_report.get("bm25") or {}).get("bm25")
|
| 349 |
+
or (sparse_report.get("bm25") or {}),
|
| 350 |
+
}
|
| 351 |
+
dummy_graph = {
|
| 352 |
+
"nodes": pd.DataFrame(),
|
| 353 |
+
"edges": pd.DataFrame(),
|
| 354 |
+
"incoming": pd.DataFrame(),
|
| 355 |
+
"outgoing": pd.DataFrame(),
|
| 356 |
+
"stats": sparse_report.get("graph") or {},
|
| 357 |
+
}
|
| 358 |
+
code_root = Path(__file__).resolve().parent.parent
|
| 359 |
+
manifest = package_release(
|
| 360 |
+
out,
|
| 361 |
+
corpus,
|
| 362 |
+
dummy_bm25,
|
| 363 |
+
dummy_graph,
|
| 364 |
+
vectors,
|
| 365 |
+
source_meta,
|
| 366 |
+
country,
|
| 367 |
+
code_root,
|
| 368 |
+
normalization_report=norm_report,
|
| 369 |
+
extra_manifest=extra_manifest,
|
| 370 |
+
wipe=False,
|
| 371 |
+
skip_bm25_graph=True,
|
| 372 |
+
)
|
| 373 |
+
del corpus, vectors
|
| 374 |
+
gc.collect()
|
| 375 |
+
_log(f"packaged {out}")
|
| 376 |
+
result = {
|
| 377 |
+
"country": country["slug"],
|
| 378 |
+
"source": repo,
|
| 379 |
+
"source_revision": source_meta["source_revision"],
|
| 380 |
+
"out": str(out),
|
| 381 |
+
"target_hub_id": target_repo(country["slug"]),
|
| 382 |
+
"counts": manifest["counts"],
|
| 383 |
+
"normalization": norm_report,
|
| 384 |
+
"vector_blocker": vector_blocker,
|
| 385 |
+
"neighbor_via": neighbor_via,
|
| 386 |
+
"schema_version": manifest["schema_version"],
|
| 387 |
+
"skipped": False,
|
| 388 |
+
"incremental": extra_manifest["incremental"],
|
| 389 |
+
}
|
| 390 |
+
if upload:
|
| 391 |
+
from .upload import upload_release
|
| 392 |
+
|
| 393 |
+
hub = upload_release(out, target_repo(country["slug"]))
|
| 394 |
+
result["hub"] = hub
|
| 395 |
+
_log(f"uploaded {hub['url']} rev={hub['revision']}")
|
| 396 |
+
record_progress({"event": "uploaded", **result})
|
| 397 |
+
else:
|
| 398 |
+
record_progress({"event": "built_local", **{k: v for k, v in result.items() if k != "normalization"}})
|
| 399 |
+
return result
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def batch(
|
| 403 |
+
slugs: list[str] | None = None,
|
| 404 |
+
upload: bool = False,
|
| 405 |
+
skip_done: bool = True,
|
| 406 |
+
mode: str = "auto",
|
| 407 |
+
force: bool = False,
|
| 408 |
+
skip_vectors: bool = False,
|
| 409 |
+
) -> list[dict[str, Any]]:
|
| 410 |
+
"""Build every indexable country. Unchanged Hub revisions are skipped in auto mode.
|
| 411 |
+
|
| 412 |
+
``skip_done`` is kept for compatibility: it no longer skips a country whose
|
| 413 |
+
source revision changed. Pass ``force=True`` (or ``--no-skip-done``) to
|
| 414 |
+
rebuild regardless of CID overlap.
|
| 415 |
+
"""
|
| 416 |
+
targets = slugs or [c["slug"] for c in indexable_countries()]
|
| 417 |
+
if "malta" in targets:
|
| 418 |
+
targets = ["malta"] + [s for s in targets if s != "malta"]
|
| 419 |
+
results = []
|
| 420 |
+
rebuild_force = force or not skip_done
|
| 421 |
+
for slug in targets:
|
| 422 |
+
try:
|
| 423 |
+
results.append(
|
| 424 |
+
build_country(
|
| 425 |
+
slug,
|
| 426 |
+
upload=upload,
|
| 427 |
+
mode=mode,
|
| 428 |
+
force=rebuild_force,
|
| 429 |
+
skip_vectors=skip_vectors,
|
| 430 |
+
)
|
| 431 |
+
)
|
| 432 |
+
except Exception as exc:
|
| 433 |
+
_log(f"FAILED {slug}: {exc}")
|
| 434 |
+
record_progress(
|
| 435 |
+
{
|
| 436 |
+
"event": "failed",
|
| 437 |
+
"country": slug,
|
| 438 |
+
"error": str(exc),
|
| 439 |
+
"traceback": traceback.format_exc(),
|
| 440 |
+
}
|
| 441 |
+
)
|
| 442 |
+
continue
|
| 443 |
+
return results
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def reindex_from_gaps(
|
| 447 |
+
*,
|
| 448 |
+
upload: bool = False,
|
| 449 |
+
slugs: list[str] | None = None,
|
| 450 |
+
limit: int | None = None,
|
| 451 |
+
max_corpus_rows: int | None = 20_000,
|
| 452 |
+
skip_vectors: bool = False,
|
| 453 |
+
workers: int = 4,
|
| 454 |
+
mode: str = "auto",
|
| 455 |
+
force: bool = False,
|
| 456 |
+
all_indexable: bool = False,
|
| 457 |
+
device: str = "cuda",
|
| 458 |
+
renormalize: bool = False,
|
| 459 |
+
corpus_rows: dict[str, int] | None = None,
|
| 460 |
+
) -> list[dict[str, Any]]:
|
| 461 |
+
"""Rebuild country IR. Default is Hub gaps; ``all_indexable`` processes every catalog country.
|
| 462 |
+
|
| 463 |
+
``workers`` is a ceiling. Live memory, disk, and free GPU memory shrink it,
|
| 464 |
+
and a full host backs off instead of starting another country. Default cap
|
| 465 |
+
skips huge corpora (Finland, Dominican Republic). Pass
|
| 466 |
+
``max_corpus_rows=None`` to include them.
|
| 467 |
+
"""
|
| 468 |
+
from .catalog import indexable_countries
|
| 469 |
+
from .coverage import gap_report
|
| 470 |
+
|
| 471 |
+
if slugs is None:
|
| 472 |
+
if all_indexable:
|
| 473 |
+
rows = [{"slug": c["slug"], "corpus_rows": 0} for c in indexable_countries()]
|
| 474 |
+
_log(f"reindex all indexable n={len(rows)}")
|
| 475 |
+
else:
|
| 476 |
+
report = gap_report(workers=workers)
|
| 477 |
+
rows = [c for c in report["countries"] if c.get("rebuild")]
|
| 478 |
+
_log(
|
| 479 |
+
f"reindex targets n={len(rows)} "
|
| 480 |
+
f"(from scan rebuild={len(report.get('rebuild') or [])})"
|
| 481 |
+
)
|
| 482 |
+
rows.sort(key=lambda r: int(r.get("corpus_rows") or 0))
|
| 483 |
+
if max_corpus_rows is not None:
|
| 484 |
+
rows = [
|
| 485 |
+
r
|
| 486 |
+
for r in rows
|
| 487 |
+
if int(r.get("corpus_rows") or 0) <= int(max_corpus_rows)
|
| 488 |
+
]
|
| 489 |
+
if limit is not None:
|
| 490 |
+
rows = rows[: int(limit)]
|
| 491 |
+
queued = [(str(r["slug"]), int(r.get("corpus_rows") or 0)) for r in rows]
|
| 492 |
+
else:
|
| 493 |
+
known = corpus_rows or {}
|
| 494 |
+
queued = [(str(slug), int(known.get(str(slug)) or 0)) for slug in slugs]
|
| 495 |
+
kwargs = {
|
| 496 |
+
"upload": upload,
|
| 497 |
+
"mode": mode,
|
| 498 |
+
"force": force,
|
| 499 |
+
"skip_vectors": skip_vectors,
|
| 500 |
+
"fetch_hub_prior_ir": True,
|
| 501 |
+
"device": device,
|
| 502 |
+
"renormalize": renormalize,
|
| 503 |
+
}
|
| 504 |
+
ceiling = max(1, int(workers or 1))
|
| 505 |
+
_log(f"reindex adaptive ceiling={ceiling} countries={len(queued)} device={device}")
|
| 506 |
+
return _run_adaptive(queued, kwargs, ceiling)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def _run_adaptive(
|
| 510 |
+
queued: list[tuple[str, int]],
|
| 511 |
+
kwargs: dict[str, Any],
|
| 512 |
+
ceiling: int,
|
| 513 |
+
) -> list[dict[str, Any]]:
|
| 514 |
+
"""Start countries only while memory, disk, and a GPU have room."""
|
| 515 |
+
|
| 516 |
+
import multiprocessing as mp
|
| 517 |
+
import time
|
| 518 |
+
from concurrent.futures import FIRST_COMPLETED, ProcessPoolExecutor, wait
|
| 519 |
+
|
| 520 |
+
from .resources import (
|
| 521 |
+
admission_budget_gib,
|
| 522 |
+
admit_parallelism,
|
| 523 |
+
assign_device,
|
| 524 |
+
backoff_seconds,
|
| 525 |
+
can_admit,
|
| 526 |
+
job_slots,
|
| 527 |
+
probe_host,
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
try:
|
| 531 |
+
mp.set_start_method("spawn", force=False)
|
| 532 |
+
except RuntimeError:
|
| 533 |
+
pass
|
| 534 |
+
|
| 535 |
+
pending = list(enumerate(queued))
|
| 536 |
+
inflight: dict[Any, tuple[int, str, str, int]] = {}
|
| 537 |
+
results: list[dict[str, Any] | None] = [None] * len(queued)
|
| 538 |
+
pressure = 0
|
| 539 |
+
last_sig: tuple[Any, ...] | None = None
|
| 540 |
+
requested = str(kwargs.get("device") or "cuda")
|
| 541 |
+
with ProcessPoolExecutor(max_workers=ceiling, max_tasks_per_child=1) as pool:
|
| 542 |
+
while pending or inflight:
|
| 543 |
+
snap = probe_host()
|
| 544 |
+
admission = admit_parallelism(snap, ceiling=ceiling)
|
| 545 |
+
devices = admission.devices
|
| 546 |
+
if requested == "cpu":
|
| 547 |
+
devices = ("cpu",) if admission.workers else ()
|
| 548 |
+
elif requested.startswith("cuda:") and requested not in devices:
|
| 549 |
+
devices = ()
|
| 550 |
+
limit = admission.workers if devices else 0
|
| 551 |
+
signature = (limit, devices, admission.reason)
|
| 552 |
+
if signature != last_sig:
|
| 553 |
+
_log(
|
| 554 |
+
f"admit workers={limit} devices={list(devices)} reason={admission.reason} "
|
| 555 |
+
f"mem={snap.mem_available_gib:.1f}G sched={admission_budget_gib(snap):.1f}G "
|
| 556 |
+
f"disk={snap.disk_free_gib:.0f}G "
|
| 557 |
+
f"inflight={len(inflight)} pending={len(pending)}"
|
| 558 |
+
)
|
| 559 |
+
last_sig = signature
|
| 560 |
+
used = sum(item[3] for item in inflight.values())
|
| 561 |
+
started = False
|
| 562 |
+
while pending and devices:
|
| 563 |
+
_idx, (_source, rows) = pending[0]
|
| 564 |
+
cost = job_slots(rows)
|
| 565 |
+
if not can_admit(used, limit, cost):
|
| 566 |
+
break
|
| 567 |
+
device = assign_device(devices, tuple(item[2] for item in inflight.values()))
|
| 568 |
+
idx, (source, _rows) = pending.pop(0)
|
| 569 |
+
held = cost
|
| 570 |
+
task_kwargs = dict(kwargs)
|
| 571 |
+
task_kwargs["device"] = device
|
| 572 |
+
future = pool.submit(_reindex_one_country, (source, task_kwargs))
|
| 573 |
+
inflight[future] = (idx, source, device, held)
|
| 574 |
+
used += held
|
| 575 |
+
started = True
|
| 576 |
+
_log(f"admit start {source} device={device} slots={cost}")
|
| 577 |
+
if started:
|
| 578 |
+
pressure = 0
|
| 579 |
+
if inflight:
|
| 580 |
+
done, _pending_futs = wait(
|
| 581 |
+
set(inflight), timeout=5.0, return_when=FIRST_COMPLETED
|
| 582 |
+
)
|
| 583 |
+
for future in done:
|
| 584 |
+
idx, source, _device, _held = inflight.pop(future)
|
| 585 |
+
try:
|
| 586 |
+
results[idx] = future.result()
|
| 587 |
+
except Exception as exc:
|
| 588 |
+
_log(f"FAILED {source}: {exc}")
|
| 589 |
+
results[idx] = {"country": source, "skipped": False, "error": str(exc)}
|
| 590 |
+
continue
|
| 591 |
+
if not pending:
|
| 592 |
+
break
|
| 593 |
+
delay = backoff_seconds(admission.backoff_s or 15.0, pressure)
|
| 594 |
+
pressure += 1
|
| 595 |
+
_log(f"backoff {delay:.0f}s reason={admission.reason} pressure={pressure}")
|
| 596 |
+
time.sleep(delay)
|
| 597 |
+
return [row for row in results if row is not None]
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def _publish_unchanged_revision(
|
| 601 |
+
prior,
|
| 602 |
+
source_revision: str,
|
| 603 |
+
slug: str,
|
| 604 |
+
upload: bool,
|
| 605 |
+
) -> dict[str, Any] | None:
|
| 606 |
+
"""Upload the existing pack with the new raw SHA when the rows did not change."""
|
| 607 |
+
|
| 608 |
+
if prior is None or not upload:
|
| 609 |
+
return None
|
| 610 |
+
from .incremental import stamp_source_revision
|
| 611 |
+
|
| 612 |
+
manifest_path = Path(prior.directory) / "manifest.json"
|
| 613 |
+
if not manifest_path.is_file():
|
| 614 |
+
return None
|
| 615 |
+
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 616 |
+
if not isinstance(manifest, dict) or not stamp_source_revision(manifest, source_revision):
|
| 617 |
+
return None
|
| 618 |
+
manifest_path.write_text(json.dumps(manifest, indent=2) + "\n", encoding="utf-8")
|
| 619 |
+
from .upload import upload_release
|
| 620 |
+
|
| 621 |
+
hub = upload_release(Path(prior.directory), target_repo(slug))
|
| 622 |
+
_log(f"uploaded unchanged {hub['url']} source={source_revision}")
|
| 623 |
+
return hub
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def _external_build_owns(source: str) -> bool:
|
| 627 |
+
"""True when a build outside this pool already claimed the country."""
|
| 628 |
+
|
| 629 |
+
import os
|
| 630 |
+
|
| 631 |
+
root = Path(
|
| 632 |
+
os.environ.get(
|
| 633 |
+
"COUNTRY_LAWS_IR_ROOT",
|
| 634 |
+
str(Path.home() / ".ipfs_datasets" / "country-laws-ir"),
|
| 635 |
+
)
|
| 636 |
+
)
|
| 637 |
+
name = str(source).rstrip("/").rsplit("/", 1)[-1]
|
| 638 |
+
if name.startswith("ipfs_") and name.endswith("_laws"):
|
| 639 |
+
name = name[len("ipfs_") : -len("_laws")]
|
| 640 |
+
return (root / "external-builds" / name).is_file()
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def _reindex_one_country(item: tuple[str, dict[str, Any]]) -> dict[str, Any]:
|
| 644 |
+
slug, kwargs = item
|
| 645 |
+
if _external_build_owns(slug):
|
| 646 |
+
_log(f"skip {slug}: external build owns it")
|
| 647 |
+
return {"country": slug, "skipped": True, "reason": "external"}
|
| 648 |
+
_log(f"reindex start {slug}")
|
| 649 |
+
try:
|
| 650 |
+
return build_country(slug, **kwargs)
|
| 651 |
+
except Exception as exc:
|
| 652 |
+
_log(f"FAILED {slug}: {exc}")
|
| 653 |
+
record_progress(
|
| 654 |
+
{
|
| 655 |
+
"event": "failed",
|
| 656 |
+
"country": slug,
|
| 657 |
+
"error": str(exc),
|
| 658 |
+
"traceback": traceback.format_exc(),
|
| 659 |
+
}
|
| 660 |
+
)
|
| 661 |
+
return {"country": slug, "skipped": False, "error": str(exc)}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/catalog.py
ADDED
|
@@ -0,0 +1,307 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Catalog of endomorphosis/ipfs_*_laws corpora.
|
| 2 |
+
|
| 3 |
+
Belgium, Portugal, and Lithuania are incomplete Wayback harvests and are
|
| 4 |
+
excluded from indexing. american_municipal_law is out of scope.
|
| 5 |
+
|
| 6 |
+
The static ``COUNTRIES`` list is the fail-closed baseline. ``refresh_from_hub``
|
| 7 |
+
persists a sidecar cache of newly listed Hub datasets so incremental scrapes
|
| 8 |
+
of additional jurisdictions are indexable without a code change.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
EXCLUDED_SLUGS = {"belgium", "portugal", "lithuania", "ghana"}
|
| 19 |
+
EXCLUDED_REPOS = {f"endomorphosis/ipfs_{s}_laws" for s in EXCLUDED_SLUGS}
|
| 20 |
+
|
| 21 |
+
_SKIP_REASONS = {
|
| 22 |
+
"belgium": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)",
|
| 23 |
+
"portugal": "incomplete Wayback harvest (Diário da República archive shard)",
|
| 24 |
+
"lithuania": "incomplete Wayback harvest (e-TAR archive shard)",
|
| 25 |
+
"ghana": "thin scrape; Act PDF path blocked by robots",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def catalog_cache_path() -> Path:
|
| 30 |
+
root = Path(
|
| 31 |
+
os.environ.get(
|
| 32 |
+
"COUNTRY_LAWS_IR_ROOT",
|
| 33 |
+
str(Path.home() / ".ipfs_datasets" / "country-laws-ir"),
|
| 34 |
+
)
|
| 35 |
+
)
|
| 36 |
+
return root / "catalog_cache.json"
|
| 37 |
+
|
| 38 |
+
# Hub listing as of 2026-09-03. Refresh via `python -m country_laws_ir catalog --refresh`.
|
| 39 |
+
COUNTRIES: list[dict[str, Any]] = [
|
| 40 |
+
{"slug": "argentina", "repo": "endomorphosis/ipfs_argentina_laws", "name": "Argentina", "indexable": True},
|
| 41 |
+
{"slug": "australia", "repo": "endomorphosis/ipfs_australia_laws", "name": "Australia", "indexable": True},
|
| 42 |
+
{"slug": "austria", "repo": "endomorphosis/ipfs_austria_laws", "name": "Austria", "indexable": True},
|
| 43 |
+
{"slug": "bangladesh", "repo": "endomorphosis/ipfs_bangladesh_laws", "name": "Bangladesh", "indexable": True},
|
| 44 |
+
{"slug": "belgium", "repo": "endomorphosis/ipfs_belgium_laws", "name": "Belgium", "indexable": False,
|
| 45 |
+
"skip_reason": "incomplete Wayback harvest (Justel / Moniteur belge archive shard)"},
|
| 46 |
+
{"slug": "brazil", "repo": "endomorphosis/ipfs_brazil_laws", "name": "Brazil", "indexable": True},
|
| 47 |
+
{"slug": "canada", "repo": "endomorphosis/ipfs_canada_laws", "name": "Canada", "indexable": True},
|
| 48 |
+
{"slug": "chile", "repo": "endomorphosis/ipfs_chile_laws", "name": "Chile", "indexable": True},
|
| 49 |
+
{"slug": "china", "repo": "endomorphosis/ipfs_china_laws", "name": "China", "indexable": True},
|
| 50 |
+
{"slug": "colombia", "repo": "endomorphosis/ipfs_colombia_laws", "name": "Colombia", "indexable": True},
|
| 51 |
+
{"slug": "croatia", "repo": "endomorphosis/ipfs_croatia_laws", "name": "Croatia", "indexable": True},
|
| 52 |
+
{"slug": "czechia", "repo": "endomorphosis/ipfs_czechia_laws", "name": "Czechia", "indexable": True},
|
| 53 |
+
{"slug": "denmark", "repo": "endomorphosis/ipfs_denmark_laws", "name": "Denmark", "indexable": True},
|
| 54 |
+
{"slug": "egypt", "repo": "endomorphosis/ipfs_egypt_laws", "name": "Egypt", "indexable": True},
|
| 55 |
+
{"slug": "estonia", "repo": "endomorphosis/ipfs_estonia_laws", "name": "Estonia", "indexable": True},
|
| 56 |
+
{"slug": "eu", "repo": "endomorphosis/ipfs_eu_laws", "name": "European Union", "indexable": True},
|
| 57 |
+
{"slug": "finland", "repo": "endomorphosis/ipfs_finland_laws", "name": "Finland", "indexable": True},
|
| 58 |
+
{"slug": "france", "repo": "endomorphosis/ipfs_france_laws", "name": "France", "indexable": True},
|
| 59 |
+
{"slug": "ghana", "repo": "endomorphosis/ipfs_ghana_laws", "name": "Ghana", "indexable": False,
|
| 60 |
+
"skip_reason": "thin scrape; Act PDF path blocked by robots"},
|
| 61 |
+
{"slug": "germany", "repo": "endomorphosis/ipfs_germany_laws", "name": "Germany", "indexable": True},
|
| 62 |
+
{"slug": "greece", "repo": "endomorphosis/ipfs_greece_laws", "name": "Greece", "indexable": True},
|
| 63 |
+
{"slug": "hongkong", "repo": "endomorphosis/ipfs_hongkong_laws", "name": "Hong Kong", "indexable": True},
|
| 64 |
+
{"slug": "iceland", "repo": "endomorphosis/ipfs_iceland_laws", "name": "Iceland", "indexable": True},
|
| 65 |
+
{"slug": "hungary", "repo": "endomorphosis/ipfs_hungary_laws", "name": "Hungary", "indexable": True},
|
| 66 |
+
{"slug": "india", "repo": "endomorphosis/ipfs_india_laws", "name": "India", "indexable": True},
|
| 67 |
+
{"slug": "indonesia", "repo": "endomorphosis/ipfs_indonesia_laws", "name": "Indonesia", "indexable": True},
|
| 68 |
+
{"slug": "ireland", "repo": "endomorphosis/ipfs_ireland_laws", "name": "Ireland", "indexable": True},
|
| 69 |
+
{"slug": "israel", "repo": "endomorphosis/ipfs_israel_laws", "name": "Israel", "indexable": True},
|
| 70 |
+
{"slug": "japan", "repo": "endomorphosis/ipfs_japan_laws", "name": "Japan", "indexable": True},
|
| 71 |
+
{"slug": "kenya", "repo": "endomorphosis/ipfs_kenya_laws", "name": "Kenya", "indexable": True},
|
| 72 |
+
{"slug": "korea", "repo": "endomorphosis/ipfs_korea_laws", "name": "Korea (ROK)", "indexable": True},
|
| 73 |
+
{"slug": "kuwait", "repo": "endomorphosis/ipfs_kuwait_laws", "name": "Kuwait", "indexable": True},
|
| 74 |
+
{"slug": "latvia", "repo": "endomorphosis/ipfs_latvia_laws", "name": "Latvia", "indexable": True},
|
| 75 |
+
{"slug": "lithuania", "repo": "endomorphosis/ipfs_lithuania_laws", "name": "Lithuania", "indexable": False,
|
| 76 |
+
"skip_reason": "incomplete Wayback harvest (e-TAR archive shard)"},
|
| 77 |
+
{"slug": "luxembourg", "repo": "endomorphosis/ipfs_luxembourg_laws", "name": "Luxembourg", "indexable": True},
|
| 78 |
+
{"slug": "malaysia", "repo": "endomorphosis/ipfs_malaysia_laws", "name": "Malaysia", "indexable": True},
|
| 79 |
+
{"slug": "malta", "repo": "endomorphosis/ipfs_malta_laws", "name": "Malta", "indexable": True, "pilot": True},
|
| 80 |
+
{"slug": "morocco", "repo": "endomorphosis/ipfs_morocco_laws", "name": "Morocco", "indexable": True},
|
| 81 |
+
{"slug": "mexico", "repo": "endomorphosis/ipfs_mexico_laws", "name": "Mexico", "indexable": True},
|
| 82 |
+
{"slug": "netherlands", "repo": "endomorphosis/ipfs_netherlands_laws", "name": "Netherlands", "indexable": True},
|
| 83 |
+
{"slug": "newzealand", "repo": "endomorphosis/ipfs_newzealand_laws", "name": "New Zealand", "indexable": True},
|
| 84 |
+
{"slug": "nigeria", "repo": "endomorphosis/ipfs_nigeria_laws", "name": "Nigeria", "indexable": True},
|
| 85 |
+
{"slug": "norway", "repo": "endomorphosis/ipfs_norway_laws", "name": "Norway", "indexable": True},
|
| 86 |
+
{"slug": "pakistan", "repo": "endomorphosis/ipfs_pakistan_laws", "name": "Pakistan", "indexable": True},
|
| 87 |
+
{"slug": "philippines", "repo": "endomorphosis/ipfs_philippines_laws", "name": "Philippines", "indexable": True},
|
| 88 |
+
{"slug": "poland", "repo": "endomorphosis/ipfs_poland_laws", "name": "Poland", "indexable": True},
|
| 89 |
+
{"slug": "portugal", "repo": "endomorphosis/ipfs_portugal_laws", "name": "Portugal", "indexable": False,
|
| 90 |
+
"skip_reason": "incomplete Wayback harvest (Diário da República archive shard)"},
|
| 91 |
+
{"slug": "qatar", "repo": "endomorphosis/ipfs_qatar_laws", "name": "Qatar", "indexable": True},
|
| 92 |
+
{"slug": "russia", "repo": "endomorphosis/ipfs_russia_laws", "name": "Russia", "indexable": True},
|
| 93 |
+
{"slug": "saudiarabia", "repo": "endomorphosis/ipfs_saudiarabia_laws", "name": "Saudi Arabia", "indexable": True},
|
| 94 |
+
{"slug": "singapore", "repo": "endomorphosis/ipfs_singapore_laws", "name": "Singapore", "indexable": True},
|
| 95 |
+
{"slug": "slovakia", "repo": "endomorphosis/ipfs_slovakia_laws", "name": "Slovakia", "indexable": True},
|
| 96 |
+
{"slug": "southafrica", "repo": "endomorphosis/ipfs_southafrica_laws", "name": "South Africa", "indexable": True},
|
| 97 |
+
{"slug": "spain", "repo": "endomorphosis/ipfs_spain_laws", "name": "Spain", "indexable": True},
|
| 98 |
+
{"slug": "sweden", "repo": "endomorphosis/ipfs_sweden_laws", "name": "Sweden", "indexable": True},
|
| 99 |
+
{"slug": "switzerland", "repo": "endomorphosis/ipfs_switzerland_laws", "name": "Switzerland", "indexable": True},
|
| 100 |
+
{"slug": "taiwan", "repo": "endomorphosis/ipfs_taiwan_laws", "name": "Taiwan", "indexable": True},
|
| 101 |
+
{"slug": "thailand", "repo": "endomorphosis/ipfs_thailand_laws", "name": "Thailand", "indexable": True},
|
| 102 |
+
{"slug": "turkey", "repo": "endomorphosis/ipfs_turkey_laws", "name": "Turkey", "indexable": True},
|
| 103 |
+
{"slug": "uae", "repo": "endomorphosis/ipfs_uae_laws", "name": "United Arab Emirates", "indexable": True},
|
| 104 |
+
{"slug": "uk", "repo": "endomorphosis/ipfs_uk_laws", "name": "United Kingdom", "indexable": True},
|
| 105 |
+
{"slug": "ukraine", "repo": "endomorphosis/ipfs_ukraine_laws", "name": "Ukraine", "indexable": True},
|
| 106 |
+
{"slug": "vietnam", "repo": "endomorphosis/ipfs_vietnam_laws", "name": "Vietnam", "indexable": True},
|
| 107 |
+
{"slug": "bulgaria", "repo": "endomorphosis/ipfs_bulgaria_laws", "name": "Bulgaria", "indexable": True},
|
| 108 |
+
{"slug": "cyprus", "repo": "endomorphosis/ipfs_cyprus_laws", "name": "Cyprus", "indexable": True},
|
| 109 |
+
{"slug": "italy", "repo": "endomorphosis/ipfs_italy_laws", "name": "Italy", "indexable": True},
|
| 110 |
+
{"slug": "romania", "repo": "endomorphosis/ipfs_romania_laws", "name": "Romania", "indexable": True},
|
| 111 |
+
{"slug": "slovenia", "repo": "endomorphosis/ipfs_slovenia_laws", "name": "Slovenia", "indexable": True},
|
| 112 |
+
]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def load_cached_countries() -> list[dict[str, Any]]:
|
| 116 |
+
path = catalog_cache_path()
|
| 117 |
+
if not path.is_file():
|
| 118 |
+
return []
|
| 119 |
+
try:
|
| 120 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 121 |
+
except Exception:
|
| 122 |
+
return []
|
| 123 |
+
rows = payload.get("countries") if isinstance(payload, dict) else payload
|
| 124 |
+
if not isinstance(rows, list):
|
| 125 |
+
return []
|
| 126 |
+
out: list[dict[str, Any]] = []
|
| 127 |
+
for row in rows:
|
| 128 |
+
if isinstance(row, dict) and row.get("slug") and row.get("repo"):
|
| 129 |
+
out.append(dict(row))
|
| 130 |
+
return out
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def persist_catalog(countries: list[dict[str, Any]], path: Path | None = None) -> Path:
|
| 134 |
+
dest = path or catalog_cache_path()
|
| 135 |
+
dest.parent.mkdir(parents=True, exist_ok=True)
|
| 136 |
+
payload = {
|
| 137 |
+
"n": len(countries),
|
| 138 |
+
"indexable": sum(1 for c in countries if c.get("indexable")),
|
| 139 |
+
"countries": countries,
|
| 140 |
+
}
|
| 141 |
+
dest.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 142 |
+
return dest
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def merge_country_rows(
|
| 146 |
+
baseline: list[dict[str, Any]],
|
| 147 |
+
extra: list[dict[str, Any]],
|
| 148 |
+
) -> list[dict[str, Any]]:
|
| 149 |
+
"""Static catalog wins on slug; Hub extras fill gaps."""
|
| 150 |
+
by_slug = {str(row["slug"]): dict(row) for row in baseline if row.get("slug")}
|
| 151 |
+
for row in extra:
|
| 152 |
+
slug = str(row.get("slug") or "")
|
| 153 |
+
if not slug or slug in by_slug:
|
| 154 |
+
continue
|
| 155 |
+
by_slug[slug] = dict(row)
|
| 156 |
+
return [by_slug[k] for k in sorted(by_slug)]
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def all_countries() -> list[dict[str, Any]]:
|
| 160 |
+
return merge_country_rows(COUNTRIES, load_cached_countries())
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def is_local_law_pack(path: Path) -> bool:
|
| 164 |
+
"""True when a directory already has laws.parquet or text law shards."""
|
| 165 |
+
|
| 166 |
+
local = Path(path)
|
| 167 |
+
if not local.is_dir():
|
| 168 |
+
return False
|
| 169 |
+
if (local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file():
|
| 170 |
+
return True
|
| 171 |
+
data = local / "data"
|
| 172 |
+
if not data.is_dir():
|
| 173 |
+
return False
|
| 174 |
+
return any(
|
| 175 |
+
shard.name.startswith("laws-") and shard.suffix == ".parquet" and "_html" not in shard.name
|
| 176 |
+
for shard in data.glob("laws-*.parquet")
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def static_crosswalk_coverage() -> dict[str, Any]:
|
| 181 |
+
"""Compare reviewed crosswalk slugs with the static catalog.
|
| 182 |
+
|
| 183 |
+
A slug that is only in the crosswalk stays non-indexable. Alias keys
|
| 184 |
+
fold onto the canonical slug and are not a second country.
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
from ipfs_datasets_py.processors.legal_data.iso_slug_crosswalk import (
|
| 188 |
+
codes_in_crosswalk,
|
| 189 |
+
national_slug,
|
| 190 |
+
)
|
| 191 |
+
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.coverage import (
|
| 192 |
+
ALIAS_TO_CANONICAL,
|
| 193 |
+
canonical_slug,
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
slugs: set[str] = set()
|
| 197 |
+
for code in codes_in_crosswalk():
|
| 198 |
+
slug = national_slug(code)
|
| 199 |
+
if slug:
|
| 200 |
+
slugs.add(canonical_slug(slug))
|
| 201 |
+
known = {str(row["slug"]) for row in COUNTRIES if row.get("slug")}
|
| 202 |
+
return {
|
| 203 |
+
"crosswalk_slugs": sorted(slugs),
|
| 204 |
+
"in_static_catalog": sorted(slugs & known),
|
| 205 |
+
"not_in_static_catalog": sorted(slugs - known),
|
| 206 |
+
"missing_indexable": False,
|
| 207 |
+
"alias_keys_are_not_extra_countries": sorted(ALIAS_TO_CANONICAL),
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def get_country(source: str) -> dict[str, Any]:
|
| 212 |
+
source = source.strip()
|
| 213 |
+
# Local filtered pack: directory with data/laws.parquet (+ optional pack_meta.json)
|
| 214 |
+
from pathlib import Path as _Path
|
| 215 |
+
import json as _json
|
| 216 |
+
|
| 217 |
+
local = _Path(source)
|
| 218 |
+
if is_local_law_pack(local):
|
| 219 |
+
pack_meta: dict[str, Any] = {}
|
| 220 |
+
meta_path = local / "pack_meta.json"
|
| 221 |
+
if meta_path.is_file():
|
| 222 |
+
try:
|
| 223 |
+
pack_meta = _json.loads(meta_path.read_text(encoding="utf-8"))
|
| 224 |
+
except Exception:
|
| 225 |
+
pack_meta = {}
|
| 226 |
+
slug = str(pack_meta.get("slug") or local.name)
|
| 227 |
+
# strip common cache prefixes like oman_filtered_c72f142a
|
| 228 |
+
if slug.startswith("oman"):
|
| 229 |
+
slug = "oman"
|
| 230 |
+
for prefix in ("ipfs_",):
|
| 231 |
+
if slug.startswith(prefix):
|
| 232 |
+
slug = slug[len(prefix):]
|
| 233 |
+
for suffix in ("_laws", "_filtered", "-ir"):
|
| 234 |
+
if slug.endswith(suffix):
|
| 235 |
+
slug = slug[: -len(suffix)]
|
| 236 |
+
# e.g. oman_filtered_c72f142a -> oman
|
| 237 |
+
if "_filtered" in slug:
|
| 238 |
+
slug = slug.split("_filtered", 1)[0]
|
| 239 |
+
repo = str(pack_meta.get("repo") or pack_meta.get("source_dataset") or f"endomorphosis/ipfs_{slug}_laws")
|
| 240 |
+
return {
|
| 241 |
+
"slug": slug,
|
| 242 |
+
"repo": repo,
|
| 243 |
+
"name": str(pack_meta.get("name") or slug.replace("_", " ").title()),
|
| 244 |
+
"indexable": bool(pack_meta.get("indexable", slug not in EXCLUDED_SLUGS)),
|
| 245 |
+
"skip_reason": pack_meta.get("skip_reason"),
|
| 246 |
+
"local_source_dir": str(local.resolve()),
|
| 247 |
+
"source_revision": pack_meta.get("source_revision"),
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
slug = source
|
| 251 |
+
if "/" in source:
|
| 252 |
+
slug = source.rsplit("/", 1)[-1]
|
| 253 |
+
slug = slug.removeprefix("ipfs_").removesuffix("_laws").removesuffix("-ir")
|
| 254 |
+
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.coverage import (
|
| 255 |
+
canonical_slug,
|
| 256 |
+
)
|
| 257 |
+
|
| 258 |
+
slug = canonical_slug(slug)
|
| 259 |
+
for row in all_countries():
|
| 260 |
+
if row["slug"] == slug or row["repo"] == source or row["repo"].endswith("/" + source):
|
| 261 |
+
return dict(row)
|
| 262 |
+
if source.startswith("endomorphosis/ipfs_") and source.endswith("_laws"):
|
| 263 |
+
inferred = source.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 264 |
+
return {
|
| 265 |
+
"slug": inferred,
|
| 266 |
+
"repo": source,
|
| 267 |
+
"name": inferred.replace("_", " ").title(),
|
| 268 |
+
"indexable": inferred not in EXCLUDED_SLUGS,
|
| 269 |
+
"skip_reason": _SKIP_REASONS.get(inferred),
|
| 270 |
+
}
|
| 271 |
+
raise KeyError(f"Unknown country-law source: {source}")
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def indexable_countries() -> list[dict[str, Any]]:
|
| 275 |
+
return [c for c in all_countries() if c.get("indexable")]
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def target_repo(slug: str) -> str:
|
| 279 |
+
return f"justicedao/ipfs_{slug}_laws_ir"
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def refresh_from_hub(*, persist: bool = True) -> list[dict[str, Any]]:
|
| 283 |
+
"""Anonymous Hub listing of public endomorphosis/ipfs_*_laws datasets."""
|
| 284 |
+
from huggingface_hub import HfApi
|
| 285 |
+
|
| 286 |
+
from .auth import configure_hf, public_token
|
| 287 |
+
|
| 288 |
+
configure_hf()
|
| 289 |
+
api = HfApi(token=public_token())
|
| 290 |
+
found: list[dict[str, Any]] = []
|
| 291 |
+
for ds in api.list_datasets(author="endomorphosis"):
|
| 292 |
+
ds_id = ds.id
|
| 293 |
+
if not ds_id.startswith("endomorphosis/ipfs_") or not ds_id.endswith("_laws"):
|
| 294 |
+
continue
|
| 295 |
+
slug = ds_id.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 296 |
+
found.append({
|
| 297 |
+
"slug": slug,
|
| 298 |
+
"repo": ds_id,
|
| 299 |
+
"name": slug.replace("_", " ").title(),
|
| 300 |
+
"indexable": slug not in EXCLUDED_SLUGS,
|
| 301 |
+
"skip_reason": _SKIP_REASONS.get(slug),
|
| 302 |
+
})
|
| 303 |
+
found.sort(key=lambda r: r["slug"])
|
| 304 |
+
merged = merge_country_rows(COUNTRIES, found)
|
| 305 |
+
if persist:
|
| 306 |
+
persist_catalog(merged)
|
| 307 |
+
return merged
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/cidutil.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CIDv1 (raw + sha2-256) helpers. Produces bafkrei... identifiers.
|
| 2 |
+
|
| 3 |
+
Payload format (deterministic):
|
| 4 |
+
json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 5 |
+
|
| 6 |
+
Codec: CIDv1 version=0x01, multicodec raw=0x55, multihash sha2-256=0x12, length=0x20,
|
| 7 |
+
then 32-byte digest. Multibase prefix `b` + RFC 4648 base32 (lowercase, no padding).
|
| 8 |
+
Same payload bytes always yield the same CID.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
_B32 = "abcdefghijklmnopqrstuvwxyz234567"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def sha256_hex(data: bytes) -> str:
|
| 23 |
+
return hashlib.sha256(data).hexdigest()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def sha256_file(path: Path) -> str:
|
| 27 |
+
h = hashlib.sha256()
|
| 28 |
+
with path.open("rb") as f:
|
| 29 |
+
while True:
|
| 30 |
+
chunk = f.read(1024 * 1024)
|
| 31 |
+
if not chunk:
|
| 32 |
+
break
|
| 33 |
+
h.update(chunk)
|
| 34 |
+
return h.hexdigest()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def canonical_json_bytes(obj: Any) -> bytes:
|
| 38 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _b32encode(data: bytes) -> str:
|
| 42 |
+
bits = 0
|
| 43 |
+
value = 0
|
| 44 |
+
out = []
|
| 45 |
+
for byte in data:
|
| 46 |
+
value = (value << 8) | byte
|
| 47 |
+
bits += 8
|
| 48 |
+
while bits >= 5:
|
| 49 |
+
bits -= 5
|
| 50 |
+
out.append(_B32[(value >> bits) & 31])
|
| 51 |
+
if bits:
|
| 52 |
+
out.append(_B32[(value << (5 - bits)) & 31])
|
| 53 |
+
return "".join(out)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def cid_v1_raw_sha256(data: bytes) -> str:
|
| 57 |
+
digest = hashlib.sha256(data).digest()
|
| 58 |
+
cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest
|
| 59 |
+
return "b" + _b32encode(cid_bytes)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def sha256_key_to_cidv1(value: str) -> str:
|
| 63 |
+
"""Turn a bare/prefixed SHA-256 routing key into ``bafkrei…`` CIDv1.
|
| 64 |
+
|
| 65 |
+
GraphRAG locators must not use hex digests as ``entry_cid`` / ``node_cid``.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
text = str(value or "").strip()
|
| 69 |
+
if text.startswith("bafkrei"):
|
| 70 |
+
return text
|
| 71 |
+
hex_part = text[7:71] if text.lower().startswith("sha256:") else text[:64]
|
| 72 |
+
rest = text[71:] if text.lower().startswith("sha256:") else text[64:]
|
| 73 |
+
if len(hex_part) != 64:
|
| 74 |
+
return text
|
| 75 |
+
try:
|
| 76 |
+
digest = bytes.fromhex(hex_part)
|
| 77 |
+
except ValueError:
|
| 78 |
+
return text
|
| 79 |
+
cid_bytes = bytes([0x01, 0x55, 0x12, 0x20]) + digest
|
| 80 |
+
return "b" + _b32encode(cid_bytes) + rest
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def cid_of_json(obj: Any) -> str:
|
| 84 |
+
return cid_v1_raw_sha256(canonical_json_bytes(obj))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def cid_of_text(*parts: str) -> str:
|
| 88 |
+
blob = "\n".join("" if p is None else str(p) for p in parts).encode("utf-8")
|
| 89 |
+
return cid_v1_raw_sha256(blob)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def file_descriptor(path: Path, relative_path: str, extra: dict | None = None) -> dict:
|
| 93 |
+
data = path.read_bytes()
|
| 94 |
+
desc = {
|
| 95 |
+
"cid": cid_v1_raw_sha256(data),
|
| 96 |
+
"sha256": sha256_hex(data),
|
| 97 |
+
"size_bytes": len(data),
|
| 98 |
+
"relative_path": relative_path,
|
| 99 |
+
}
|
| 100 |
+
if extra:
|
| 101 |
+
desc.update(extra)
|
| 102 |
+
return desc
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/citations.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official and Bluebook citations for country-law corpus rows.
|
| 2 |
+
|
| 3 |
+
Bluebook T2/T10 abbreviations are used only when this table has a row.
|
| 4 |
+
Unknown jurisdictions get ``official_citation`` only — never a invented
|
| 5 |
+
Bluebook form. Query keys are normalized so ``ORS 1.010`` and
|
| 6 |
+
``Or. Rev. Stat. § 1.010`` can hit the same row later.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
import re
|
| 13 |
+
import unicodedata
|
| 14 |
+
from typing import Any
|
| 15 |
+
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
import json as _json
|
| 18 |
+
|
| 19 |
+
_TABLE_PATH = Path(__file__).resolve().parent / "data" / "bluebook_t2.json"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _load_t2() -> dict[str, dict[str, Any]]:
|
| 23 |
+
if not _TABLE_PATH.is_file():
|
| 24 |
+
return {}
|
| 25 |
+
payload = _json.loads(_TABLE_PATH.read_text(encoding="utf-8"))
|
| 26 |
+
return payload if isinstance(payload, dict) else {}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
_BLUEBOOK_T2 = _load_t2()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@dataclass(frozen=True)
|
| 33 |
+
class Citation:
|
| 34 |
+
official_citation: str
|
| 35 |
+
bluebook_citation: str
|
| 36 |
+
cite_key: str
|
| 37 |
+
citation_status: str # bluebook | official_only | unknown
|
| 38 |
+
pinpoint: str
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def normalize_cite_key(value: str) -> str:
|
| 42 |
+
if not value:
|
| 43 |
+
return ""
|
| 44 |
+
text = unicodedata.normalize("NFKC", value).lower()
|
| 45 |
+
text = text.replace("§", " s ")
|
| 46 |
+
text = text.replace("¶", " ")
|
| 47 |
+
text = re.sub(r"\bart(?:icle|\.)?\b", "art", text)
|
| 48 |
+
text = re.sub(r"\bsec(?:tion|\.)?\b", "s", text)
|
| 49 |
+
text = re.sub(r"[^a-z0-9]+", " ", text)
|
| 50 |
+
return re.sub(r"\s+", " ", text).strip()
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _pinpoint(article_number: str, section_number: str, record_type: str) -> str:
|
| 54 |
+
if record_type == "section" and section_number:
|
| 55 |
+
return f"§ {section_number}"
|
| 56 |
+
if article_number:
|
| 57 |
+
return f"art. {article_number}"
|
| 58 |
+
if section_number:
|
| 59 |
+
return f"§ {section_number}"
|
| 60 |
+
return ""
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _t2_row(jurisdiction: str, country: str, slug: str = "") -> dict[str, Any]:
|
| 64 |
+
for key in (slug, country, jurisdiction):
|
| 65 |
+
hit = _BLUEBOOK_T2.get(str(key or "").strip().lower().replace("_", " "))
|
| 66 |
+
if isinstance(hit, dict):
|
| 67 |
+
return hit
|
| 68 |
+
return {}
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def assign_citation(
|
| 72 |
+
*,
|
| 73 |
+
eli: str = "",
|
| 74 |
+
official_identifier: str = "",
|
| 75 |
+
identifier: str = "",
|
| 76 |
+
instrument_title: str = "",
|
| 77 |
+
article_number: str = "",
|
| 78 |
+
section_number: str = "",
|
| 79 |
+
record_type: str = "law",
|
| 80 |
+
jurisdiction: str = "",
|
| 81 |
+
country: str = "",
|
| 82 |
+
slug: str = "",
|
| 83 |
+
year: str = "",
|
| 84 |
+
) -> Citation:
|
| 85 |
+
pinpoint = _pinpoint(article_number, section_number, record_type)
|
| 86 |
+
official = (
|
| 87 |
+
(eli or "").strip()
|
| 88 |
+
or (official_identifier or "").strip()
|
| 89 |
+
or (identifier or "").strip()
|
| 90 |
+
or (instrument_title or "").strip()
|
| 91 |
+
)
|
| 92 |
+
if official and pinpoint and pinpoint.lower() not in official.lower():
|
| 93 |
+
official_cite = f"{official}, {pinpoint}"
|
| 94 |
+
else:
|
| 95 |
+
official_cite = official
|
| 96 |
+
|
| 97 |
+
t2 = _t2_row(jurisdiction, country, slug)
|
| 98 |
+
abbrev = str(t2.get("abbrev") or "")
|
| 99 |
+
emit = str(t2.get("emit") or "official_only")
|
| 100 |
+
required = list(t2.get("required") or [])
|
| 101 |
+
have = {
|
| 102 |
+
"year": bool(year),
|
| 103 |
+
"section": bool(section_number or (record_type == "section" and article_number)),
|
| 104 |
+
"article": bool(article_number),
|
| 105 |
+
"title": bool(instrument_title),
|
| 106 |
+
}
|
| 107 |
+
missing = [k for k in required if not have.get(k)]
|
| 108 |
+
bluebook = ""
|
| 109 |
+
if emit == "bluebook" and abbrev and not missing:
|
| 110 |
+
if pinpoint:
|
| 111 |
+
bluebook = f"{abbrev} {pinpoint}" + (f" ({year})" if year else "")
|
| 112 |
+
elif have.get("section"):
|
| 113 |
+
bluebook = f"{abbrev} § {section_number}" + (f" ({year})" if year else "")
|
| 114 |
+
|
| 115 |
+
if bluebook:
|
| 116 |
+
status = "bluebook"
|
| 117 |
+
elif official_cite:
|
| 118 |
+
status = "official_only"
|
| 119 |
+
else:
|
| 120 |
+
status = "unknown"
|
| 121 |
+
|
| 122 |
+
key_src = bluebook or official_cite
|
| 123 |
+
return Citation(
|
| 124 |
+
official_citation=official_cite,
|
| 125 |
+
bluebook_citation=bluebook,
|
| 126 |
+
cite_key=normalize_cite_key(key_src),
|
| 127 |
+
citation_status=status,
|
| 128 |
+
pinpoint=pinpoint,
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def citation_fields(cite: Citation) -> dict[str, Any]:
|
| 133 |
+
return {
|
| 134 |
+
"official_citation": cite.official_citation,
|
| 135 |
+
"bluebook_citation": cite.bluebook_citation,
|
| 136 |
+
"cite_key": cite.cite_key,
|
| 137 |
+
"citation_status": cite.citation_status,
|
| 138 |
+
"pinpoint": cite.pinpoint,
|
| 139 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/coverage.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compare endomorphosis raw sources against justicedao GraphRAG releases.
|
| 2 |
+
|
| 3 |
+
Gap kinds
|
| 4 |
+
---------
|
| 5 |
+
* missing — no JusticeDAO IR (and no local pack)
|
| 6 |
+
* unpublished — local IR exists, Hub IR does not
|
| 7 |
+
* stale — Hub/local IR source revision does not match current endomorphosis SHA
|
| 8 |
+
* incomplete — missing corpus/BM25/graph, empty corpus, or source has no laws
|
| 9 |
+
* stub_vectors — IR is otherwise current but embeddings were stubbed
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any, Mapping
|
| 19 |
+
|
| 20 |
+
from .catalog import EXCLUDED_SLUGS, all_countries, static_crosswalk_coverage, target_repo
|
| 21 |
+
|
| 22 |
+
ALIAS_TO_CANONICAL = {
|
| 23 |
+
"dominican_republic": "dominicanrepublic",
|
| 24 |
+
"el_salvador": "elsalvador",
|
| 25 |
+
"north_korea": "northkorea",
|
| 26 |
+
"papua_new_guinea": "papuanewguinea",
|
| 27 |
+
"san_marino": "sanmarino",
|
| 28 |
+
"trinidad_and_tobago": "trinidad",
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _slug_from_source(dataset_id: str) -> str | None:
|
| 33 |
+
if not dataset_id.startswith("endomorphosis/ipfs_") or not dataset_id.endswith("_laws"):
|
| 34 |
+
return None
|
| 35 |
+
return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _slug_from_ir(dataset_id: str) -> str | None:
|
| 39 |
+
if not dataset_id.startswith("justicedao/ipfs_") or not dataset_id.endswith("_laws_ir"):
|
| 40 |
+
return None
|
| 41 |
+
return dataset_id.split("ipfs_", 1)[1].removesuffix("_laws_ir")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def canonical_slug(slug: str) -> str:
|
| 45 |
+
return ALIAS_TO_CANONICAL.get(slug, slug)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def list_hub_slugs(*, author: str, kind: str) -> list[str]:
|
| 49 |
+
from huggingface_hub import HfApi
|
| 50 |
+
|
| 51 |
+
from .auth import configure_hf, operator_token, public_token
|
| 52 |
+
|
| 53 |
+
configure_hf()
|
| 54 |
+
token = operator_token() or public_token()
|
| 55 |
+
api = HfApi(token=token)
|
| 56 |
+
out: list[str] = []
|
| 57 |
+
for ds in api.list_datasets(author=author):
|
| 58 |
+
slug = _slug_from_source(ds.id) if kind == "source" else _slug_from_ir(ds.id)
|
| 59 |
+
if slug:
|
| 60 |
+
out.append(slug)
|
| 61 |
+
return sorted(set(out))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def local_release_slugs(releases_dir: Path) -> list[str]:
|
| 65 |
+
if not releases_dir.is_dir():
|
| 66 |
+
return []
|
| 67 |
+
found: list[str] = []
|
| 68 |
+
for path in sorted(releases_dir.glob("ipfs_*_laws_ir")):
|
| 69 |
+
if (path / "manifest.json").is_file():
|
| 70 |
+
slug = path.name.removeprefix("ipfs_").removesuffix("_laws_ir")
|
| 71 |
+
found.append(slug)
|
| 72 |
+
return found
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
IR_FAMILY_PREFIXES = (
|
| 76 |
+
("data/corpus/", "ir_missing_corpus"),
|
| 77 |
+
("data/bm25/", "ir_missing_bm25"),
|
| 78 |
+
("data/graph/", "ir_missing_graph"),
|
| 79 |
+
)
|
| 80 |
+
STUB_VECTOR_STATUSES = {"stub", "stub_missing_encoder", "incomplete"}
|
| 81 |
+
TINY_LAWS_BYTES = 1024
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def classify_gap(
|
| 85 |
+
*,
|
| 86 |
+
excluded: bool = False,
|
| 87 |
+
alias: bool = False,
|
| 88 |
+
source_has_laws: bool = True,
|
| 89 |
+
source_laws_bytes: int | None = None,
|
| 90 |
+
source_revision: str | None = None,
|
| 91 |
+
ir_files: list[str] | None = None,
|
| 92 |
+
ir_source_revision: str | None = None,
|
| 93 |
+
ir_corpus_rows: int | None = None,
|
| 94 |
+
vector_status: str | None = None,
|
| 95 |
+
local_only: bool = False,
|
| 96 |
+
local_source_revision: str | None = None,
|
| 97 |
+
) -> dict[str, Any]:
|
| 98 |
+
"""Pure classifier for missing / stale / incomplete country IR."""
|
| 99 |
+
issues: list[str] = []
|
| 100 |
+
if alias:
|
| 101 |
+
return {"status": "alias", "issues": issues, "rebuild": False, "publish": False}
|
| 102 |
+
if excluded:
|
| 103 |
+
return {"status": "excluded", "issues": issues, "rebuild": False, "publish": False}
|
| 104 |
+
|
| 105 |
+
if not source_has_laws:
|
| 106 |
+
issues.append("source_missing_laws")
|
| 107 |
+
if (
|
| 108 |
+
source_laws_bytes is not None
|
| 109 |
+
and source_laws_bytes >= 0
|
| 110 |
+
and source_laws_bytes < TINY_LAWS_BYTES
|
| 111 |
+
):
|
| 112 |
+
issues.append("source_laws_tiny")
|
| 113 |
+
|
| 114 |
+
if ir_files is None:
|
| 115 |
+
issues.append("missing_ir")
|
| 116 |
+
else:
|
| 117 |
+
names = set(ir_files)
|
| 118 |
+
if "manifest.json" not in names:
|
| 119 |
+
issues.append("ir_missing_manifest")
|
| 120 |
+
for prefix, issue in IR_FAMILY_PREFIXES:
|
| 121 |
+
if not any(name.startswith(prefix) for name in names):
|
| 122 |
+
issues.append(issue)
|
| 123 |
+
if ir_corpus_rows is not None and int(ir_corpus_rows) <= 0:
|
| 124 |
+
issues.append("ir_empty_corpus")
|
| 125 |
+
if (
|
| 126 |
+
source_revision
|
| 127 |
+
and ir_source_revision
|
| 128 |
+
and str(source_revision) != str(ir_source_revision)
|
| 129 |
+
):
|
| 130 |
+
issues.append("stale_source_revision")
|
| 131 |
+
if vector_status in STUB_VECTOR_STATUSES:
|
| 132 |
+
issues.append("ir_stub_vectors")
|
| 133 |
+
|
| 134 |
+
structural = {
|
| 135 |
+
"source_missing_laws",
|
| 136 |
+
"source_laws_tiny",
|
| 137 |
+
"ir_missing_manifest",
|
| 138 |
+
"ir_missing_corpus",
|
| 139 |
+
"ir_missing_bm25",
|
| 140 |
+
"ir_missing_graph",
|
| 141 |
+
"ir_empty_corpus",
|
| 142 |
+
}
|
| 143 |
+
issue_set = set(issues)
|
| 144 |
+
if "missing_ir" in issue_set:
|
| 145 |
+
status = "unpublished" if local_only else "missing"
|
| 146 |
+
elif "stale_source_revision" in issue_set:
|
| 147 |
+
status = "stale"
|
| 148 |
+
elif issue_set & structural:
|
| 149 |
+
status = "incomplete"
|
| 150 |
+
elif issue_set == {"ir_stub_vectors"}:
|
| 151 |
+
status = "stub_vectors"
|
| 152 |
+
elif not issues:
|
| 153 |
+
status = "current"
|
| 154 |
+
else:
|
| 155 |
+
status = "incomplete"
|
| 156 |
+
|
| 157 |
+
local_current = bool(
|
| 158 |
+
source_revision
|
| 159 |
+
and local_source_revision
|
| 160 |
+
and str(source_revision) == str(local_source_revision)
|
| 161 |
+
)
|
| 162 |
+
rebuild = (
|
| 163 |
+
status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"}
|
| 164 |
+
and (not local_current or status == "stub_vectors")
|
| 165 |
+
)
|
| 166 |
+
publish = status in {"missing", "unpublished", "stale", "incomplete", "stub_vectors"} and (
|
| 167 |
+
"source_missing_laws" not in issues
|
| 168 |
+
)
|
| 169 |
+
return {
|
| 170 |
+
"status": status,
|
| 171 |
+
"issues": issues,
|
| 172 |
+
"rebuild": rebuild,
|
| 173 |
+
"publish": publish,
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _ir_source_revision(manifest: Mapping[str, Any] | None) -> str | None:
|
| 178 |
+
if not manifest:
|
| 179 |
+
return None
|
| 180 |
+
pinned = manifest.get("dataset_revision") or (manifest.get("source") or {}).get(
|
| 181 |
+
"source_revision"
|
| 182 |
+
)
|
| 183 |
+
text = str(pinned or "").strip()
|
| 184 |
+
return text or None
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def _vector_status(manifest: Mapping[str, Any] | None) -> str | None:
|
| 188 |
+
if not manifest:
|
| 189 |
+
return None
|
| 190 |
+
vector = manifest.get("vector") or {}
|
| 191 |
+
if isinstance(vector, dict) and vector.get("status"):
|
| 192 |
+
return str(vector.get("status"))
|
| 193 |
+
incremental = manifest.get("incremental") or {}
|
| 194 |
+
nested = incremental.get("vectors") if isinstance(incremental, dict) else None
|
| 195 |
+
if isinstance(nested, dict) and nested.get("status"):
|
| 196 |
+
return str(nested.get("status"))
|
| 197 |
+
if isinstance(vector, dict) and vector.get("stub"):
|
| 198 |
+
return "stub"
|
| 199 |
+
return None
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
def load_local_manifest(release_dir: Path) -> dict[str, Any]:
|
| 203 |
+
path = Path(release_dir) / "manifest.json"
|
| 204 |
+
if not path.is_file():
|
| 205 |
+
return {}
|
| 206 |
+
try:
|
| 207 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 208 |
+
except Exception:
|
| 209 |
+
return {}
|
| 210 |
+
return data if isinstance(data, dict) else {}
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _sibling_map(info: Any) -> dict[str, int | None]:
|
| 214 |
+
out: dict[str, int | None] = {}
|
| 215 |
+
for sib in getattr(info, "siblings", None) or []:
|
| 216 |
+
name = str(getattr(sib, "rfilename", "") or "")
|
| 217 |
+
if not name:
|
| 218 |
+
continue
|
| 219 |
+
size = getattr(sib, "size", None)
|
| 220 |
+
try:
|
| 221 |
+
out[name] = int(size) if size is not None else None # type: ignore[assignment]
|
| 222 |
+
except (TypeError, ValueError):
|
| 223 |
+
out[name] = None # type: ignore[assignment]
|
| 224 |
+
return out
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _inspect_source(slug: str, cache_dir: Path | None = None) -> dict[str, Any]:
|
| 228 |
+
from huggingface_hub import dataset_info
|
| 229 |
+
|
| 230 |
+
from .auth import configure_hf, operator_token, public_token
|
| 231 |
+
|
| 232 |
+
repo = f"endomorphosis/ipfs_{slug}_laws"
|
| 233 |
+
configure_hf()
|
| 234 |
+
info = dataset_info(repo, token=operator_token() or public_token())
|
| 235 |
+
files = _sibling_map(info)
|
| 236 |
+
laws_file = next(
|
| 237 |
+
(name for name in ("data/laws.parquet", "laws.parquet") if name in files),
|
| 238 |
+
None,
|
| 239 |
+
)
|
| 240 |
+
arts_file = next(
|
| 241 |
+
(name for name in ("data/articles.parquet", "articles.parquet") if name in files),
|
| 242 |
+
None,
|
| 243 |
+
)
|
| 244 |
+
return {
|
| 245 |
+
"repo": repo,
|
| 246 |
+
"revision": getattr(info, "sha", None),
|
| 247 |
+
"files": sorted(files),
|
| 248 |
+
"has_laws": laws_file is not None,
|
| 249 |
+
"has_articles": arts_file is not None,
|
| 250 |
+
"laws_bytes": files.get(laws_file) if laws_file else None,
|
| 251 |
+
"articles_bytes": files.get(arts_file) if arts_file else None,
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def _inspect_ir(slug: str, cache_dir: Path) -> dict[str, Any] | None:
|
| 256 |
+
from huggingface_hub import HfApi, dataset_info, hf_hub_download
|
| 257 |
+
from huggingface_hub.errors import EntryNotFoundError, RepositoryNotFoundError
|
| 258 |
+
|
| 259 |
+
from .auth import configure_hf, operator_token, public_token
|
| 260 |
+
|
| 261 |
+
repo = target_repo(slug)
|
| 262 |
+
configure_hf()
|
| 263 |
+
token = operator_token() or public_token()
|
| 264 |
+
try:
|
| 265 |
+
info = dataset_info(repo, token=token)
|
| 266 |
+
except RepositoryNotFoundError:
|
| 267 |
+
return None
|
| 268 |
+
files = _sibling_map(info)
|
| 269 |
+
if len(files) < 8:
|
| 270 |
+
try:
|
| 271 |
+
listed = HfApi(token=token).list_repo_files(repo_id=repo, repo_type="dataset")
|
| 272 |
+
for name in listed:
|
| 273 |
+
files.setdefault(str(name), None)
|
| 274 |
+
except Exception:
|
| 275 |
+
pass
|
| 276 |
+
manifest: dict[str, Any] = {}
|
| 277 |
+
if "manifest.json" in files:
|
| 278 |
+
try:
|
| 279 |
+
path = hf_hub_download(
|
| 280 |
+
repo_id=repo,
|
| 281 |
+
filename="manifest.json",
|
| 282 |
+
repo_type="dataset",
|
| 283 |
+
token=token,
|
| 284 |
+
cache_dir=str(cache_dir / "hf"),
|
| 285 |
+
)
|
| 286 |
+
payload = json.loads(Path(path).read_text(encoding="utf-8"))
|
| 287 |
+
if isinstance(payload, dict):
|
| 288 |
+
manifest = payload
|
| 289 |
+
except (EntryNotFoundError, OSError, json.JSONDecodeError):
|
| 290 |
+
manifest = {}
|
| 291 |
+
counts = manifest.get("counts") if isinstance(manifest.get("counts"), dict) else {}
|
| 292 |
+
return {
|
| 293 |
+
"repo": repo,
|
| 294 |
+
"hub_revision": getattr(info, "sha", None),
|
| 295 |
+
"files": sorted(files),
|
| 296 |
+
"manifest": manifest,
|
| 297 |
+
"source_revision": _ir_source_revision(manifest),
|
| 298 |
+
"corpus_rows": counts.get("corpus_rows"),
|
| 299 |
+
"vector_status": _vector_status(manifest),
|
| 300 |
+
}
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def gap_report(
|
| 304 |
+
releases_dir: Path | None = None,
|
| 305 |
+
*,
|
| 306 |
+
slugs: list[str] | None = None,
|
| 307 |
+
workers: int = 8,
|
| 308 |
+
) -> dict[str, Any]:
|
| 309 |
+
"""Live Hub scan: missing, stale, incomplete, and unpublished country IR."""
|
| 310 |
+
from .build import CACHE, RELEASES
|
| 311 |
+
|
| 312 |
+
# Each spelling is its own scrape and its own justicedao index.
|
| 313 |
+
# Dropping alias keys hid el_salvador and papua_new_guinea when those
|
| 314 |
+
# repos moved and the unpunctuated twin did not.
|
| 315 |
+
sources = slugs or list_hub_slugs(author="endomorphosis", kind="source")
|
| 316 |
+
hub_ir = set(list_hub_slugs(author="justicedao", kind="ir"))
|
| 317 |
+
local_dir = Path(releases_dir) if releases_dir else RELEASES
|
| 318 |
+
local_ir = set(local_release_slugs(local_dir))
|
| 319 |
+
cache_dir = CACHE
|
| 320 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 321 |
+
|
| 322 |
+
rows: list[dict[str, Any]] = []
|
| 323 |
+
|
| 324 |
+
def _one(slug: str) -> dict[str, Any]:
|
| 325 |
+
last_exc: Exception | None = None
|
| 326 |
+
for attempt in range(4):
|
| 327 |
+
try:
|
| 328 |
+
source = _inspect_source(slug)
|
| 329 |
+
ir = _inspect_ir(slug, cache_dir) if slug in hub_ir else None
|
| 330 |
+
break
|
| 331 |
+
except Exception as exc:
|
| 332 |
+
last_exc = exc
|
| 333 |
+
name = type(exc).__name__
|
| 334 |
+
msg = str(exc)
|
| 335 |
+
if "429" in msg or "rate limit" in msg.lower():
|
| 336 |
+
time.sleep(min(45, 3 ** attempt * 2))
|
| 337 |
+
continue
|
| 338 |
+
raise
|
| 339 |
+
else:
|
| 340 |
+
raise last_exc or RuntimeError(f"scan failed for {slug}")
|
| 341 |
+
local_manifest = load_local_manifest(local_dir / f"ipfs_{slug}_laws_ir")
|
| 342 |
+
local_rev = _ir_source_revision(local_manifest) if local_manifest else None
|
| 343 |
+
classified = classify_gap(
|
| 344 |
+
excluded=slug in EXCLUDED_SLUGS,
|
| 345 |
+
alias=False,
|
| 346 |
+
source_has_laws=bool(source.get("has_laws")),
|
| 347 |
+
source_laws_bytes=source.get("laws_bytes"),
|
| 348 |
+
source_revision=source.get("revision"),
|
| 349 |
+
ir_files=None if ir is None else ir.get("files"),
|
| 350 |
+
ir_source_revision=(ir or {}).get("source_revision") or local_rev,
|
| 351 |
+
ir_corpus_rows=(ir or {}).get("corpus_rows")
|
| 352 |
+
if ir is not None
|
| 353 |
+
else (local_manifest.get("counts") or {}).get("corpus_rows")
|
| 354 |
+
if local_manifest
|
| 355 |
+
else None,
|
| 356 |
+
vector_status=(ir or {}).get("vector_status")
|
| 357 |
+
or _vector_status(local_manifest),
|
| 358 |
+
local_only=slug in local_ir and slug not in hub_ir,
|
| 359 |
+
local_source_revision=local_rev,
|
| 360 |
+
)
|
| 361 |
+
return {
|
| 362 |
+
"slug": slug,
|
| 363 |
+
"source": source.get("repo"),
|
| 364 |
+
"target": target_repo(slug),
|
| 365 |
+
"source_revision": source.get("revision"),
|
| 366 |
+
"ir_source_revision": (ir or {}).get("source_revision"),
|
| 367 |
+
"local_source_revision": local_rev,
|
| 368 |
+
"has_hub_ir": ir is not None,
|
| 369 |
+
"has_local_ir": slug in local_ir,
|
| 370 |
+
"source_has_articles": source.get("has_articles"),
|
| 371 |
+
"source_laws_bytes": source.get("laws_bytes"),
|
| 372 |
+
"corpus_rows": (ir or {}).get("corpus_rows")
|
| 373 |
+
if ir is not None
|
| 374 |
+
else (local_manifest.get("counts") or {}).get("corpus_rows")
|
| 375 |
+
if local_manifest
|
| 376 |
+
else None,
|
| 377 |
+
"vector_status": (ir or {}).get("vector_status")
|
| 378 |
+
or _vector_status(local_manifest),
|
| 379 |
+
**classified,
|
| 380 |
+
}
|
| 381 |
+
|
| 382 |
+
workers = max(1, min(int(workers), 16))
|
| 383 |
+
with ThreadPoolExecutor(max_workers=workers) as pool:
|
| 384 |
+
futs = {pool.submit(_one, slug): slug for slug in sources}
|
| 385 |
+
for fut in as_completed(futs):
|
| 386 |
+
slug = futs[fut]
|
| 387 |
+
try:
|
| 388 |
+
rows.append(fut.result())
|
| 389 |
+
except Exception as exc:
|
| 390 |
+
rows.append(
|
| 391 |
+
{
|
| 392 |
+
"slug": slug,
|
| 393 |
+
"source": f"endomorphosis/ipfs_{slug}_laws",
|
| 394 |
+
"target": target_repo(slug),
|
| 395 |
+
"status": "incomplete",
|
| 396 |
+
"issues": [f"scan_error:{type(exc).__name__}"],
|
| 397 |
+
"rebuild": False,
|
| 398 |
+
"publish": False,
|
| 399 |
+
"error": str(exc),
|
| 400 |
+
}
|
| 401 |
+
)
|
| 402 |
+
rows.sort(key=lambda r: str(r.get("slug")))
|
| 403 |
+
by_status: dict[str, list[str]] = {}
|
| 404 |
+
for row in rows:
|
| 405 |
+
by_status.setdefault(str(row.get("status")), []).append(str(row.get("slug")))
|
| 406 |
+
return {
|
| 407 |
+
"n": len(rows),
|
| 408 |
+
"by_status": {k: sorted(v) for k, v in sorted(by_status.items())},
|
| 409 |
+
"counts": {k: len(v) for k, v in sorted(by_status.items())},
|
| 410 |
+
"rebuild": [r["slug"] for r in rows if r.get("rebuild")],
|
| 411 |
+
"publish": [r["slug"] for r in rows if r.get("publish")],
|
| 412 |
+
"countries": rows,
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
def coverage_report(releases_dir: Path | None = None) -> dict[str, Any]:
|
| 417 |
+
from .build import RELEASES
|
| 418 |
+
|
| 419 |
+
sources = list_hub_slugs(author="endomorphosis", kind="source")
|
| 420 |
+
hub_ir = list_hub_slugs(author="justicedao", kind="ir")
|
| 421 |
+
local_ir = local_release_slugs(Path(releases_dir) if releases_dir else RELEASES)
|
| 422 |
+
hub_ir_canon = {canonical_slug(s) for s in hub_ir}
|
| 423 |
+
local_ir_canon = {canonical_slug(s) for s in local_ir}
|
| 424 |
+
missing_hub: list[dict[str, Any]] = []
|
| 425 |
+
missing_local: list[dict[str, Any]] = []
|
| 426 |
+
excluded: list[str] = []
|
| 427 |
+
aliases: list[str] = []
|
| 428 |
+
for slug in sources:
|
| 429 |
+
if slug in ALIAS_TO_CANONICAL:
|
| 430 |
+
aliases.append(slug)
|
| 431 |
+
continue
|
| 432 |
+
if slug in EXCLUDED_SLUGS:
|
| 433 |
+
excluded.append(slug)
|
| 434 |
+
continue
|
| 435 |
+
row = {
|
| 436 |
+
"slug": slug,
|
| 437 |
+
"source": f"endomorphosis/ipfs_{slug}_laws",
|
| 438 |
+
"target": target_repo(slug),
|
| 439 |
+
}
|
| 440 |
+
if slug not in hub_ir_canon:
|
| 441 |
+
missing_hub.append(row)
|
| 442 |
+
if slug not in local_ir_canon and slug not in hub_ir_canon:
|
| 443 |
+
missing_local.append(row)
|
| 444 |
+
return {
|
| 445 |
+
"n_sources": len(sources),
|
| 446 |
+
"n_hub_ir": len(hub_ir),
|
| 447 |
+
"n_local_ir": len(local_ir),
|
| 448 |
+
"n_catalog": len(all_countries()),
|
| 449 |
+
"excluded": excluded,
|
| 450 |
+
"alias_sources": aliases,
|
| 451 |
+
"crosswalk": static_crosswalk_coverage(),
|
| 452 |
+
"missing_justicedao": missing_hub,
|
| 453 |
+
"missing_local_and_hub": missing_local,
|
| 454 |
+
"local_only": sorted(local_ir_canon - hub_ir_canon),
|
| 455 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/duckdb_store.py
ADDED
|
@@ -0,0 +1,475 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""DuckDB views over country-laws sparse GraphRAG parquet shards.
|
| 2 |
+
|
| 3 |
+
Published artifacts are ZSTD parquet (SkillCenter / publicus-ir family).
|
| 4 |
+
Query and large-corpus neighbor generation read those shards through DuckDB
|
| 5 |
+
instead of loading them into pandas or SQLite.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
K1 = 1.2
|
| 17 |
+
B = 0.75
|
| 18 |
+
TITLE_WEIGHT = 5.0
|
| 19 |
+
BODY_WEIGHT = 1.0
|
| 20 |
+
MAX_QUERY_TERMS = 64
|
| 21 |
+
|
| 22 |
+
VIEWS = (
|
| 23 |
+
("corpus", "data/corpus/*.parquet"),
|
| 24 |
+
("bm25_documents", "data/bm25/documents/*.parquet"),
|
| 25 |
+
("bm25_postings", "data/bm25/postings/*.parquet"),
|
| 26 |
+
("graph_nodes", "data/graph/nodes/*.parquet"),
|
| 27 |
+
("graph_edges", "data/graph/edges/*.parquet"),
|
| 28 |
+
# Shared hf_graphrag layout (US Code / state laws / FR).
|
| 29 |
+
("graph_in", "data/graph/adjacency/in/*.parquet"),
|
| 30 |
+
("graph_out", "data/graph/adjacency/out/*.parquet"),
|
| 31 |
+
# Legacy country-laws-ir layout still on some Hub packs.
|
| 32 |
+
("graph_incoming", "data/graph/adjacency/incoming/*.parquet"),
|
| 33 |
+
("graph_outgoing", "data/graph/adjacency/outgoing/*.parquet"),
|
| 34 |
+
("vectors", "data/vectors/*.parquet"),
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class DuckDBStoreError(RuntimeError):
|
| 39 |
+
"""Raised when a parquet/DuckDB sparse index cannot be opened."""
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _require_duckdb():
|
| 43 |
+
try:
|
| 44 |
+
import duckdb # type: ignore
|
| 45 |
+
except ImportError as exc:
|
| 46 |
+
raise DuckDBStoreError("duckdb is required for parquet sparse GraphRAG query") from exc
|
| 47 |
+
return duckdb
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def parquet_glob(root: Path, pattern: str) -> str:
|
| 51 |
+
return str(Path(root) / pattern)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def connect_release(root: Path, *, database: str = ":memory:"):
|
| 55 |
+
"""Open a DuckDB connection with views over parquet shards."""
|
| 56 |
+
duckdb = _require_duckdb()
|
| 57 |
+
root = Path(root)
|
| 58 |
+
if not (root / "manifest.json").is_file():
|
| 59 |
+
raise DuckDBStoreError(f"release missing manifest.json: {root}")
|
| 60 |
+
con = duckdb.connect(database)
|
| 61 |
+
for name, pattern in VIEWS:
|
| 62 |
+
glob = parquet_glob(root, pattern)
|
| 63 |
+
if list(root.glob(pattern)):
|
| 64 |
+
escaped = glob.replace("'", "''")
|
| 65 |
+
con.execute(
|
| 66 |
+
f"CREATE OR REPLACE VIEW {name} AS SELECT * FROM read_parquet('{escaped}')"
|
| 67 |
+
)
|
| 68 |
+
return con
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load_manifest(root: Path) -> dict[str, Any]:
|
| 72 |
+
return json.loads((Path(root) / "manifest.json").read_text(encoding="utf-8"))
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def tokenize(text: str) -> list[str]:
|
| 76 |
+
import re
|
| 77 |
+
import unicodedata
|
| 78 |
+
|
| 79 |
+
if not text:
|
| 80 |
+
return []
|
| 81 |
+
nfkd = unicodedata.normalize("NFKD", text)
|
| 82 |
+
folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
|
| 83 |
+
return re.findall(r"[0-9A-Za-z]+", folded)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def bm25_search(root: Path, query: str, top_k: int = 10) -> list[dict[str, Any]]:
|
| 87 |
+
"""Okapi BM25 over parquet posting shards via DuckDB UNNEST."""
|
| 88 |
+
terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 89 |
+
if not terms:
|
| 90 |
+
return []
|
| 91 |
+
manifest = load_manifest(root)
|
| 92 |
+
avgdl = float((manifest.get("bm25") or {}).get("average_document_length") or 1.0) or 1.0
|
| 93 |
+
con = connect_release(root)
|
| 94 |
+
try:
|
| 95 |
+
tables = {
|
| 96 |
+
r[0]
|
| 97 |
+
for r in con.execute(
|
| 98 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
|
| 99 |
+
).fetchall()
|
| 100 |
+
}
|
| 101 |
+
if "bm25_postings" not in tables or "bm25_documents" not in tables:
|
| 102 |
+
raise DuckDBStoreError("release is missing BM25 parquet shards")
|
| 103 |
+
placeholders = ", ".join(["?"] * len(terms))
|
| 104 |
+
sql = f"""
|
| 105 |
+
WITH exploded AS (
|
| 106 |
+
SELECT
|
| 107 |
+
unnest(document_indices) AS document_index,
|
| 108 |
+
unnest(title_frequencies) AS title_tf,
|
| 109 |
+
unnest(body_frequencies) AS body_tf,
|
| 110 |
+
unnest(document_lengths) AS dl,
|
| 111 |
+
idf
|
| 112 |
+
FROM bm25_postings
|
| 113 |
+
WHERE term IN ({placeholders})
|
| 114 |
+
),
|
| 115 |
+
scored AS (
|
| 116 |
+
SELECT
|
| 117 |
+
document_index,
|
| 118 |
+
SUM(
|
| 119 |
+
idf * (
|
| 120 |
+
( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf )
|
| 121 |
+
* ({K1} + 1.0)
|
| 122 |
+
) / (
|
| 123 |
+
( {TITLE_WEIGHT} * title_tf + {BODY_WEIGHT} * body_tf )
|
| 124 |
+
+ {K1} * (1.0 - {B} + {B} * (dl / {avgdl}))
|
| 125 |
+
)
|
| 126 |
+
) AS score
|
| 127 |
+
FROM exploded
|
| 128 |
+
GROUP BY document_index
|
| 129 |
+
)
|
| 130 |
+
SELECT
|
| 131 |
+
s.document_index,
|
| 132 |
+
s.score,
|
| 133 |
+
d.entry_cid,
|
| 134 |
+
d.title,
|
| 135 |
+
d.record_type
|
| 136 |
+
FROM scored s
|
| 137 |
+
JOIN bm25_documents d USING (document_index)
|
| 138 |
+
ORDER BY s.score DESC, s.document_index
|
| 139 |
+
LIMIT ?
|
| 140 |
+
"""
|
| 141 |
+
rows = con.execute(sql, [*terms, int(top_k)]).fetchall()
|
| 142 |
+
cols = [
|
| 143 |
+
"document_index",
|
| 144 |
+
"score",
|
| 145 |
+
"entry_cid",
|
| 146 |
+
"title",
|
| 147 |
+
"record_type",
|
| 148 |
+
]
|
| 149 |
+
return [dict(zip(cols, row)) for row in rows]
|
| 150 |
+
finally:
|
| 151 |
+
con.close()
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def cite_search(
|
| 155 |
+
root: Path,
|
| 156 |
+
citation: str,
|
| 157 |
+
*,
|
| 158 |
+
cite_format: str = "any",
|
| 159 |
+
limit: int = 25,
|
| 160 |
+
) -> list[dict[str, Any]]:
|
| 161 |
+
"""Look up corpus rows by Bluebook, official cite, or normalized cite_key."""
|
| 162 |
+
from .citations import normalize_cite_key
|
| 163 |
+
|
| 164 |
+
needle = (citation or "").strip()
|
| 165 |
+
if not needle:
|
| 166 |
+
return []
|
| 167 |
+
key = normalize_cite_key(needle)
|
| 168 |
+
con = connect_release(root)
|
| 169 |
+
try:
|
| 170 |
+
tables = {
|
| 171 |
+
r[0]
|
| 172 |
+
for r in con.execute(
|
| 173 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
|
| 174 |
+
).fetchall()
|
| 175 |
+
}
|
| 176 |
+
if "corpus" not in tables:
|
| 177 |
+
raise DuckDBStoreError("release is missing corpus parquet shards")
|
| 178 |
+
cols = [
|
| 179 |
+
r[1]
|
| 180 |
+
for r in con.execute(
|
| 181 |
+
"SELECT table_schema, column_name FROM information_schema.columns "
|
| 182 |
+
"WHERE table_schema = 'main' AND table_name = 'corpus'"
|
| 183 |
+
).fetchall()
|
| 184 |
+
]
|
| 185 |
+
wanted = [
|
| 186 |
+
"entry_cid",
|
| 187 |
+
"record_type",
|
| 188 |
+
"title",
|
| 189 |
+
"instrument_title",
|
| 190 |
+
"article_number",
|
| 191 |
+
"official_citation",
|
| 192 |
+
"bluebook_citation",
|
| 193 |
+
"cite_key",
|
| 194 |
+
"citation_status",
|
| 195 |
+
"source_url",
|
| 196 |
+
]
|
| 197 |
+
select = ", ".join(c for c in wanted if c in cols) or "*"
|
| 198 |
+
clauses = []
|
| 199 |
+
params: list[Any] = []
|
| 200 |
+
fmt = (cite_format or "any").strip().lower()
|
| 201 |
+
if fmt in {"any", "bluebook"} and "bluebook_citation" in cols:
|
| 202 |
+
clauses.append("lower(coalesce(bluebook_citation, '')) = lower(?)")
|
| 203 |
+
params.append(needle)
|
| 204 |
+
if fmt in {"any", "official"} and "official_citation" in cols:
|
| 205 |
+
clauses.append("lower(coalesce(official_citation, '')) = lower(?)")
|
| 206 |
+
params.append(needle)
|
| 207 |
+
if "cite_key" in cols and key:
|
| 208 |
+
clauses.append("cite_key = ?")
|
| 209 |
+
params.append(key)
|
| 210 |
+
if not clauses:
|
| 211 |
+
return []
|
| 212 |
+
sql = f"SELECT {select} FROM corpus WHERE {' OR '.join(clauses)} LIMIT ?"
|
| 213 |
+
params.append(int(limit))
|
| 214 |
+
rows = con.execute(sql, params).fetchall()
|
| 215 |
+
names = [c for c in wanted if c in cols] if select != "*" else list(cols)
|
| 216 |
+
return [dict(zip(names, row)) for row in rows]
|
| 217 |
+
finally:
|
| 218 |
+
con.close()
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def graph_neighbors(
|
| 222 |
+
root: Path,
|
| 223 |
+
node_cid: str,
|
| 224 |
+
*,
|
| 225 |
+
direction: str = "both",
|
| 226 |
+
limit: int = 25,
|
| 227 |
+
) -> list[dict[str, Any]]:
|
| 228 |
+
"""Adjacency lookup over parquet shards via DuckDB."""
|
| 229 |
+
aliases = {
|
| 230 |
+
"both": ("in", "out", "incoming", "outgoing"),
|
| 231 |
+
"in": ("in", "incoming"),
|
| 232 |
+
"out": ("out", "outgoing"),
|
| 233 |
+
"incoming": ("in", "incoming"),
|
| 234 |
+
"outgoing": ("out", "outgoing"),
|
| 235 |
+
}
|
| 236 |
+
dirs = aliases.get(direction, (direction,))
|
| 237 |
+
con = connect_release(root)
|
| 238 |
+
try:
|
| 239 |
+
tables = {
|
| 240 |
+
r[0]
|
| 241 |
+
for r in con.execute(
|
| 242 |
+
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'main'"
|
| 243 |
+
).fetchall()
|
| 244 |
+
}
|
| 245 |
+
hits: list[dict[str, Any]] = []
|
| 246 |
+
for d in dirs:
|
| 247 |
+
view = {
|
| 248 |
+
"in": "graph_in",
|
| 249 |
+
"out": "graph_out",
|
| 250 |
+
"incoming": "graph_incoming",
|
| 251 |
+
"outgoing": "graph_outgoing",
|
| 252 |
+
}.get(d, d)
|
| 253 |
+
if view not in tables:
|
| 254 |
+
continue
|
| 255 |
+
rows = con.execute(
|
| 256 |
+
f"""
|
| 257 |
+
SELECT node_cid, neighbor_cids, edge_types, scores
|
| 258 |
+
FROM {view}
|
| 259 |
+
WHERE node_cid = ?
|
| 260 |
+
""",
|
| 261 |
+
[node_cid],
|
| 262 |
+
).fetchall()
|
| 263 |
+
for node, neighs, types, scores in rows:
|
| 264 |
+
neighs = list(neighs or [])
|
| 265 |
+
types = list(types or [])
|
| 266 |
+
scores = list(scores or [])
|
| 267 |
+
for i, neigh in enumerate(neighs):
|
| 268 |
+
hits.append(
|
| 269 |
+
{
|
| 270 |
+
"direction": d,
|
| 271 |
+
"node_cid": node,
|
| 272 |
+
"neighbor_cid": neigh,
|
| 273 |
+
"edge_type": types[i] if i < len(types) else "",
|
| 274 |
+
"score": scores[i] if i < len(scores) else None,
|
| 275 |
+
}
|
| 276 |
+
)
|
| 277 |
+
hits.sort(key=lambda r: (-(r["score"] or 0), str(r["neighbor_cid"])))
|
| 278 |
+
return hits[: int(limit)]
|
| 279 |
+
finally:
|
| 280 |
+
con.close()
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def build_fts_index(
|
| 284 |
+
corpus_parquet: Path,
|
| 285 |
+
duckdb_path: Path,
|
| 286 |
+
expected: int,
|
| 287 |
+
*,
|
| 288 |
+
log: Any | None = None,
|
| 289 |
+
) -> Path:
|
| 290 |
+
"""Load corpus parquet into DuckDB and create an FTS index (no SQLite)."""
|
| 291 |
+
duckdb = _require_duckdb()
|
| 292 |
+
duckdb_path = Path(duckdb_path)
|
| 293 |
+
duckdb_path.parent.mkdir(parents=True, exist_ok=True)
|
| 294 |
+
if duckdb_path.exists():
|
| 295 |
+
duckdb_path.unlink()
|
| 296 |
+
escaped = str(Path(corpus_parquet).resolve()).replace("'", "''")
|
| 297 |
+
con = duckdb.connect(str(duckdb_path))
|
| 298 |
+
try:
|
| 299 |
+
con.execute(
|
| 300 |
+
f"""
|
| 301 |
+
CREATE TABLE documents AS
|
| 302 |
+
SELECT
|
| 303 |
+
CAST(document_index AS INTEGER) AS document_index,
|
| 304 |
+
CAST(entry_cid AS VARCHAR) AS entry_cid,
|
| 305 |
+
CAST(COALESCE(title, '') AS VARCHAR) AS title,
|
| 306 |
+
CAST(COALESCE(body, '') AS VARCHAR) AS body
|
| 307 |
+
FROM read_parquet('{escaped}')
|
| 308 |
+
"""
|
| 309 |
+
)
|
| 310 |
+
n = int(con.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 311 |
+
if n != int(expected):
|
| 312 |
+
raise DuckDBStoreError(f"DuckDB corpus rows {n} != expected {expected}")
|
| 313 |
+
con.execute("INSTALL fts")
|
| 314 |
+
con.execute("LOAD fts")
|
| 315 |
+
con.execute(
|
| 316 |
+
"PRAGMA create_fts_index('documents', 'document_index', 'title', 'body', "
|
| 317 |
+
"stemmer='porter', stopwords='english', ignore='(\\.+)', strip_accents=1, lower=1)"
|
| 318 |
+
)
|
| 319 |
+
if log:
|
| 320 |
+
log(f"duckdb fts ready n={n} path={duckdb_path}")
|
| 321 |
+
finally:
|
| 322 |
+
con.close()
|
| 323 |
+
return duckdb_path
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def stream_neighbors_to_parquet(
|
| 327 |
+
duckdb_path: Path,
|
| 328 |
+
spill: Path,
|
| 329 |
+
n_docs: int,
|
| 330 |
+
*,
|
| 331 |
+
k: int = 8,
|
| 332 |
+
shard: int = 5000,
|
| 333 |
+
batch: int = 256,
|
| 334 |
+
resume: bool = True,
|
| 335 |
+
log: Any | None = None,
|
| 336 |
+
) -> list[Path]:
|
| 337 |
+
"""Stream DuckDB FTS neighbors into flattened neighbor_*.parquet shards."""
|
| 338 |
+
duckdb = _require_duckdb()
|
| 339 |
+
spill = Path(spill)
|
| 340 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 341 |
+
existing = sorted(spill.glob("neighbors_*.parquet"))
|
| 342 |
+
buf_start = 0
|
| 343 |
+
shard_paths: list[Path] = []
|
| 344 |
+
if resume and existing:
|
| 345 |
+
covered = 0
|
| 346 |
+
for path in existing:
|
| 347 |
+
parts = path.stem.split("_")
|
| 348 |
+
try:
|
| 349 |
+
start_i, end_i = int(parts[1]), int(parts[2])
|
| 350 |
+
except (IndexError, ValueError):
|
| 351 |
+
continue
|
| 352 |
+
if start_i != covered:
|
| 353 |
+
break
|
| 354 |
+
shard_paths.append(path)
|
| 355 |
+
covered = end_i
|
| 356 |
+
buf_start = covered
|
| 357 |
+
if buf_start >= n_docs:
|
| 358 |
+
if log:
|
| 359 |
+
log(f"neighbors resume complete {buf_start}/{n_docs}")
|
| 360 |
+
return shard_paths
|
| 361 |
+
for path in existing:
|
| 362 |
+
if path not in shard_paths:
|
| 363 |
+
path.unlink(missing_ok=True)
|
| 364 |
+
else:
|
| 365 |
+
for path in existing:
|
| 366 |
+
path.unlink(missing_ok=True)
|
| 367 |
+
|
| 368 |
+
con = duckdb.connect(str(duckdb_path), read_only=True)
|
| 369 |
+
con.execute("LOAD fts")
|
| 370 |
+
rows_buf: list[dict[str, Any]] = []
|
| 371 |
+
shard_start = buf_start
|
| 372 |
+
last_idx = buf_start - 1
|
| 373 |
+
done = buf_start
|
| 374 |
+
try:
|
| 375 |
+
while True:
|
| 376 |
+
batch_rows = con.execute(
|
| 377 |
+
"SELECT document_index, title, body FROM documents "
|
| 378 |
+
"WHERE document_index > ? ORDER BY document_index LIMIT ?",
|
| 379 |
+
[last_idx, batch],
|
| 380 |
+
).fetchall()
|
| 381 |
+
if not batch_rows:
|
| 382 |
+
break
|
| 383 |
+
for di, title, body in batch_rows:
|
| 384 |
+
di = int(di)
|
| 385 |
+
query = (str(title or "").strip() or str(body or "")[:800]).strip()
|
| 386 |
+
hits: list[tuple[int, float]] = []
|
| 387 |
+
if query:
|
| 388 |
+
hits = con.execute(
|
| 389 |
+
"SELECT document_index, "
|
| 390 |
+
"fts_main_documents.match_bm25(document_index, ?) AS score "
|
| 391 |
+
"FROM documents "
|
| 392 |
+
"WHERE document_index != ? AND score IS NOT NULL "
|
| 393 |
+
"ORDER BY score DESC, document_index "
|
| 394 |
+
"LIMIT ?",
|
| 395 |
+
[query, di, int(k)],
|
| 396 |
+
).fetchall()
|
| 397 |
+
for neigh_i, score in hits:
|
| 398 |
+
rows_buf.append(
|
| 399 |
+
{
|
| 400 |
+
"source_index": di,
|
| 401 |
+
"neighbor_index": int(neigh_i),
|
| 402 |
+
"score": float(score or 0.0),
|
| 403 |
+
}
|
| 404 |
+
)
|
| 405 |
+
last_idx = di
|
| 406 |
+
done += 1
|
| 407 |
+
if (di + 1 - shard_start) >= shard:
|
| 408 |
+
end = di + 1
|
| 409 |
+
path = spill / f"neighbors_{shard_start:06d}_{end:06d}.parquet"
|
| 410 |
+
pd.DataFrame(rows_buf).to_parquet(path, index=False)
|
| 411 |
+
shard_paths.append(path)
|
| 412 |
+
rows_buf = []
|
| 413 |
+
shard_start = end
|
| 414 |
+
if log:
|
| 415 |
+
log(f"neighbors parquet shard {path.name}")
|
| 416 |
+
if done % 5_000 == 0 and log:
|
| 417 |
+
log(f"duckdb neighbors {done}/{n_docs}")
|
| 418 |
+
if shard_start < n_docs:
|
| 419 |
+
path = spill / f"neighbors_{shard_start:06d}_{n_docs:06d}.parquet"
|
| 420 |
+
pd.DataFrame(rows_buf).to_parquet(path, index=False)
|
| 421 |
+
shard_paths.append(path)
|
| 422 |
+
if log:
|
| 423 |
+
log(f"duckdb neighbors done={done} shards={len(shard_paths)}")
|
| 424 |
+
return shard_paths
|
| 425 |
+
finally:
|
| 426 |
+
con.close()
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def iter_neighbor_parquet_shards(spill: Path) -> Any:
|
| 430 |
+
"""Yield (start_index, list-of-neighbor-lists) from parquet shards."""
|
| 431 |
+
import pandas as pd
|
| 432 |
+
|
| 433 |
+
paths = sorted(Path(spill).glob("neighbors_*.parquet"))
|
| 434 |
+
for path in paths:
|
| 435 |
+
parts = path.stem.split("_")
|
| 436 |
+
start_i = int(parts[1])
|
| 437 |
+
end_i = int(parts[2])
|
| 438 |
+
frame = pd.read_parquet(path)
|
| 439 |
+
part: list[list] = [[] for _ in range(max(0, end_i - start_i))]
|
| 440 |
+
if not frame.empty:
|
| 441 |
+
for rec in frame.itertuples(index=False):
|
| 442 |
+
src = int(rec.source_index)
|
| 443 |
+
offset = src - start_i
|
| 444 |
+
if 0 <= offset < len(part):
|
| 445 |
+
part[offset].append(
|
| 446 |
+
(int(rec.neighbor_index), float(rec.score), [])
|
| 447 |
+
)
|
| 448 |
+
yield start_i, part
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def materialize_corpus_duckdb(corpus_parquet: Path, duckdb_path: Path) -> Path:
|
| 452 |
+
"""Load a corpus parquet file into a persistent DuckDB database."""
|
| 453 |
+
duckdb = _require_duckdb()
|
| 454 |
+
duckdb_path = Path(duckdb_path)
|
| 455 |
+
duckdb_path.parent.mkdir(parents=True, exist_ok=True)
|
| 456 |
+
if duckdb_path.exists():
|
| 457 |
+
duckdb_path.unlink()
|
| 458 |
+
con = duckdb.connect(str(duckdb_path))
|
| 459 |
+
try:
|
| 460 |
+
con.execute(
|
| 461 |
+
"""
|
| 462 |
+
CREATE TABLE documents AS
|
| 463 |
+
SELECT
|
| 464 |
+
CAST(document_index AS INTEGER) AS document_index,
|
| 465 |
+
CAST(entry_cid AS VARCHAR) AS entry_cid,
|
| 466 |
+
CAST(title AS VARCHAR) AS title,
|
| 467 |
+
CAST(body AS VARCHAR) AS body
|
| 468 |
+
FROM read_parquet(?)
|
| 469 |
+
""",
|
| 470 |
+
[str(corpus_parquet)],
|
| 471 |
+
)
|
| 472 |
+
con.execute("CREATE INDEX documents_idx ON documents(document_index)")
|
| 473 |
+
finally:
|
| 474 |
+
con.close()
|
| 475 |
+
return duckd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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Property graph: entry nodes, facet nodes, BM25_NEIGHBOR_OF k=8, ARTICLE_OF, ELI."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections import defaultdict
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from . import EDGE_IDENTITY_SCHEMA, FACET_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 11 |
+
from .cidutil import cid_of_json
|
| 12 |
+
|
| 13 |
+
# Facet kinds requested by the SkillCenter-style country-laws graph:
|
| 14 |
+
# jurisdiction, language, instrument/law, source, status.
|
| 15 |
+
FACET_FIELDS = (
|
| 16 |
+
("jurisdiction", "HAS_JURISDICTION", "jurisdiction"),
|
| 17 |
+
("language", "HAS_LANGUAGE", "language"),
|
| 18 |
+
("instrument", "HAS_INSTRUMENT", "instrument_id"),
|
| 19 |
+
("source", "HAS_SOURCE", "source_type"),
|
| 20 |
+
("status", "HAS_STATUS", "law_status"),
|
| 21 |
+
)
|
| 22 |
+
ADJ_POINTERS_PER_ROW = 4096
|
| 23 |
+
ADJ_POINTERS_PER_SHARD = 8192
|
| 24 |
+
_LABEL_MAX = 4096
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _graph_label(text: str, fallback: str) -> str:
|
| 28 |
+
"""Node labels are capped at 4096 characters. The full value stays in properties."""
|
| 29 |
+
cleaned = str(text or "").replace("\x00", "").strip() or fallback
|
| 30 |
+
if len(cleaned) > _LABEL_MAX:
|
| 31 |
+
return cleaned[: _LABEL_MAX - 3] + "..."
|
| 32 |
+
return cleaned
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _facet_cid(kind: str, value: str) -> str:
|
| 36 |
+
"""CIDv1 raw sha2-256 of sorted JSON {kind, schema, value}."""
|
| 37 |
+
return cid_of_json(
|
| 38 |
+
{
|
| 39 |
+
"kind": kind,
|
| 40 |
+
"schema": FACET_IDENTITY_SCHEMA,
|
| 41 |
+
"value": value,
|
| 42 |
+
}
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _edge_cid(source: str, edge_type: str, target: str) -> str:
|
| 47 |
+
return cid_of_json(
|
| 48 |
+
{
|
| 49 |
+
"edge_type": edge_type,
|
| 50 |
+
"schema": EDGE_IDENTITY_SCHEMA,
|
| 51 |
+
"source": source,
|
| 52 |
+
"target": target,
|
| 53 |
+
}
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def build_graph(
|
| 58 |
+
corpus: pd.DataFrame,
|
| 59 |
+
neighbors: list[list[tuple]],
|
| 60 |
+
) -> dict[str, Any]:
|
| 61 |
+
nodes: list[dict[str, Any]] = []
|
| 62 |
+
edges: list[dict[str, Any]] = []
|
| 63 |
+
seen_facets: set[str] = set()
|
| 64 |
+
cid_by_idx = corpus["entry_cid"].tolist()
|
| 65 |
+
|
| 66 |
+
# Law identity nodes (targets of ARTICLE_OF when the parent is not a corpus entry).
|
| 67 |
+
law_nodes: dict[str, dict[str, Any]] = {}
|
| 68 |
+
entry_by_instrument: dict[str, str] = {}
|
| 69 |
+
for rec in corpus.itertuples(index=False):
|
| 70 |
+
law_cid = str(getattr(rec, "law_cid", "") or "")
|
| 71 |
+
instrument_id = str(getattr(rec, "instrument_id", "") or "")
|
| 72 |
+
if getattr(rec, "record_type", "") == "law" and instrument_id and rec.entry_cid:
|
| 73 |
+
entry_by_instrument.setdefault(instrument_id, rec.entry_cid)
|
| 74 |
+
if not law_cid or law_cid in law_nodes:
|
| 75 |
+
continue
|
| 76 |
+
law_nodes[law_cid] = {
|
| 77 |
+
"node_cid": law_cid,
|
| 78 |
+
"node_type": "law",
|
| 79 |
+
"entry_cid": "",
|
| 80 |
+
"label": _graph_label(getattr(rec, "instrument_title", None) or instrument_id, instrument_id),
|
| 81 |
+
"properties_json": _json(
|
| 82 |
+
{
|
| 83 |
+
"instrument_id": instrument_id,
|
| 84 |
+
"instrument_title": str(getattr(rec, "instrument_title", "") or ""),
|
| 85 |
+
"jurisdiction": str(getattr(rec, "jurisdiction", "") or ""),
|
| 86 |
+
"language": str(getattr(rec, "language", "") or ""),
|
| 87 |
+
"law_cid": law_cid,
|
| 88 |
+
}
|
| 89 |
+
),
|
| 90 |
+
"schema_version": SCHEMA_VERSION,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
for law_node in law_nodes.values():
|
| 94 |
+
nodes.append(law_node)
|
| 95 |
+
|
| 96 |
+
for rec in corpus.itertuples(index=False):
|
| 97 |
+
if rec.record_type == "law":
|
| 98 |
+
node_type = "law_entry"
|
| 99 |
+
elif rec.record_type == "notice":
|
| 100 |
+
node_type = "notice"
|
| 101 |
+
else:
|
| 102 |
+
node_type = "article"
|
| 103 |
+
title = getattr(rec, "title", None) or getattr(rec, "instrument_title", None) or rec.source_id
|
| 104 |
+
nodes.append(
|
| 105 |
+
{
|
| 106 |
+
"node_cid": rec.entry_cid,
|
| 107 |
+
"node_type": node_type,
|
| 108 |
+
"entry_cid": rec.entry_cid,
|
| 109 |
+
"label": _graph_label(title or rec.source_id, str(rec.source_id)),
|
| 110 |
+
"properties_json": _props_tuple(rec),
|
| 111 |
+
"schema_version": SCHEMA_VERSION,
|
| 112 |
+
}
|
| 113 |
+
)
|
| 114 |
+
src = rec.entry_cid
|
| 115 |
+
row_map = rec._asdict() if hasattr(rec, "_asdict") else {}
|
| 116 |
+
|
| 117 |
+
for kind, edge_type, col in FACET_FIELDS:
|
| 118 |
+
value = str(row_map.get(col) or "").strip()
|
| 119 |
+
if not value:
|
| 120 |
+
continue
|
| 121 |
+
fc = _facet_cid(kind, value)
|
| 122 |
+
if fc not in seen_facets:
|
| 123 |
+
seen_facets.add(fc)
|
| 124 |
+
nodes.append(
|
| 125 |
+
{
|
| 126 |
+
"node_cid": fc,
|
| 127 |
+
"node_type": f"facet_{kind}",
|
| 128 |
+
"entry_cid": "",
|
| 129 |
+
"label": _graph_label(f"{kind}:{value}", kind),
|
| 130 |
+
"properties_json": _json({"kind": kind, "value": value}),
|
| 131 |
+
"schema_version": SCHEMA_VERSION,
|
| 132 |
+
}
|
| 133 |
+
)
|
| 134 |
+
edges.append(_edge(src, edge_type, fc, "facet", 1.0, {"facet": kind, "value": value}))
|
| 135 |
+
|
| 136 |
+
# ELI / identifier links — only values present in the source, never invented.
|
| 137 |
+
eli = str(row_map.get("eli") or "").strip()
|
| 138 |
+
if eli:
|
| 139 |
+
fc = _facet_cid("eli", eli)
|
| 140 |
+
if fc not in seen_facets:
|
| 141 |
+
seen_facets.add(fc)
|
| 142 |
+
nodes.append(
|
| 143 |
+
{
|
| 144 |
+
"node_cid": fc,
|
| 145 |
+
"node_type": "facet_eli",
|
| 146 |
+
"entry_cid": "",
|
| 147 |
+
"label": _graph_label(f"eli:{eli}", "eli"),
|
| 148 |
+
"properties_json": _json({"kind": "eli", "value": eli}),
|
| 149 |
+
"schema_version": SCHEMA_VERSION,
|
| 150 |
+
}
|
| 151 |
+
)
|
| 152 |
+
edges.append(_edge(src, "IDENTIFIED_BY_ELI", fc, "identifier", 1.0, {"eli": eli}))
|
| 153 |
+
ident = str(row_map.get("official_identifier") or row_map.get("identifier") or "").strip()
|
| 154 |
+
if ident and ident != eli:
|
| 155 |
+
fc = _facet_cid("identifier", ident)
|
| 156 |
+
if fc not in seen_facets:
|
| 157 |
+
seen_facets.add(fc)
|
| 158 |
+
nodes.append(
|
| 159 |
+
{
|
| 160 |
+
"node_cid": fc,
|
| 161 |
+
"node_type": "facet_identifier",
|
| 162 |
+
"entry_cid": "",
|
| 163 |
+
"label": _graph_label(f"identifier:{ident}", "identifier"),
|
| 164 |
+
"properties_json": _json({"kind": "identifier", "value": ident}),
|
| 165 |
+
"schema_version": SCHEMA_VERSION,
|
| 166 |
+
}
|
| 167 |
+
)
|
| 168 |
+
edges.append(
|
| 169 |
+
_edge(src, "IDENTIFIED_BY", fc, "identifier", 1.0, {"identifier": ident})
|
| 170 |
+
)
|
| 171 |
+
|
| 172 |
+
law_cid = str(row_map.get("law_cid") or "")
|
| 173 |
+
instrument_id = str(row_map.get("instrument_id") or "")
|
| 174 |
+
if rec.record_type in {"article", "section"}:
|
| 175 |
+
parent = entry_by_instrument.get(instrument_id) or law_cid
|
| 176 |
+
if parent and parent != rec.entry_cid:
|
| 177 |
+
edges.append(
|
| 178 |
+
_edge(
|
| 179 |
+
rec.entry_cid,
|
| 180 |
+
"ARTICLE_OF",
|
| 181 |
+
parent,
|
| 182 |
+
"structural",
|
| 183 |
+
1.0,
|
| 184 |
+
{
|
| 185 |
+
"instrument_id": instrument_id,
|
| 186 |
+
"article_number": row_map.get("article_number"),
|
| 187 |
+
},
|
| 188 |
+
)
|
| 189 |
+
)
|
| 190 |
+
elif law_cid and rec.entry_cid != law_cid:
|
| 191 |
+
# Law-level corpus unit still points at its instrument identity node.
|
| 192 |
+
edges.append(
|
| 193 |
+
_edge(
|
| 194 |
+
rec.entry_cid,
|
| 195 |
+
"HAS_INSTRUMENT",
|
| 196 |
+
law_cid,
|
| 197 |
+
"structural",
|
| 198 |
+
1.0,
|
| 199 |
+
{"instrument_id": instrument_id},
|
| 200 |
+
)
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
for i, neigh in enumerate(neighbors):
|
| 204 |
+
src = cid_by_idx[i]
|
| 205 |
+
for item in neigh:
|
| 206 |
+
if len(item) == 3:
|
| 207 |
+
j, score, terms = item
|
| 208 |
+
else:
|
| 209 |
+
j, score = item[0], item[1]
|
| 210 |
+
terms = []
|
| 211 |
+
tgt = cid_by_idx[int(j)]
|
| 212 |
+
edges.append(
|
| 213 |
+
_edge(
|
| 214 |
+
src,
|
| 215 |
+
"BM25_NEIGHBOR_OF",
|
| 216 |
+
tgt,
|
| 217 |
+
"bm25-okapi",
|
| 218 |
+
float(score),
|
| 219 |
+
{"k": 8, "neighbor_index": int(j)},
|
| 220 |
+
matched_terms=list(terms),
|
| 221 |
+
)
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
nodes_df = pd.DataFrame(nodes).drop_duplicates("node_cid").reset_index(drop=True)
|
| 225 |
+
nodes_df = nodes_df.sort_values(["node_type", "node_cid"]).reset_index(drop=True)
|
| 226 |
+
edges_df = pd.DataFrame(edges)
|
| 227 |
+
if not edges_df.empty:
|
| 228 |
+
edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True)
|
| 229 |
+
edges_df = edges_df.sort_values(["edge_type", "source_cid", "target_cid"]).reset_index(drop=True)
|
| 230 |
+
|
| 231 |
+
node_type = {r["node_cid"]: r["node_type"] for r in nodes_df.to_dict("records")}
|
| 232 |
+
incoming, outgoing = _adjacency(edges_df, node_type)
|
| 233 |
+
return {
|
| 234 |
+
"nodes": nodes_df,
|
| 235 |
+
"edges": edges_df,
|
| 236 |
+
"incoming": incoming,
|
| 237 |
+
"outgoing": outgoing,
|
| 238 |
+
"stats": {
|
| 239 |
+
"n_nodes": int(len(nodes_df)),
|
| 240 |
+
"n_edges": int(len(edges_df)),
|
| 241 |
+
"n_doc_nodes": int(nodes_df["node_type"].isin(["law_entry", "article", "law"]).sum()),
|
| 242 |
+
"n_facet_nodes": int(nodes_df["node_type"].astype(str).str.startswith("facet_").sum()),
|
| 243 |
+
"edge_types": sorted(edges_df["edge_type"].unique().tolist()) if not edges_df.empty else [],
|
| 244 |
+
},
|
| 245 |
+
}
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _json(obj: dict) -> str:
|
| 249 |
+
import json
|
| 250 |
+
|
| 251 |
+
return json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _props_tuple(rec: Any) -> str:
|
| 255 |
+
keys = [
|
| 256 |
+
"record_type",
|
| 257 |
+
"instrument_id",
|
| 258 |
+
"instrument_title",
|
| 259 |
+
"law_cid",
|
| 260 |
+
"article_number",
|
| 261 |
+
"article_title",
|
| 262 |
+
"jurisdiction",
|
| 263 |
+
"language",
|
| 264 |
+
"source_url",
|
| 265 |
+
"snapshot_date",
|
| 266 |
+
"coverage",
|
| 267 |
+
"license",
|
| 268 |
+
"collector",
|
| 269 |
+
"source_id",
|
| 270 |
+
"eli",
|
| 271 |
+
"law_status",
|
| 272 |
+
"source_type",
|
| 273 |
+
]
|
| 274 |
+
d = rec._asdict() if hasattr(rec, "_asdict") else {}
|
| 275 |
+
out = {}
|
| 276 |
+
for k in keys:
|
| 277 |
+
v = d.get(k, "")
|
| 278 |
+
if v is None or (isinstance(v, float) and pd.isna(v)):
|
| 279 |
+
v = ""
|
| 280 |
+
out[k] = str(v)
|
| 281 |
+
return _json(out)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _edge(
|
| 285 |
+
src: str,
|
| 286 |
+
etype: str,
|
| 287 |
+
tgt: str,
|
| 288 |
+
method: str,
|
| 289 |
+
score: float,
|
| 290 |
+
props: dict,
|
| 291 |
+
matched_terms: list[str] | None = None,
|
| 292 |
+
) -> dict[str, Any]:
|
| 293 |
+
import json
|
| 294 |
+
|
| 295 |
+
terms = matched_terms or []
|
| 296 |
+
return {
|
| 297 |
+
"edge_cid": _edge_cid(src, etype, tgt),
|
| 298 |
+
"edge_type": etype,
|
| 299 |
+
"source_cid": src,
|
| 300 |
+
"target_cid": tgt,
|
| 301 |
+
"retrieval_method": method,
|
| 302 |
+
"score": float(score),
|
| 303 |
+
"query_terms_json": json.dumps(terms, ensure_ascii=False, separators=(",", ":")),
|
| 304 |
+
"matched_terms": terms,
|
| 305 |
+
"properties_json": _json({k: v for k, v in props.items() if v is not None}),
|
| 306 |
+
"schema_version": SCHEMA_VERSION,
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _adjacency(edges: pd.DataFrame, node_type: dict[str, str]) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 311 |
+
out_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list)
|
| 312 |
+
in_map: dict[str, list[tuple[float, str, str, str]]] = defaultdict(list)
|
| 313 |
+
if edges is None or edges.empty:
|
| 314 |
+
return pd.DataFrame(), pd.DataFrame()
|
| 315 |
+
for rec in edges.itertuples(index=False):
|
| 316 |
+
score = float(rec.score) if rec.score == rec.score else float("-inf")
|
| 317 |
+
out_map[rec.source_cid].append((score, rec.target_cid, rec.edge_type, rec.edge_cid))
|
| 318 |
+
in_map[rec.target_cid].append((score, rec.source_cid, rec.edge_type, rec.edge_cid))
|
| 319 |
+
|
| 320 |
+
def pages(mapping: dict[str, list], direction: str) -> pd.DataFrame:
|
| 321 |
+
rows = []
|
| 322 |
+
for node, items in mapping.items():
|
| 323 |
+
items = sorted(items, key=lambda t: (-t[0] if t[0] == t[0] else float("inf"), t[1]))
|
| 324 |
+
total = len(items)
|
| 325 |
+
page_size = ADJ_POINTERS_PER_ROW
|
| 326 |
+
n_pages = max(1, (total + page_size - 1) // page_size)
|
| 327 |
+
for p in range(n_pages):
|
| 328 |
+
chunk = items[p * page_size : (p + 1) * page_size]
|
| 329 |
+
rows.append(
|
| 330 |
+
{
|
| 331 |
+
"direction": direction,
|
| 332 |
+
"node_cid": node,
|
| 333 |
+
"page_index": p,
|
| 334 |
+
"page_count": n_pages,
|
| 335 |
+
"neighbor_count": len(chunk),
|
| 336 |
+
"total_neighbor_count": total,
|
| 337 |
+
"neighbor_cids": [t[1] for t in chunk],
|
| 338 |
+
"neighbor_node_types": [node_type.get(t[1], "") for t in chunk],
|
| 339 |
+
"edge_types": [t[2] for t in chunk],
|
| 340 |
+
"edge_cids": [t[3] for t in chunk],
|
| 341 |
+
"retrieval_methods": ["graph"] * len(chunk),
|
| 342 |
+
"scores": [t[0] if t[0] != float("-inf") else None for t in chunk],
|
| 343 |
+
"schema_version": SCHEMA_VERSION,
|
| 344 |
+
}
|
| 345 |
+
)
|
| 346 |
+
if not rows:
|
| 347 |
+
return pd.DataFrame()
|
| 348 |
+
return pd.DataFrame(rows).sort_values(["node_cid", "page_index"]).reset_index(drop=True)
|
| 349 |
+
|
| 350 |
+
return pages(in_map, "incoming"), pages(out_map, "outgoing")
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/html_legal.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pull operative legal text out of municipal HTML chunks.
|
| 2 |
+
|
| 3 |
+
The scrapers store a page as ``<div class="chunk-content">``. The flattened
|
| 4 |
+
``text`` column still starts with letterhead, attendance rolls, and cover
|
| 5 |
+
sheets, and the embedder only reads the first 4,000 characters of the body.
|
| 6 |
+
This keeps the operative text and leaves a page unchanged when the cut would
|
| 7 |
+
drop most of it.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
from html.parser import HTMLParser
|
| 14 |
+
|
| 15 |
+
_LEGAL = re.compile(
|
| 16 |
+
r"(?i)("
|
| 17 |
+
r"§|"
|
| 18 |
+
r"\bart\.?\s*\d|"
|
| 19 |
+
r"\barticles?\s+\d|"
|
| 20 |
+
r"\bartikel\b|"
|
| 21 |
+
r"\bpasal\b|"
|
| 22 |
+
r"\bayat\b|"
|
| 23 |
+
r"\bmenimbang\b|"
|
| 24 |
+
r"\bmemutuskan\b|"
|
| 25 |
+
r"\bmenetapkan\b|"
|
| 26 |
+
r"\bperaturan\b|"
|
| 27 |
+
r"\bconsidérant\b|"
|
| 28 |
+
r"\bdécide\b|"
|
| 29 |
+
r"\bdélibère\b|"
|
| 30 |
+
r"\bvu (?:le|la|les|l['’])|"
|
| 31 |
+
r"\brundschreiben\b|"
|
| 32 |
+
r"\bverordnung\b|"
|
| 33 |
+
r"\bdecreto\b|"
|
| 34 |
+
r"\bdelibera\b|"
|
| 35 |
+
r"\brèglement\b|"
|
| 36 |
+
r"\barrêté\b|"
|
| 37 |
+
r"\brésumé\s*:"
|
| 38 |
+
r")"
|
| 39 |
+
)
|
| 40 |
+
_EMAIL = re.compile(r"\b[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}\b")
|
| 41 |
+
_URL = re.compile(r"(?i)\b(?:https?://|www\.)\S+")
|
| 42 |
+
_PHONE = re.compile(
|
| 43 |
+
r"(?i)\b(?:tel\.?|telefon|téléphone|telephone|cellulaire|télécopieur|telefax|fax)\b"
|
| 44 |
+
)
|
| 45 |
+
_TAX = re.compile(
|
| 46 |
+
r"(?i)\b(?:steuernr|mwst\.?|codice fiscale|partita iva|npwp|momsnr)\b"
|
| 47 |
+
)
|
| 48 |
+
_POSTAL = re.compile(
|
| 49 |
+
r"(?i)\b(?:straße|strasse|via |rue |väg|gatan|landhaus|palazzo)\b"
|
| 50 |
+
)
|
| 51 |
+
_TOC = re.compile(r"\.{4,}\s*\d{1,4}\s*$")
|
| 52 |
+
_PAGE = re.compile(r"^\d{1,4}$")
|
| 53 |
+
_PAGE_PREFIX = re.compile(r"^(\d{1,3})\s+(?=[A-ZÀ-ÖØ-Þ]{4,}\b)")
|
| 54 |
+
_LABEL = re.compile(
|
| 55 |
+
r"(?i)^(?:"
|
| 56 |
+
r"dokumentnamn|gäller\s+fr.*|gäller\s+t.*|diarienummer|fastställd(?:\s+av)?|"
|
| 57 |
+
r"dokumentansvar\w*|handläggare|dokumenthistorik|version|tidigare beslut|"
|
| 58 |
+
r"innehållsförteckning|rapporteur|secrétaire|commission|avis"
|
| 59 |
+
r")\s*:?\s*$"
|
| 60 |
+
)
|
| 61 |
+
_ATTEND = re.compile(
|
| 62 |
+
r"(?i)\b(?:étaient présents|etaient présents|étaient absents|etaient absents|"
|
| 63 |
+
r"procurations de vote|secrétaire\s*:)"
|
| 64 |
+
)
|
| 65 |
+
_START = re.compile(
|
| 66 |
+
r"(?i)("
|
| 67 |
+
r"résumé\s*:|"
|
| 68 |
+
r"\ble présent\b|"
|
| 69 |
+
r"\bvu (?:le|la|les|l['’])|"
|
| 70 |
+
r"\bconsidérant\b|"
|
| 71 |
+
r"\barticles?\s+\d|"
|
| 72 |
+
r"\bdécide\b|"
|
| 73 |
+
r"\brundschreiben\b|"
|
| 74 |
+
r"\bperaturan\b|"
|
| 75 |
+
r"\bmenimbang\b"
|
| 76 |
+
r")"
|
| 77 |
+
)
|
| 78 |
+
_ROLL = re.compile(
|
| 79 |
+
r"(?i)\b(?:étaient présents|etaient présents|présidence de|"
|
| 80 |
+
r"conseillers municipaux en exercice|procurations de vote)\b"
|
| 81 |
+
)
|
| 82 |
+
_ROLE = re.compile(
|
| 83 |
+
r"(?i)\b(?:kommundirektör|handläggare|utredare|föreningssamordnare|dokumentansvar)\b"
|
| 84 |
+
)
|
| 85 |
+
_IDLINE = re.compile(
|
| 86 |
+
r"^(?:[A-Z]{1,6}/\d{4}:\d+|\d{8}-\d+(?:\.\d+)?|\d{4}-\d{2}-\d{2})$"
|
| 87 |
+
)
|
| 88 |
+
_EMAIL_ONLY = re.compile(r"(?i)(?:nur mittels|solo via)\s+e-?mail")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class _Paragraphs(HTMLParser):
|
| 92 |
+
def __init__(self) -> None:
|
| 93 |
+
super().__init__(convert_charrefs=True)
|
| 94 |
+
self.parts: list[str] = []
|
| 95 |
+
self._buf: list[str] = []
|
| 96 |
+
self._skip = 0
|
| 97 |
+
|
| 98 |
+
def handle_starttag(self, tag, attrs):
|
| 99 |
+
if tag in {"script", "style", "noscript"}:
|
| 100 |
+
self._skip += 1
|
| 101 |
+
if tag in {"p", "br", "div", "li", "h1", "h2", "h3", "tr"} and self._skip == 0:
|
| 102 |
+
self._flush()
|
| 103 |
+
|
| 104 |
+
def handle_endtag(self, tag):
|
| 105 |
+
if tag in {"script", "style", "noscript"} and self._skip:
|
| 106 |
+
self._skip -= 1
|
| 107 |
+
if tag in {"p", "div", "li", "tr", "h1", "h2", "h3"} and self._skip == 0:
|
| 108 |
+
self._flush()
|
| 109 |
+
|
| 110 |
+
def handle_data(self, data):
|
| 111 |
+
if self._skip == 0 and data:
|
| 112 |
+
self._buf.append(data)
|
| 113 |
+
|
| 114 |
+
def _flush(self) -> None:
|
| 115 |
+
text = re.sub(r"\s+", " ", "".join(self._buf)).strip()
|
| 116 |
+
self._buf.clear()
|
| 117 |
+
if text:
|
| 118 |
+
self.parts.append(text)
|
| 119 |
+
|
| 120 |
+
def close(self):
|
| 121 |
+
super().close()
|
| 122 |
+
self._flush()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def _paragraphs(html: str, fallback: str) -> list[str]:
|
| 126 |
+
if html and "<" in html:
|
| 127 |
+
parser = _Paragraphs()
|
| 128 |
+
try:
|
| 129 |
+
parser.feed(html)
|
| 130 |
+
parser.close()
|
| 131 |
+
except Exception:
|
| 132 |
+
parser.parts = []
|
| 133 |
+
if parser.parts:
|
| 134 |
+
return parser.parts
|
| 135 |
+
raw = fallback or html or ""
|
| 136 |
+
parts = [re.sub(r"\s+", " ", line).strip() for line in raw.splitlines()]
|
| 137 |
+
return [part for part in parts if part]
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _is_chrome(text: str) -> bool:
|
| 141 |
+
if not text:
|
| 142 |
+
return True
|
| 143 |
+
if _PAGE.fullmatch(text) or _TOC.search(text) or _LABEL.fullmatch(text):
|
| 144 |
+
return True
|
| 145 |
+
if _EMAIL_ONLY.search(text) and len(text) < 80:
|
| 146 |
+
return True
|
| 147 |
+
if _IDLINE.fullmatch(text):
|
| 148 |
+
return True
|
| 149 |
+
if _ROLE.search(text) and len(text) < 140 and _LEGAL.search(text) is None:
|
| 150 |
+
return True
|
| 151 |
+
if _ATTEND.search(text) and _START.search(text) is None and _LEGAL.search(text) is None:
|
| 152 |
+
return True
|
| 153 |
+
if _LEGAL.search(text):
|
| 154 |
+
return False
|
| 155 |
+
if len(text) > 280:
|
| 156 |
+
return False
|
| 157 |
+
if _EMAIL.search(text) or _URL.search(text) or _PHONE.search(text) or _TAX.search(text):
|
| 158 |
+
return True
|
| 159 |
+
if _POSTAL.search(text) and len(text) < 140:
|
| 160 |
+
return True
|
| 161 |
+
return False
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def _leading_cover(text: str) -> bool:
|
| 165 |
+
"""Short cover-sheet line with no operative marker."""
|
| 166 |
+
if _LEGAL.search(text) or _is_chrome(text):
|
| 167 |
+
return False
|
| 168 |
+
if len(text) > 90:
|
| 169 |
+
return False
|
| 170 |
+
words = text.split()
|
| 171 |
+
return len(words) <= 14
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _trim_blob(text: str) -> str:
|
| 175 |
+
match = _START.search(text)
|
| 176 |
+
if match is None or match.start() < 60:
|
| 177 |
+
return text
|
| 178 |
+
head = text[: match.start()]
|
| 179 |
+
if _ROLL.search(head) or _ATTEND.search(head) or re.search(r"(?i)\b(?:mairie|rapporteur)\b", head):
|
| 180 |
+
return text[match.start() :].strip()
|
| 181 |
+
return text
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _strip_page_prefix(text: str) -> str:
|
| 185 |
+
match = _PAGE_PREFIX.match(text)
|
| 186 |
+
if match is None or int(match.group(1)) > 40:
|
| 187 |
+
return text
|
| 188 |
+
return text[match.end() :].strip()
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def extract_municipal_legal_text(html: str, fallback: str = "") -> str:
|
| 192 |
+
"""Return operative text. ``fallback`` is the flattened page text."""
|
| 193 |
+
base = re.sub(r"\s+", " ", (fallback or "")).strip()
|
| 194 |
+
paragraphs = [_trim_blob(part) for part in _paragraphs(html or "", fallback or "")]
|
| 195 |
+
start = 0
|
| 196 |
+
while start < len(paragraphs) and (
|
| 197 |
+
_is_chrome(paragraphs[start]) or _leading_cover(paragraphs[start])
|
| 198 |
+
):
|
| 199 |
+
start += 1
|
| 200 |
+
kept: list[str] = []
|
| 201 |
+
for part in paragraphs[start:]:
|
| 202 |
+
if _is_chrome(part):
|
| 203 |
+
continue
|
| 204 |
+
part = _strip_page_prefix(part)
|
| 205 |
+
if part:
|
| 206 |
+
kept.append(part)
|
| 207 |
+
cleaned = "\n".join(kept).strip()
|
| 208 |
+
plain = (fallback or "").strip()
|
| 209 |
+
if not cleaned:
|
| 210 |
+
return plain
|
| 211 |
+
if plain and len(plain) > 400 and len(cleaned) < int(0.2 * len(plain)):
|
| 212 |
+
return plain
|
| 213 |
+
return cleaned
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/incremental.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""CID-keyed incremental GraphRAG rebuild for country-laws IR.
|
| 2 |
+
|
| 3 |
+
Follows the US Code / patent persistent-index pattern:
|
| 4 |
+
|
| 5 |
+
* ``entry_cid`` is the durable identity (not positional ``document_index``).
|
| 6 |
+
* A matching source revision + parquet digest is a no-op.
|
| 7 |
+
* Unchanged CIDs reuse embeddings; BM25/graph are rebuilt from the current
|
| 8 |
+
corpus because ``document_index`` is a shard pointer, not an identity.
|
| 9 |
+
* Delta refresh is never labeled equivalent to a full rebuild.
|
| 10 |
+
|
| 11 |
+
Public Hub reads stay anonymous. Publication to ``justicedao/*`` is a separate
|
| 12 |
+
gated upload step.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
from enum import Enum
|
| 19 |
+
import json
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
from typing import Any, Iterable, Mapping
|
| 22 |
+
|
| 23 |
+
import pandas as pd
|
| 24 |
+
|
| 25 |
+
from . import SCHEMA_VERSION
|
| 26 |
+
|
| 27 |
+
class RebuildKind(str, Enum):
|
| 28 |
+
UNCHANGED = "unchanged"
|
| 29 |
+
DELTA_REFRESH = "delta_refresh"
|
| 30 |
+
FULL_REBUILD = "full_rebuild"
|
| 31 |
+
|
| 32 |
+
@classmethod
|
| 33 |
+
def coerce(cls, value: Any) -> "RebuildKind":
|
| 34 |
+
if isinstance(value, RebuildKind):
|
| 35 |
+
return value
|
| 36 |
+
text = str(value or "").strip().lower().replace("-", "_")
|
| 37 |
+
aliases = {
|
| 38 |
+
"skip": cls.UNCHANGED,
|
| 39 |
+
"noop": cls.UNCHANGED,
|
| 40 |
+
"none": cls.UNCHANGED,
|
| 41 |
+
"delta": cls.DELTA_REFRESH,
|
| 42 |
+
"incremental": cls.DELTA_REFRESH,
|
| 43 |
+
"partial": cls.DELTA_REFRESH,
|
| 44 |
+
"full": cls.FULL_REBUILD,
|
| 45 |
+
"rebuild": cls.FULL_REBUILD,
|
| 46 |
+
"force": cls.FULL_REBUILD,
|
| 47 |
+
}
|
| 48 |
+
if text in aliases:
|
| 49 |
+
return aliases[text]
|
| 50 |
+
for kind in cls:
|
| 51 |
+
if kind.value == text or kind.name.lower() == text:
|
| 52 |
+
return kind
|
| 53 |
+
raise ValueError(f"unknown rebuild kind: {value!r}")
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class BuildMode(str, Enum):
|
| 57 |
+
AUTO = "auto"
|
| 58 |
+
FULL = "full"
|
| 59 |
+
DELTA = "delta"
|
| 60 |
+
|
| 61 |
+
@classmethod
|
| 62 |
+
def coerce(cls, value: Any) -> "BuildMode":
|
| 63 |
+
if isinstance(value, BuildMode):
|
| 64 |
+
return value
|
| 65 |
+
text = str(value or "").strip().lower().replace("-", "_")
|
| 66 |
+
aliases = {
|
| 67 |
+
"incremental": cls.DELTA,
|
| 68 |
+
"diff": cls.DELTA,
|
| 69 |
+
"rebuild": cls.FULL,
|
| 70 |
+
"complete": cls.FULL,
|
| 71 |
+
}
|
| 72 |
+
if text in aliases:
|
| 73 |
+
return aliases[text]
|
| 74 |
+
for mode in cls:
|
| 75 |
+
if mode.value == text or mode.name.lower() == text:
|
| 76 |
+
return mode
|
| 77 |
+
raise ValueError(f"unknown build mode: {value!r}")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass(frozen=True)
|
| 81 |
+
class CorpusDelta:
|
| 82 |
+
added_cids: tuple[str, ...] = ()
|
| 83 |
+
removed_cids: tuple[str, ...] = ()
|
| 84 |
+
unchanged_cids: tuple[str, ...] = ()
|
| 85 |
+
prior_count: int = 0
|
| 86 |
+
current_count: int = 0
|
| 87 |
+
changed_ratio: float = 1.0
|
| 88 |
+
equivalent_to_full: bool = False
|
| 89 |
+
|
| 90 |
+
@property
|
| 91 |
+
def n_added(self) -> int:
|
| 92 |
+
return len(self.added_cids)
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def n_removed(self) -> int:
|
| 96 |
+
return len(self.removed_cids)
|
| 97 |
+
|
| 98 |
+
@property
|
| 99 |
+
def n_unchanged(self) -> int:
|
| 100 |
+
return len(self.unchanged_cids)
|
| 101 |
+
|
| 102 |
+
def to_dict(self, *, include_cids: bool = False, cid_sample: int = 8) -> dict[str, Any]:
|
| 103 |
+
payload = {
|
| 104 |
+
"n_added": self.n_added,
|
| 105 |
+
"n_removed": self.n_removed,
|
| 106 |
+
"n_unchanged": self.n_unchanged,
|
| 107 |
+
"prior_count": self.prior_count,
|
| 108 |
+
"current_count": self.current_count,
|
| 109 |
+
"changed_ratio": self.changed_ratio,
|
| 110 |
+
"equivalent_to_full": self.equivalent_to_full,
|
| 111 |
+
}
|
| 112 |
+
if include_cids:
|
| 113 |
+
payload["added_cids"] = list(self.added_cids)
|
| 114 |
+
payload["removed_cids"] = list(self.removed_cids)
|
| 115 |
+
payload["unchanged_cids"] = list(self.unchanged_cids)
|
| 116 |
+
else:
|
| 117 |
+
payload["added_cids_sample"] = list(self.added_cids[:cid_sample])
|
| 118 |
+
payload["removed_cids_sample"] = list(self.removed_cids[:cid_sample])
|
| 119 |
+
return payload
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass(frozen=True)
|
| 123 |
+
class RebuildPlan:
|
| 124 |
+
kind: RebuildKind
|
| 125 |
+
mode: BuildMode
|
| 126 |
+
reason: str
|
| 127 |
+
source_revision: str
|
| 128 |
+
prior_revision: str | None = None
|
| 129 |
+
source_fingerprint: str = ""
|
| 130 |
+
prior_fingerprint: str | None = None
|
| 131 |
+
delta: CorpusDelta | None = None
|
| 132 |
+
reuse_embeddings: bool = False
|
| 133 |
+
skip_build: bool = False
|
| 134 |
+
equivalent_to_full: bool = False
|
| 135 |
+
|
| 136 |
+
def to_dict(self) -> dict[str, Any]:
|
| 137 |
+
return {
|
| 138 |
+
"kind": self.kind.value,
|
| 139 |
+
"mode": self.mode.value,
|
| 140 |
+
"reason": self.reason,
|
| 141 |
+
"source_revision": self.source_revision,
|
| 142 |
+
"prior_revision": self.prior_revision,
|
| 143 |
+
"source_fingerprint": self.source_fingerprint,
|
| 144 |
+
"prior_fingerprint": self.prior_fingerprint,
|
| 145 |
+
"delta": None if self.delta is None else self.delta.to_dict(include_cids=False),
|
| 146 |
+
"reuse_embeddings": self.reuse_embeddings,
|
| 147 |
+
"skip_build": self.skip_build,
|
| 148 |
+
"equivalent_to_full": self.equivalent_to_full,
|
| 149 |
+
"schema_version": SCHEMA_VERSION,
|
| 150 |
+
}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@dataclass
|
| 154 |
+
class PriorRelease:
|
| 155 |
+
directory: Path
|
| 156 |
+
manifest: dict[str, Any] = field(default_factory=dict)
|
| 157 |
+
corpus: pd.DataFrame | None = None
|
| 158 |
+
vectors_by_cid: dict[str, list[float]] | None = None
|
| 159 |
+
|
| 160 |
+
@property
|
| 161 |
+
def source_revision(self) -> str | None:
|
| 162 |
+
return (
|
| 163 |
+
self.manifest.get("dataset_revision")
|
| 164 |
+
or (self.manifest.get("source") or {}).get("source_revision")
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
@property
|
| 168 |
+
def fingerprint(self) -> str:
|
| 169 |
+
return source_fingerprint_from_manifest(self.manifest)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def stamp_source_revision(manifest: dict[str, Any], new_revision: str) -> bool:
|
| 173 |
+
"""Record a new raw SHA on an unchanged release.
|
| 174 |
+
|
| 175 |
+
Entry rows can match while the endomorphosis commit moved. The gap scan
|
| 176 |
+
compares ``dataset_revision``, so an unchanged corpus still needs that
|
| 177 |
+
field updated or the pack stays stale forever.
|
| 178 |
+
"""
|
| 179 |
+
|
| 180 |
+
new = str(new_revision or "").strip().lower()
|
| 181 |
+
if len(new) != 40 or any(ch not in "0123456789abcdef" for ch in new):
|
| 182 |
+
return False
|
| 183 |
+
old = str(manifest.get("dataset_revision") or "").strip().lower()
|
| 184 |
+
if not old or old == new:
|
| 185 |
+
return False
|
| 186 |
+
manifest["dataset_revision"] = new
|
| 187 |
+
for key in ("source", "normalization"):
|
| 188 |
+
block = manifest.get(key)
|
| 189 |
+
if isinstance(block, dict) and block.get("source_revision"):
|
| 190 |
+
block["source_revision"] = new
|
| 191 |
+
incremental = manifest.get("incremental")
|
| 192 |
+
if isinstance(incremental, dict):
|
| 193 |
+
incremental["source_revision"] = new
|
| 194 |
+
fingerprint = str(incremental.get("source_fingerprint") or "")
|
| 195 |
+
if fingerprint.startswith(old + "|"):
|
| 196 |
+
incremental["source_fingerprint"] = new + fingerprint[len(old):]
|
| 197 |
+
return True
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def source_fingerprint(source_meta: Mapping[str, Any]) -> str:
|
| 201 |
+
"""Stable skip key: Hub SHA plus parquet digests when present."""
|
| 202 |
+
revision = str(source_meta.get("source_revision") or "")
|
| 203 |
+
laws = str(source_meta.get("laws_sha256") or "")
|
| 204 |
+
articles = str(source_meta.get("articles_sha256") or "")
|
| 205 |
+
return f"{revision}|{laws}|{articles}"
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
def source_fingerprint_from_manifest(manifest: Mapping[str, Any]) -> str:
|
| 209 |
+
revision = str(
|
| 210 |
+
manifest.get("dataset_revision")
|
| 211 |
+
or (manifest.get("source") or {}).get("source_revision")
|
| 212 |
+
or ""
|
| 213 |
+
)
|
| 214 |
+
sha = manifest.get("input_sha256") or {}
|
| 215 |
+
laws = str(sha.get("laws.parquet") or "")
|
| 216 |
+
articles = str(sha.get("articles.parquet") or "")
|
| 217 |
+
if not laws and not articles:
|
| 218 |
+
src = manifest.get("source") or {}
|
| 219 |
+
laws = str(src.get("laws_sha256") or "")
|
| 220 |
+
articles = str(src.get("articles_sha256") or "")
|
| 221 |
+
return f"{revision}|{laws}|{articles}"
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def _cid_set(frame: pd.DataFrame | None) -> set[str]:
|
| 225 |
+
if frame is None or frame.empty or "entry_cid" not in frame.columns:
|
| 226 |
+
return set()
|
| 227 |
+
return {str(x) for x in frame["entry_cid"].dropna().astype(str) if str(x).strip()}
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def diff_corpus(
|
| 231 |
+
prior: pd.DataFrame | None,
|
| 232 |
+
current: pd.DataFrame,
|
| 233 |
+
) -> CorpusDelta:
|
| 234 |
+
"""Diff two CID-keyed corpora. Same ``entry_cid`` implies same body."""
|
| 235 |
+
current_cids = _cid_set(current)
|
| 236 |
+
prior_cids = _cid_set(prior)
|
| 237 |
+
added = tuple(sorted(current_cids - prior_cids))
|
| 238 |
+
removed = tuple(sorted(prior_cids - current_cids))
|
| 239 |
+
unchanged = tuple(sorted(current_cids & prior_cids))
|
| 240 |
+
current_count = int(len(current_cids))
|
| 241 |
+
prior_count = int(len(prior_cids))
|
| 242 |
+
if current_count == 0:
|
| 243 |
+
ratio = 1.0 if prior_count else 0.0
|
| 244 |
+
else:
|
| 245 |
+
ratio = 1.0 - (len(unchanged) / float(current_count))
|
| 246 |
+
equivalent = prior_count == 0 or (not unchanged and current_count > 0)
|
| 247 |
+
return CorpusDelta(
|
| 248 |
+
added_cids=added,
|
| 249 |
+
removed_cids=removed,
|
| 250 |
+
unchanged_cids=unchanged,
|
| 251 |
+
prior_count=prior_count,
|
| 252 |
+
current_count=current_count,
|
| 253 |
+
changed_ratio=float(ratio),
|
| 254 |
+
equivalent_to_full=equivalent,
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def plan_rebuild(
|
| 259 |
+
*,
|
| 260 |
+
mode: BuildMode | str,
|
| 261 |
+
source_meta: Mapping[str, Any],
|
| 262 |
+
prior: PriorRelease | None,
|
| 263 |
+
current_corpus: pd.DataFrame | None = None,
|
| 264 |
+
force: bool = False,
|
| 265 |
+
rebuild_stub_vectors: bool = True,
|
| 266 |
+
compare_normalized: bool = False,
|
| 267 |
+
) -> RebuildPlan:
|
| 268 |
+
"""Decide skip / delta / full from source fingerprints and CID overlap."""
|
| 269 |
+
mode = BuildMode.coerce(mode)
|
| 270 |
+
revision = str(source_meta.get("source_revision") or "")
|
| 271 |
+
fingerprint = source_fingerprint(source_meta)
|
| 272 |
+
prior_revision = prior.source_revision if prior is not None else None
|
| 273 |
+
prior_fp = prior.fingerprint if prior is not None else None
|
| 274 |
+
|
| 275 |
+
if force or mode is BuildMode.FULL:
|
| 276 |
+
delta = None
|
| 277 |
+
if current_corpus is not None and prior is not None:
|
| 278 |
+
delta = diff_corpus(prior.corpus, current_corpus)
|
| 279 |
+
return RebuildPlan(
|
| 280 |
+
kind=RebuildKind.FULL_REBUILD,
|
| 281 |
+
mode=mode,
|
| 282 |
+
reason="operator forced full rebuild" if force else "build mode is full",
|
| 283 |
+
source_revision=revision,
|
| 284 |
+
prior_revision=prior_revision,
|
| 285 |
+
source_fingerprint=fingerprint,
|
| 286 |
+
prior_fingerprint=prior_fp,
|
| 287 |
+
delta=delta,
|
| 288 |
+
reuse_embeddings=False,
|
| 289 |
+
skip_build=False,
|
| 290 |
+
equivalent_to_full=True,
|
| 291 |
+
)
|
| 292 |
+
|
| 293 |
+
if prior is None:
|
| 294 |
+
return RebuildPlan(
|
| 295 |
+
kind=RebuildKind.FULL_REBUILD,
|
| 296 |
+
mode=mode,
|
| 297 |
+
reason="no prior release",
|
| 298 |
+
source_revision=revision,
|
| 299 |
+
prior_revision=None,
|
| 300 |
+
source_fingerprint=fingerprint,
|
| 301 |
+
prior_fingerprint=None,
|
| 302 |
+
delta=None,
|
| 303 |
+
reuse_embeddings=False,
|
| 304 |
+
skip_build=False,
|
| 305 |
+
equivalent_to_full=True,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
prior_vector_status = str(
|
| 309 |
+
((prior.manifest.get("vector") or {}) if prior.manifest else {}).get("status")
|
| 310 |
+
or ((prior.manifest.get("incremental") or {}).get("vectors") or {}).get("status")
|
| 311 |
+
or ""
|
| 312 |
+
).strip().lower()
|
| 313 |
+
stub_vectors = rebuild_stub_vectors and prior_vector_status in {
|
| 314 |
+
"stub",
|
| 315 |
+
"stub_missing_encoder",
|
| 316 |
+
"incomplete",
|
| 317 |
+
"partial",
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
fingerprint_match = bool(prior_fp == fingerprint and fingerprint.strip("|") and not stub_vectors)
|
| 321 |
+
if fingerprint_match and not (compare_normalized and current_corpus is not None):
|
| 322 |
+
return RebuildPlan(
|
| 323 |
+
kind=RebuildKind.UNCHANGED,
|
| 324 |
+
mode=mode,
|
| 325 |
+
reason="source revision and parquet digests match prior release",
|
| 326 |
+
source_revision=revision,
|
| 327 |
+
prior_revision=prior_revision,
|
| 328 |
+
source_fingerprint=fingerprint,
|
| 329 |
+
prior_fingerprint=prior_fp,
|
| 330 |
+
delta=CorpusDelta(
|
| 331 |
+
unchanged_cids=tuple(sorted(_cid_set(prior.corpus))),
|
| 332 |
+
prior_count=int(len(_cid_set(prior.corpus))),
|
| 333 |
+
current_count=int(len(_cid_set(prior.corpus))),
|
| 334 |
+
changed_ratio=0.0,
|
| 335 |
+
equivalent_to_full=False,
|
| 336 |
+
),
|
| 337 |
+
reuse_embeddings=True,
|
| 338 |
+
skip_build=True,
|
| 339 |
+
equivalent_to_full=False,
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
delta = None
|
| 343 |
+
if current_corpus is not None:
|
| 344 |
+
delta = diff_corpus(prior.corpus, current_corpus)
|
| 345 |
+
if delta.n_added == 0 and delta.n_removed == 0 and not stub_vectors:
|
| 346 |
+
return RebuildPlan(
|
| 347 |
+
kind=RebuildKind.UNCHANGED,
|
| 348 |
+
mode=mode,
|
| 349 |
+
reason="normalized entry_cids match the prior release",
|
| 350 |
+
source_revision=revision,
|
| 351 |
+
prior_revision=prior_revision,
|
| 352 |
+
source_fingerprint=fingerprint,
|
| 353 |
+
prior_fingerprint=prior_fp,
|
| 354 |
+
delta=delta,
|
| 355 |
+
reuse_embeddings=True,
|
| 356 |
+
skip_build=True,
|
| 357 |
+
equivalent_to_full=False,
|
| 358 |
+
)
|
| 359 |
+
if delta.equivalent_to_full:
|
| 360 |
+
return RebuildPlan(
|
| 361 |
+
kind=RebuildKind.FULL_REBUILD,
|
| 362 |
+
mode=mode,
|
| 363 |
+
reason="CID overlap is empty; delta equals a full rebuild",
|
| 364 |
+
source_revision=revision,
|
| 365 |
+
prior_revision=prior_revision,
|
| 366 |
+
source_fingerprint=fingerprint,
|
| 367 |
+
prior_fingerprint=prior_fp,
|
| 368 |
+
delta=delta,
|
| 369 |
+
reuse_embeddings=False,
|
| 370 |
+
skip_build=False,
|
| 371 |
+
equivalent_to_full=True,
|
| 372 |
+
)
|
| 373 |
+
|
| 374 |
+
reason = (
|
| 375 |
+
"source fingerprint matches but vectors are stub/incomplete; encode missing CIDs"
|
| 376 |
+
if stub_vectors and prior_fp == fingerprint
|
| 377 |
+
else "source changed; reuse embeddings for unchanged entry_cids"
|
| 378 |
+
)
|
| 379 |
+
return RebuildPlan(
|
| 380 |
+
kind=RebuildKind.DELTA_REFRESH,
|
| 381 |
+
mode=mode,
|
| 382 |
+
reason=reason,
|
| 383 |
+
source_revision=revision,
|
| 384 |
+
prior_revision=prior_revision,
|
| 385 |
+
source_fingerprint=fingerprint,
|
| 386 |
+
prior_fingerprint=prior_fp,
|
| 387 |
+
delta=delta,
|
| 388 |
+
reuse_embeddings=True,
|
| 389 |
+
skip_build=False,
|
| 390 |
+
equivalent_to_full=False,
|
| 391 |
+
)
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
def _read_sharded_parquet(directory: Path) -> pd.DataFrame | None:
|
| 395 |
+
if not directory.is_dir():
|
| 396 |
+
return None
|
| 397 |
+
parts = sorted(directory.glob("part-*.parquet"))
|
| 398 |
+
if not parts:
|
| 399 |
+
parts = sorted(p for p in directory.rglob("*.parquet") if p.is_file())
|
| 400 |
+
if not parts:
|
| 401 |
+
return None
|
| 402 |
+
frames = [pd.read_parquet(p) for p in parts]
|
| 403 |
+
return pd.concat(frames, ignore_index=True) if frames else None
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def load_release_manifest(release_dir: Path) -> dict[str, Any]:
|
| 407 |
+
path = Path(release_dir) / "manifest.json"
|
| 408 |
+
if not path.is_file():
|
| 409 |
+
return {}
|
| 410 |
+
try:
|
| 411 |
+
data = json.loads(path.read_text(encoding="utf-8"))
|
| 412 |
+
except Exception:
|
| 413 |
+
return {}
|
| 414 |
+
return data if isinstance(data, dict) else {}
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def load_release_corpus(release_dir: Path) -> pd.DataFrame | None:
|
| 418 |
+
release_dir = Path(release_dir)
|
| 419 |
+
corpus = _read_sharded_parquet(release_dir / "data" / "corpus")
|
| 420 |
+
if corpus is not None:
|
| 421 |
+
return corpus
|
| 422 |
+
checkpoint = release_dir / "corpus.parquet"
|
| 423 |
+
if checkpoint.is_file():
|
| 424 |
+
return pd.read_parquet(checkpoint)
|
| 425 |
+
return None
|
| 426 |
+
|
| 427 |
+
|
| 428 |
+
def embeddings_from_vector_table(frame: pd.DataFrame) -> dict[str, list[float]]:
|
| 429 |
+
out: dict[str, list[float]] = {}
|
| 430 |
+
if frame is None or frame.empty:
|
| 431 |
+
return out
|
| 432 |
+
if "entry_cid" not in frame.columns or "embedding" not in frame.columns:
|
| 433 |
+
return out
|
| 434 |
+
for rec in frame.itertuples(index=False):
|
| 435 |
+
cid = str(getattr(rec, "entry_cid", "") or "")
|
| 436 |
+
emb = getattr(rec, "embedding", None)
|
| 437 |
+
if not cid or emb is None:
|
| 438 |
+
continue
|
| 439 |
+
if isinstance(emb, float) and pd.isna(emb):
|
| 440 |
+
continue
|
| 441 |
+
try:
|
| 442 |
+
values = [float(x) for x in list(emb)]
|
| 443 |
+
except Exception:
|
| 444 |
+
continue
|
| 445 |
+
if not values:
|
| 446 |
+
continue
|
| 447 |
+
out[cid] = values
|
| 448 |
+
return out
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def load_release_vectors_by_cid(release_dir: Path) -> dict[str, list[float]]:
|
| 452 |
+
frame = _read_sharded_parquet(Path(release_dir) / "data" / "vectors")
|
| 453 |
+
if frame is None:
|
| 454 |
+
return {}
|
| 455 |
+
return embeddings_from_vector_table(frame)
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def load_prior_release(release_dir: Path | None) -> PriorRelease | None:
|
| 459 |
+
if release_dir is None:
|
| 460 |
+
return None
|
| 461 |
+
directory = Path(release_dir)
|
| 462 |
+
if not directory.is_dir():
|
| 463 |
+
return None
|
| 464 |
+
manifest = load_release_manifest(directory)
|
| 465 |
+
if not manifest and not (directory / "data").is_dir():
|
| 466 |
+
return None
|
| 467 |
+
return PriorRelease(
|
| 468 |
+
directory=directory,
|
| 469 |
+
manifest=manifest,
|
| 470 |
+
corpus=load_release_corpus(directory),
|
| 471 |
+
vectors_by_cid=None,
|
| 472 |
+
)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def load_embedding_cache(path: Path) -> dict[str, list[float]]:
|
| 476 |
+
if not path.is_file():
|
| 477 |
+
return {}
|
| 478 |
+
try:
|
| 479 |
+
frame = pd.read_parquet(path)
|
| 480 |
+
except Exception:
|
| 481 |
+
return {}
|
| 482 |
+
return embeddings_from_vector_table(frame)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def save_embedding_cache(
|
| 486 |
+
path: Path,
|
| 487 |
+
by_cid: Mapping[str, Iterable[float]],
|
| 488 |
+
*,
|
| 489 |
+
model_name: str,
|
| 490 |
+
dimension: int,
|
| 491 |
+
) -> None:
|
| 492 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 493 |
+
rows = [
|
| 494 |
+
{
|
| 495 |
+
"entry_cid": cid,
|
| 496 |
+
"embedding": list(vec),
|
| 497 |
+
"model_name": model_name,
|
| 498 |
+
"dimension": int(dimension),
|
| 499 |
+
}
|
| 500 |
+
for cid, vec in sorted(by_cid.items())
|
| 501 |
+
]
|
| 502 |
+
frame = pd.DataFrame(rows)
|
| 503 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 504 |
+
frame.to_parquet(tmp, index=False)
|
| 505 |
+
tmp.replace(path)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def merge_embedding_maps(
|
| 509 |
+
*maps: Mapping[str, list[float]] | None,
|
| 510 |
+
) -> dict[str, list[float]]:
|
| 511 |
+
merged: dict[str, list[float]] = {}
|
| 512 |
+
for mapping in maps:
|
| 513 |
+
if not mapping:
|
| 514 |
+
continue
|
| 515 |
+
merged.update(mapping)
|
| 516 |
+
return merged
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def fetch_hub_prior(
|
| 520 |
+
slug: str,
|
| 521 |
+
dest: Path | None = None,
|
| 522 |
+
*,
|
| 523 |
+
cache_root: Path | None = None,
|
| 524 |
+
) -> Path | None:
|
| 525 |
+
"""Download JusticeDAO corpus+vector shards to use as an incremental parent.
|
| 526 |
+
|
| 527 |
+
Missing Hub IR is not an error: first-time countries return ``None``.
|
| 528 |
+
"""
|
| 529 |
+
from huggingface_hub import snapshot_download
|
| 530 |
+
from huggingface_hub.errors import RepositoryNotFoundError
|
| 531 |
+
|
| 532 |
+
from .auth import operator_token, public_token
|
| 533 |
+
from .catalog import target_repo
|
| 534 |
+
|
| 535 |
+
root = Path(cache_root) if cache_root is not None else (
|
| 536 |
+
Path.home() / ".ipfs_datasets" / "country-laws-ir" / "cache" / "hub-ir"
|
| 537 |
+
)
|
| 538 |
+
dest = Path(dest) if dest is not None else (root / slug)
|
| 539 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 540 |
+
repo = target_repo(slug)
|
| 541 |
+
try:
|
| 542 |
+
snapshot_download(
|
| 543 |
+
repo_id=repo,
|
| 544 |
+
repo_type="dataset",
|
| 545 |
+
local_dir=str(dest),
|
| 546 |
+
allow_patterns=[
|
| 547 |
+
"manifest.json",
|
| 548 |
+
"data/vectors/**",
|
| 549 |
+
"data/corpus/**",
|
| 550 |
+
"indexes/vector_chunks.parquet",
|
| 551 |
+
],
|
| 552 |
+
token=operator_token() or public_token(),
|
| 553 |
+
)
|
| 554 |
+
except RepositoryNotFoundError:
|
| 555 |
+
return None
|
| 556 |
+
except Exception:
|
| 557 |
+
if not (dest / "manifest.json").is_file():
|
| 558 |
+
return None
|
| 559 |
+
raise
|
| 560 |
+
if not (dest / "manifest.json").is_file():
|
| 561 |
+
return None
|
| 562 |
+
return dest
|
scrapers_and_normalizers/ipfs_datasets_py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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Copy one code name onto sibling rows of the same source law.
|
| 2 |
+
|
| 3 |
+
A whole-line code name is inherited only when that law contains exactly one
|
| 4 |
+
such name. A title that already names a loi or an ordonnance is left as it
|
| 5 |
+
is. Hierarchy numbers are copied only into empty locator fields, and only
|
| 6 |
+
from a heading that appears once in that law. Statute text is not rewritten.
|
| 7 |
+
Nothing is invented, downloaded, or uploaded, and the assembled corpus is
|
| 8 |
+
only read.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import re
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Iterable, Mapping
|
| 17 |
+
|
| 18 |
+
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.national_directory import (
|
| 19 |
+
_HEADING_KIND,
|
| 20 |
+
_HEADING_LINE,
|
| 21 |
+
_ROMAN,
|
| 22 |
+
_TITLE_LOI,
|
| 23 |
+
_fold,
|
| 24 |
+
)
|
| 25 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.schema import LEGAL_RECORD_FIELDS
|
| 26 |
+
|
| 27 |
+
INHERIT_VERSION = "instrument-inherit/v1"
|
| 28 |
+
_MAX_ATOMS = 250_000
|
| 29 |
+
_NORMALIZER = "country-source-admit/v1"
|
| 30 |
+
_HEADING_KEYS = ("book", "title", "chapter", "part", "section")
|
| 31 |
+
_CODE_LINE = re.compile(
|
| 32 |
+
r"(?m)^CODE [A-ZÀÂÉÈÊËÎÏÔÙÛÜÇŒ][A-ZÀÂÉÈÊËÎÏÔÙÛÜÇŒ '&-]{4,}$"
|
| 33 |
+
)
|
| 34 |
+
_CODE_CAPTION = re.compile(r"(?i)^(code\b(?:[^\n>]{0,160}?))\s*>\s*article\b")
|
| 35 |
+
_CAPTION_TITLE = re.compile(
|
| 36 |
+
r"(?i)^(?:"
|
| 37 |
+
r"article|art\.?|section|sec\.?|livre|titre|titulo|título|chapitre|chapter|partie|part|title"
|
| 38 |
+
r")"
|
| 39 |
+
r"(?:[ \t]*[-–—.]?[ \t]*(?:"
|
| 40 |
+
r"[0-9]{1,4}(?:[.\-][0-9]{1,4})?[A-Za-z]?|[IVXLCDM]{1,12}|1er"
|
| 41 |
+
r"))?"
|
| 42 |
+
r"[ \t]*(?:[.:\-–—]+)?[ \t]*$"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def inheritance_plan(
|
| 47 |
+
rows: Iterable[Mapping[str, object]],
|
| 48 |
+
) -> dict[str, tuple[str, dict[str, str]]]:
|
| 49 |
+
"""Map each law id to its single code name and its unique headings."""
|
| 50 |
+
|
| 51 |
+
codes: dict[str, set[str]] = {}
|
| 52 |
+
headings: dict[str, dict[str, set[str]]] = {}
|
| 53 |
+
for row in rows:
|
| 54 |
+
law = row.get("law_id")
|
| 55 |
+
if not isinstance(law, str) or not law.strip():
|
| 56 |
+
continue
|
| 57 |
+
text = _source_text(row)
|
| 58 |
+
names = codes.setdefault(law, set())
|
| 59 |
+
names.update(_CODE_LINE.findall(text))
|
| 60 |
+
bucket = headings.setdefault(law, {})
|
| 61 |
+
for line in [item.strip() for item in text.splitlines() if item.strip()][:80]:
|
| 62 |
+
heading = _HEADING_LINE.match(line)
|
| 63 |
+
if heading is None:
|
| 64 |
+
continue
|
| 65 |
+
kind = _HEADING_KIND[heading.group(1).casefold()]
|
| 66 |
+
number = heading.group(2)
|
| 67 |
+
number = number if number.isdigit() else number.upper()
|
| 68 |
+
if not number.isdigit() and _ROMAN.fullmatch(number) is None:
|
| 69 |
+
continue
|
| 70 |
+
bucket.setdefault(kind, set()).add(number)
|
| 71 |
+
plan: dict[str, tuple[str, dict[str, str]]] = {}
|
| 72 |
+
for law, names in codes.items():
|
| 73 |
+
if len(names) != 1:
|
| 74 |
+
continue
|
| 75 |
+
sole = {
|
| 76 |
+
kind: next(iter(values))
|
| 77 |
+
for kind, values in headings.get(law, {}).items()
|
| 78 |
+
if len(values) == 1 and kind in _HEADING_KEYS
|
| 79 |
+
}
|
| 80 |
+
plan[law] = (next(iter(names)), sole)
|
| 81 |
+
return plan
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def replacement_title(title: str, text: str, law_code: str | None) -> str | None:
|
| 85 |
+
"""Return the code name to store as the record title, or None to keep it."""
|
| 86 |
+
|
| 87 |
+
if not law_code:
|
| 88 |
+
return None
|
| 89 |
+
label = title.strip()
|
| 90 |
+
if _names_other_instrument(label, text):
|
| 91 |
+
return None
|
| 92 |
+
if not label or _CAPTION_TITLE.fullmatch(label):
|
| 93 |
+
return law_code
|
| 94 |
+
caption = _CODE_CAPTION.match(label)
|
| 95 |
+
if caption and _fold(caption.group(1)) == _fold(law_code):
|
| 96 |
+
return law_code
|
| 97 |
+
return None
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def refine_atom(
|
| 101 |
+
record: Mapping[str, object],
|
| 102 |
+
*,
|
| 103 |
+
law_code: str | None,
|
| 104 |
+
headings: Mapping[str, str],
|
| 105 |
+
) -> dict[str, object]:
|
| 106 |
+
"""Fill a blank instrument title and empty hierarchy fields.
|
| 107 |
+
|
| 108 |
+
The returned text is the input text. A loi or ordonnance title is not
|
| 109 |
+
replaced by the parent code.
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
updated = dict(record)
|
| 113 |
+
text = updated.get("text") if isinstance(updated.get("text"), str) else ""
|
| 114 |
+
current = updated.get("title") if isinstance(updated.get("title"), str) else ""
|
| 115 |
+
new_title = replacement_title(current, text, law_code)
|
| 116 |
+
if new_title == current:
|
| 117 |
+
new_title = None
|
| 118 |
+
provenance, encoded = _copy_provenance(updated.get("provenance"))
|
| 119 |
+
added: dict[str, str] = {}
|
| 120 |
+
if provenance is not None and _accepts_hierarchy(current, text, law_code):
|
| 121 |
+
for key in _HEADING_KEYS:
|
| 122 |
+
value = headings.get(key, "")
|
| 123 |
+
if not value:
|
| 124 |
+
continue
|
| 125 |
+
already = provenance.get(key)
|
| 126 |
+
if isinstance(already, str) and already.strip():
|
| 127 |
+
continue
|
| 128 |
+
provenance[key] = value
|
| 129 |
+
added[key] = value
|
| 130 |
+
_note_jsonld(provenance, new_title, added)
|
| 131 |
+
elif provenance is not None and new_title:
|
| 132 |
+
_note_jsonld(provenance, new_title, {})
|
| 133 |
+
if new_title:
|
| 134 |
+
updated["title"] = new_title
|
| 135 |
+
if provenance is not None and (new_title or added):
|
| 136 |
+
updated["provenance"] = _store_provenance(provenance, encoded)
|
| 137 |
+
if updated.get("text") != record.get("text"):
|
| 138 |
+
raise ValueError("text")
|
| 139 |
+
return updated
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def refine_assembled_corpus(
|
| 143 |
+
source_paths: Iterable[Path | str],
|
| 144 |
+
assembled_dir: Path | str,
|
| 145 |
+
dest_dir: Path | str,
|
| 146 |
+
*,
|
| 147 |
+
source_dataset: str,
|
| 148 |
+
source_revision: str,
|
| 149 |
+
) -> dict[str, object]:
|
| 150 |
+
"""Write a sibling corpus whose titles carry a same-law code name.
|
| 151 |
+
|
| 152 |
+
``assembled_dir`` must already be a finished country fill. This function
|
| 153 |
+
does not modify it, does not download, and does not upload.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
assembled = Path(assembled_dir)
|
| 157 |
+
destination = Path(dest_dir)
|
| 158 |
+
_separate(assembled, destination)
|
| 159 |
+
if not _is_sha(source_revision):
|
| 160 |
+
raise ValueError("source_revision")
|
| 161 |
+
report = _assembled_report(assembled)
|
| 162 |
+
parts = sorted(assembled.glob("part-*.parquet"))
|
| 163 |
+
if not parts:
|
| 164 |
+
raise ValueError("assembled")
|
| 165 |
+
total = _row_count(parts)
|
| 166 |
+
if total < 1 or total > _MAX_ATOMS:
|
| 167 |
+
raise ValueError("assembled")
|
| 168 |
+
sources = [Path(path) for path in source_paths]
|
| 169 |
+
if not sources or any(not path.is_file() for path in sources):
|
| 170 |
+
raise ValueError("source")
|
| 171 |
+
rows = _read_source_rows(sources)
|
| 172 |
+
plan = inheritance_plan(rows)
|
| 173 |
+
if not plan:
|
| 174 |
+
return {
|
| 175 |
+
"version": INHERIT_VERSION,
|
| 176 |
+
"written": False,
|
| 177 |
+
"titles_filled": 0,
|
| 178 |
+
"headings_filled": 0,
|
| 179 |
+
"reason": "no_sole_code",
|
| 180 |
+
"normalizer_version": report.get("normalizer_version"),
|
| 181 |
+
}
|
| 182 |
+
law_by_cid = _law_by_entry_cid(
|
| 183 |
+
rows,
|
| 184 |
+
source_dataset=source_dataset,
|
| 185 |
+
source_revision=source_revision,
|
| 186 |
+
)
|
| 187 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 188 |
+
for stale in destination.glob("part-*.parquet"):
|
| 189 |
+
stale.unlink()
|
| 190 |
+
stale_report = destination / "refine_report.json"
|
| 191 |
+
if stale_report.exists():
|
| 192 |
+
stale_report.unlink()
|
| 193 |
+
titles = 0
|
| 194 |
+
heading_rows = 0
|
| 195 |
+
unmatched = 0
|
| 196 |
+
written: list[str] = []
|
| 197 |
+
for index, part in enumerate(parts):
|
| 198 |
+
refined: list[dict[str, object]] = []
|
| 199 |
+
for record in _iter_part(part):
|
| 200 |
+
cid = record.get("entry_cid") if isinstance(record.get("entry_cid"), str) else ""
|
| 201 |
+
law = law_by_cid.get(cid, "")
|
| 202 |
+
code, headings = plan.get(law, (None, {}))
|
| 203 |
+
if not law:
|
| 204 |
+
unmatched += 1
|
| 205 |
+
before_title = record.get("title")
|
| 206 |
+
before_provenance = record.get("provenance")
|
| 207 |
+
atom = refine_atom(record, law_code=code, headings=headings if code else {})
|
| 208 |
+
if atom.get("text") != record.get("text") or atom.get("entry_cid") != record.get("entry_cid"):
|
| 209 |
+
raise ValueError("text")
|
| 210 |
+
if atom.get("content_sha256") != record.get("content_sha256"):
|
| 211 |
+
raise ValueError("text")
|
| 212 |
+
if atom.get("title") != before_title:
|
| 213 |
+
titles += 1
|
| 214 |
+
if atom.get("provenance") != before_provenance and atom.get("title") == before_title:
|
| 215 |
+
heading_rows += 1
|
| 216 |
+
elif atom.get("provenance") != before_provenance and _gained_heading(before_provenance, atom.get("provenance")):
|
| 217 |
+
heading_rows += 1
|
| 218 |
+
refined.append(atom)
|
| 219 |
+
written.append(_write_part(destination, index, refined))
|
| 220 |
+
summary = {
|
| 221 |
+
"version": INHERIT_VERSION,
|
| 222 |
+
"written": True,
|
| 223 |
+
"source_dataset": source_dataset,
|
| 224 |
+
"source_revision": source_revision,
|
| 225 |
+
"atoms": total,
|
| 226 |
+
"titles_filled": titles,
|
| 227 |
+
"headings_filled": heading_rows,
|
| 228 |
+
"unmatched": unmatched,
|
| 229 |
+
"laws": len(plan),
|
| 230 |
+
"files": [Path(path).name for path in written],
|
| 231 |
+
"normalizer_version": report.get("normalizer_version"),
|
| 232 |
+
}
|
| 233 |
+
stale_report.write_text(json.dumps(summary, indent=2, sort_keys=True) + "\n", encoding="utf-8")
|
| 234 |
+
return summary
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _names_other_instrument(title: str, text: str) -> bool:
|
| 238 |
+
if _TITLE_LOI.match(title):
|
| 239 |
+
return True
|
| 240 |
+
for line in text.splitlines():
|
| 241 |
+
if line.strip():
|
| 242 |
+
return _TITLE_LOI.match(line.strip()) is not None
|
| 243 |
+
return False
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
def _accepts_hierarchy(title: str, text: str, law_code: str | None) -> bool:
|
| 247 |
+
if not law_code:
|
| 248 |
+
return False
|
| 249 |
+
if _fold(title) == _fold(law_code):
|
| 250 |
+
return True
|
| 251 |
+
return replacement_title(title, text, law_code) is not None
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def _source_text(row: Mapping[str, object]) -> str:
|
| 255 |
+
body = row.get("body")
|
| 256 |
+
if isinstance(body, str) and body:
|
| 257 |
+
return body
|
| 258 |
+
text = row.get("text")
|
| 259 |
+
return text if isinstance(text, str) else ""
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
def _copy_provenance(value: object) -> tuple[dict[str, object] | None, bool]:
|
| 263 |
+
if isinstance(value, str) and value.strip().startswith("{"):
|
| 264 |
+
try:
|
| 265 |
+
loaded = json.loads(value)
|
| 266 |
+
except json.JSONDecodeError:
|
| 267 |
+
return None, True
|
| 268 |
+
if isinstance(loaded, dict):
|
| 269 |
+
return loaded, True
|
| 270 |
+
return None, True
|
| 271 |
+
if isinstance(value, dict):
|
| 272 |
+
loaded = json.loads(json.dumps(value))
|
| 273 |
+
if isinstance(loaded, dict):
|
| 274 |
+
return loaded, False
|
| 275 |
+
return None, False
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _store_provenance(provenance: Mapping[str, object], encoded: bool) -> str | dict[str, object]:
|
| 279 |
+
if encoded:
|
| 280 |
+
return json.dumps(provenance, sort_keys=True, ensure_ascii=False)
|
| 281 |
+
copied = json.loads(json.dumps(provenance))
|
| 282 |
+
return copied if isinstance(copied, dict) else {}
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def _note_jsonld(provenance: dict[str, object], name: str | None, added: Mapping[str, str]) -> None:
|
| 286 |
+
document = provenance.get("jsonld")
|
| 287 |
+
if not isinstance(document, dict):
|
| 288 |
+
return
|
| 289 |
+
before = document.get("text")
|
| 290 |
+
if name:
|
| 291 |
+
document["name"] = name
|
| 292 |
+
if added:
|
| 293 |
+
properties = document.get("additionalProperty")
|
| 294 |
+
if not isinstance(properties, list):
|
| 295 |
+
properties = []
|
| 296 |
+
document["additionalProperty"] = properties
|
| 297 |
+
present = {
|
| 298 |
+
item.get("propertyID")
|
| 299 |
+
for item in properties
|
| 300 |
+
if isinstance(item, dict) and isinstance(item.get("propertyID"), str)
|
| 301 |
+
}
|
| 302 |
+
for key, value in added.items():
|
| 303 |
+
if key in present:
|
| 304 |
+
continue
|
| 305 |
+
properties.append({"@type": "PropertyValue", "propertyID": key, "value": value})
|
| 306 |
+
if document.get("text") != before:
|
| 307 |
+
raise ValueError("text")
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def _gained_heading(before: object, after: object) -> bool:
|
| 311 |
+
old, _old_encoded = _copy_provenance(before)
|
| 312 |
+
new, _new_encoded = _copy_provenance(after)
|
| 313 |
+
if old is None or new is None:
|
| 314 |
+
return False
|
| 315 |
+
for key in _HEADING_KEYS:
|
| 316 |
+
previous = old.get(key)
|
| 317 |
+
current = new.get(key)
|
| 318 |
+
if (not isinstance(previous, str) or not previous.strip()) and isinstance(current, str) and current.strip():
|
| 319 |
+
return True
|
| 320 |
+
return False
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _separate(assembled: Path, destination: Path) -> None:
|
| 324 |
+
source = assembled.resolve()
|
| 325 |
+
target = destination.resolve()
|
| 326 |
+
if source == target or target.is_relative_to(source) or source.is_relative_to(target):
|
| 327 |
+
raise ValueError("dest")
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def _assembled_report(assembled: Path) -> dict[str, object]:
|
| 331 |
+
path = assembled / "report.json"
|
| 332 |
+
if not path.is_file():
|
| 333 |
+
raise ValueError("assembled")
|
| 334 |
+
try:
|
| 335 |
+
loaded = json.loads(path.read_text(encoding="utf-8"))
|
| 336 |
+
except json.JSONDecodeError as exc:
|
| 337 |
+
raise ValueError("assembled") from exc
|
| 338 |
+
if not isinstance(loaded, dict):
|
| 339 |
+
raise ValueError("assembled")
|
| 340 |
+
if loaded.get("corpus_complete") is not True:
|
| 341 |
+
raise ValueError("assembled")
|
| 342 |
+
if loaded.get("normalizer_version") != _NORMALIZER:
|
| 343 |
+
raise ValueError("assembled")
|
| 344 |
+
return loaded
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
def _row_count(parts: list[Path]) -> int:
|
| 348 |
+
import pyarrow.parquet as pq
|
| 349 |
+
|
| 350 |
+
return sum(pq.ParquetFile(path).metadata.num_rows for path in parts)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def _read_source_rows(paths: list[Path]) -> list[dict[str, object]]:
|
| 354 |
+
import pyarrow.parquet as pq
|
| 355 |
+
|
| 356 |
+
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.admit import _FILL_COLUMNS
|
| 357 |
+
|
| 358 |
+
rows: list[dict[str, object]] = []
|
| 359 |
+
wanted = ("law_id", *_FILL_COLUMNS)
|
| 360 |
+
for path in paths:
|
| 361 |
+
present = [name for name in wanted if name in pq.read_schema(path).names]
|
| 362 |
+
if "law_id" not in present:
|
| 363 |
+
continue
|
| 364 |
+
parquet = pq.ParquetFile(path)
|
| 365 |
+
for batch in parquet.iter_batches(batch_size=256, columns=present):
|
| 366 |
+
rows.extend(batch.to_pylist())
|
| 367 |
+
return rows
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _law_by_entry_cid(
|
| 371 |
+
rows: Iterable[Mapping[str, object]],
|
| 372 |
+
*,
|
| 373 |
+
source_dataset: str,
|
| 374 |
+
source_revision: str,
|
| 375 |
+
) -> dict[str, str]:
|
| 376 |
+
from ipfs_datasets_py.processors.legal_scrapers.country_laws_ir.admit import (
|
| 377 |
+
_fill_row,
|
| 378 |
+
_is_sha,
|
| 379 |
+
admit_source_law,
|
| 380 |
+
)
|
| 381 |
+
|
| 382 |
+
found: dict[str, str] = {}
|
| 383 |
+
blocked: set[str] = set()
|
| 384 |
+
for row in rows:
|
| 385 |
+
law = row.get("law_id")
|
| 386 |
+
if not isinstance(law, str) or not law.strip():
|
| 387 |
+
continue
|
| 388 |
+
revision = row.get("source_revision")
|
| 389 |
+
pin = revision if _is_sha(revision) else source_revision
|
| 390 |
+
decision = admit_source_law(
|
| 391 |
+
_fill_row(row),
|
| 392 |
+
source_dataset=source_dataset,
|
| 393 |
+
source_revision=pin,
|
| 394 |
+
)
|
| 395 |
+
if not decision.admitted:
|
| 396 |
+
continue
|
| 397 |
+
for atom in decision.records:
|
| 398 |
+
cid = atom.get("entry_cid")
|
| 399 |
+
if not isinstance(cid, str) or not cid:
|
| 400 |
+
continue
|
| 401 |
+
previous = found.get(cid)
|
| 402 |
+
if previous is None:
|
| 403 |
+
found[cid] = law
|
| 404 |
+
elif previous != law:
|
| 405 |
+
blocked.add(cid)
|
| 406 |
+
for cid in blocked:
|
| 407 |
+
found.pop(cid, None)
|
| 408 |
+
return found
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _iter_part(path: Path) -> Iterable[dict[str, object]]:
|
| 412 |
+
import pyarrow.parquet as pq
|
| 413 |
+
|
| 414 |
+
parquet = pq.ParquetFile(path)
|
| 415 |
+
present = [name for name in LEGAL_RECORD_FIELDS if name in pq.read_schema(path).names]
|
| 416 |
+
for batch in parquet.iter_batches(batch_size=256, columns=present):
|
| 417 |
+
yield from batch.to_pylist()
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _write_part(destination: Path, index: int, records: list[dict[str, object]]) -> str:
|
| 421 |
+
import pyarrow as pa
|
| 422 |
+
import pyarrow.parquet as pq
|
| 423 |
+
|
| 424 |
+
schema = pa.schema([pa.field(name, pa.string()) for name in LEGAL_RECORD_FIELDS])
|
| 425 |
+
columns = {
|
| 426 |
+
name: [
|
| 427 |
+
record.get(name) if isinstance(record.get(name), str) else None
|
| 428 |
+
for record in records
|
| 429 |
+
]
|
| 430 |
+
for name in LEGAL_RECORD_FIELDS
|
| 431 |
+
}
|
| 432 |
+
part = destination / f"part-{index:06d}.parquet"
|
| 433 |
+
pq.write_table(pa.table(columns, schema=schema), part, compression="zstd")
|
| 434 |
+
return str(part)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
def _is_sha(value: object) -> bool:
|
| 438 |
+
return (
|
| 439 |
+
isinstance(value, str)
|
| 440 |
+
and len(value) == 40
|
| 441 |
+
and all(char in "0123456789abcdef" for char in value)
|
| 442 |
+
)
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/mem.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Process / host memory watchdog for large IR builds (DO OOM lesson).
|
| 2 |
+
|
| 3 |
+
Env overrides:
|
| 4 |
+
IR_MEM_WARN_GIB MemAvailable threshold to shed collectors (default 3.5)
|
| 5 |
+
IR_MEM_ABORT_GIB MemAvailable abort floor (default 2.5)
|
| 6 |
+
IR_RSS_ABORT_GIB process RSS hard abort (default 12.0)
|
| 7 |
+
IR_MEM_LOG_EVERY rows between mem logs when callers pass every_n (default 5000)
|
| 8 |
+
|
| 9 |
+
Admission may treat ZFS ARC above arc_c_min as schedulable. Warn, shed, and
|
| 10 |
+
MemAbort keep reading raw MemAvailable: the ARC does not shrink instantly,
|
| 11 |
+
and counting it in the abort floor lets a build grow until the OOM killer.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import os
|
| 17 |
+
import signal
|
| 18 |
+
from datetime import datetime, timezone
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from typing import Any, Callable
|
| 21 |
+
|
| 22 |
+
DEFAULT_WARN_GIB = 3.5
|
| 23 |
+
DEFAULT_ABORT_AVAIL_GIB = 2.5
|
| 24 |
+
DEFAULT_ABORT_RSS_GIB = 12.0
|
| 25 |
+
DEFAULT_LOG_EVERY = 5000
|
| 26 |
+
_GIB = 1024**3
|
| 27 |
+
ARCSTATS_PATH = Path("/proc/spl/kstat/zfs/arcstats")
|
| 28 |
+
|
| 29 |
+
# Prefer shedding zero-article / lean collectors first; protect AT+DK until last.
|
| 30 |
+
DEFAULT_SHED_ORDER: list[tuple[str, tuple[str, ...]]] = [
|
| 31 |
+
("mm", ("collect_mm", "run_collector_cc.sh collect_mm")),
|
| 32 |
+
("th", ("collect_th", "run_collector_cc.sh collect_th")),
|
| 33 |
+
("is-reg", ("collect_is", "is-reg", "run_collector_cc.sh collect_is")),
|
| 34 |
+
("lt", ("collect_lt", "run_collector_cc.sh collect_lt")),
|
| 35 |
+
("kw", ("collect_kw", "run_collector_cc.sh collect_kw")),
|
| 36 |
+
("mt", ("collect_mt", "run_collector_cc.sh collect_mt")),
|
| 37 |
+
("dk", ("collect_dk", "run_collector_cc.sh collect_dk")),
|
| 38 |
+
("at", ("collect_at", "run_collector_cc.sh collect_at", "at_deepen")),
|
| 39 |
+
]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class MemAbort(RuntimeError):
|
| 43 |
+
"""Raised when MemAvailable or RSS crosses hard abort thresholds."""
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _env_float(name: str, default: float) -> float:
|
| 47 |
+
raw = os.environ.get(name)
|
| 48 |
+
if raw is None or raw == "":
|
| 49 |
+
return default
|
| 50 |
+
try:
|
| 51 |
+
return float(raw)
|
| 52 |
+
except ValueError:
|
| 53 |
+
return default
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def warn_gib() -> float:
|
| 57 |
+
return _env_float("IR_MEM_WARN_GIB", DEFAULT_WARN_GIB)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def abort_avail_gib() -> float:
|
| 61 |
+
return _env_float("IR_MEM_ABORT_GIB", DEFAULT_ABORT_AVAIL_GIB)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def abort_rss_gib() -> float:
|
| 65 |
+
return _env_float("IR_RSS_ABORT_GIB", DEFAULT_ABORT_RSS_GIB)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def log_every() -> int:
|
| 69 |
+
try:
|
| 70 |
+
return max(1, int(os.environ.get("IR_MEM_LOG_EVERY", DEFAULT_LOG_EVERY)))
|
| 71 |
+
except ValueError:
|
| 72 |
+
return DEFAULT_LOG_EVERY
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def mem_available_gib() -> float:
|
| 76 |
+
"""Raw Linux MemAvailable, in GiB.
|
| 77 |
+
|
| 78 |
+
This figure does not include the ZFS ARC. Keep using it for warn, shed,
|
| 79 |
+
and MemAbort. Scheduling headroom is ``schedulable_gib``.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
try:
|
| 83 |
+
for line in Path("/proc/meminfo").read_text().splitlines():
|
| 84 |
+
if line.startswith("MemAvailable:"):
|
| 85 |
+
return int(line.split()[1]) / 1024 / 1024
|
| 86 |
+
except Exception:
|
| 87 |
+
pass
|
| 88 |
+
return -1.0
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def evictable_arc_bytes(size: int, c_min: int) -> int:
|
| 92 |
+
"""ARC bytes the kernel can reclaim by shrinking toward ``c_min``."""
|
| 93 |
+
|
| 94 |
+
return max(0, int(size) - int(c_min))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def parse_arc_kstat(text: str) -> dict[str, int]:
|
| 98 |
+
"""Parse ``/proc/spl/kstat/zfs/arcstats``. The value is the third field."""
|
| 99 |
+
|
| 100 |
+
stats: dict[str, int] = {}
|
| 101 |
+
for line in text.splitlines():
|
| 102 |
+
parts = line.split()
|
| 103 |
+
if len(parts) < 3 or parts[0] == "name":
|
| 104 |
+
continue
|
| 105 |
+
try:
|
| 106 |
+
stats[parts[0]] = int(parts[2])
|
| 107 |
+
except ValueError:
|
| 108 |
+
continue
|
| 109 |
+
return stats
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def evictable_arc_gib(stats_text: str | None = None) -> float:
|
| 113 |
+
"""GiB of ZFS ARC above ``c_min``. Zero when arcstats is missing."""
|
| 114 |
+
|
| 115 |
+
if stats_text is None:
|
| 116 |
+
try:
|
| 117 |
+
stats_text = ARCSTATS_PATH.read_text()
|
| 118 |
+
except OSError:
|
| 119 |
+
return 0.0
|
| 120 |
+
stats = parse_arc_kstat(stats_text)
|
| 121 |
+
if "size" not in stats or "c_min" not in stats:
|
| 122 |
+
return 0.0
|
| 123 |
+
return evictable_arc_bytes(stats["size"], stats["c_min"]) / _GIB
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def schedulable_gib(
|
| 127 |
+
available_gib: float | None = None,
|
| 128 |
+
*,
|
| 129 |
+
arc_gib: float | None = None,
|
| 130 |
+
) -> float:
|
| 131 |
+
"""MemAvailable plus ZFS ARC that can shrink to ``c_min``.
|
| 132 |
+
|
| 133 |
+
Returns -1 when MemAvailable itself cannot be read. Does not replace
|
| 134 |
+
``mem_available_gib`` for the abort floor.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
avail = mem_available_gib() if available_gib is None else float(available_gib)
|
| 138 |
+
if avail < 0:
|
| 139 |
+
return -1.0
|
| 140 |
+
extra = evictable_arc_gib() if arc_gib is None else max(0.0, float(arc_gib))
|
| 141 |
+
return avail + extra
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def rss_gib(pid: int | None = None) -> float:
|
| 145 |
+
path = Path(f"/proc/{pid or 'self'}/status")
|
| 146 |
+
try:
|
| 147 |
+
for line in path.read_text().splitlines():
|
| 148 |
+
if line.startswith("VmRSS:"):
|
| 149 |
+
return int(line.split()[1]) / 1024 / 1024
|
| 150 |
+
except Exception:
|
| 151 |
+
pass
|
| 152 |
+
return -1.0
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def snapshot(stage: str = "") -> dict[str, Any]:
|
| 156 |
+
return {
|
| 157 |
+
"stage": stage,
|
| 158 |
+
"mem_avail_gib": round(mem_available_gib(), 3),
|
| 159 |
+
"rss_gib": round(rss_gib(), 3),
|
| 160 |
+
"ts": datetime.now(timezone.utc).isoformat(),
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def log_mem(stage: str, log: Callable[[str], None] | None = None) -> dict[str, Any]:
|
| 165 |
+
snap = snapshot(stage)
|
| 166 |
+
msg = (
|
| 167 |
+
f"mem stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G "
|
| 168 |
+
f"RSS={snap['rss_gib']:.2f}G"
|
| 169 |
+
)
|
| 170 |
+
if log is not None:
|
| 171 |
+
log(msg)
|
| 172 |
+
else:
|
| 173 |
+
print(f"[{snap['ts']}] {msg}", flush=True)
|
| 174 |
+
return snap
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def discover_pids(*patterns: str) -> list[int]:
|
| 178 |
+
found: list[int] = []
|
| 179 |
+
try:
|
| 180 |
+
for proc in Path("/proc").iterdir():
|
| 181 |
+
if not proc.name.isdigit():
|
| 182 |
+
continue
|
| 183 |
+
try:
|
| 184 |
+
cmd = (proc / "cmdline").read_bytes().replace(b"\x00", b" ").decode(
|
| 185 |
+
"utf-8", "ignore"
|
| 186 |
+
)
|
| 187 |
+
except Exception:
|
| 188 |
+
continue
|
| 189 |
+
if any(p in cmd for p in patterns):
|
| 190 |
+
found.append(int(proc.name))
|
| 191 |
+
except Exception:
|
| 192 |
+
pass
|
| 193 |
+
return found
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def shed_collectors(
|
| 197 |
+
stage: str,
|
| 198 |
+
*,
|
| 199 |
+
warn: float | None = None,
|
| 200 |
+
protect: frozenset[str] | None = None,
|
| 201 |
+
log: Callable[[str], None] | None = None,
|
| 202 |
+
notes: list[dict[str, Any]] | None = None,
|
| 203 |
+
) -> list[dict[str, Any]]:
|
| 204 |
+
"""SIGTERM lean collectors when MemAvailable < warn. Protect AT/DK by default until last."""
|
| 205 |
+
warn = warn_gib() if warn is None else warn
|
| 206 |
+
protect = protect if protect is not None else frozenset({"at", "dk"})
|
| 207 |
+
g = mem_available_gib()
|
| 208 |
+
out: list[dict[str, Any]] = []
|
| 209 |
+
if g < 0 or g >= warn:
|
| 210 |
+
return out
|
| 211 |
+
# First pass: non-protected; second pass: protected if still under warn.
|
| 212 |
+
for pass_protected in (False, True):
|
| 213 |
+
for name, pats in DEFAULT_SHED_ORDER:
|
| 214 |
+
if (name in protect) != pass_protected:
|
| 215 |
+
continue
|
| 216 |
+
pids = discover_pids(*pats)
|
| 217 |
+
for pid in pids:
|
| 218 |
+
try:
|
| 219 |
+
os.kill(pid, 0)
|
| 220 |
+
except ProcessLookupError:
|
| 221 |
+
continue
|
| 222 |
+
except PermissionError:
|
| 223 |
+
continue
|
| 224 |
+
try:
|
| 225 |
+
os.kill(pid, signal.SIGTERM)
|
| 226 |
+
note = {
|
| 227 |
+
"stage": stage,
|
| 228 |
+
"name": name,
|
| 229 |
+
"pid": pid,
|
| 230 |
+
"mem_before": round(g, 2),
|
| 231 |
+
"protected_pass": pass_protected,
|
| 232 |
+
}
|
| 233 |
+
out.append(note)
|
| 234 |
+
if notes is not None:
|
| 235 |
+
notes.append(note)
|
| 236 |
+
msg = f"SIGTERM collector {name} pid={pid} mem={g:.2f}G stage={stage}"
|
| 237 |
+
if log:
|
| 238 |
+
log(msg)
|
| 239 |
+
else:
|
| 240 |
+
print(msg, flush=True)
|
| 241 |
+
except ProcessLookupError:
|
| 242 |
+
pass
|
| 243 |
+
except Exception as exc:
|
| 244 |
+
msg = f"SIGTERM failed {name} pid={pid}: {exc}"
|
| 245 |
+
if log:
|
| 246 |
+
log(msg)
|
| 247 |
+
else:
|
| 248 |
+
print(msg, flush=True)
|
| 249 |
+
g = mem_available_gib()
|
| 250 |
+
if g >= warn:
|
| 251 |
+
return out
|
| 252 |
+
return out
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def checkpoint(
|
| 256 |
+
stage: str,
|
| 257 |
+
*,
|
| 258 |
+
row: int | None = None,
|
| 259 |
+
every_n: int | None = None,
|
| 260 |
+
shed: bool = True,
|
| 261 |
+
abort: bool = True,
|
| 262 |
+
log: Callable[[str], None] | None = None,
|
| 263 |
+
notes: list[dict[str, Any]] | None = None,
|
| 264 |
+
) -> dict[str, Any]:
|
| 265 |
+
"""Periodic mem log + optional shed + hard abort.
|
| 266 |
+
|
| 267 |
+
Call every N rows with ``row`` set; always logs when row is None.
|
| 268 |
+
"""
|
| 269 |
+
every = every_n if every_n is not None else log_every()
|
| 270 |
+
if row is not None and row != 0 and row % every != 0:
|
| 271 |
+
# Still enforce hard abort cheaply on every call.
|
| 272 |
+
rss = rss_gib()
|
| 273 |
+
avail = mem_available_gib()
|
| 274 |
+
if abort and rss >= abort_rss_gib():
|
| 275 |
+
raise MemAbort(f"RSS_ABORT stage={stage} rss={rss:.2f}G > {abort_rss_gib()}G")
|
| 276 |
+
if abort and 0 <= avail < abort_avail_gib():
|
| 277 |
+
if shed:
|
| 278 |
+
shed_collectors(stage, log=log, notes=notes)
|
| 279 |
+
avail = mem_available_gib()
|
| 280 |
+
if 0 <= avail < abort_avail_gib():
|
| 281 |
+
raise MemAbort(
|
| 282 |
+
f"MEM_ABORT stage={stage} MemAvailable={avail:.2f}G < {abort_avail_gib()}G"
|
| 283 |
+
)
|
| 284 |
+
return snapshot(stage)
|
| 285 |
+
|
| 286 |
+
snap = log_mem(stage if row is None else f"{stage}@{row}", log=log)
|
| 287 |
+
if shed and 0 <= snap["mem_avail_gib"] < warn_gib():
|
| 288 |
+
shed_collectors(stage, log=log, notes=notes)
|
| 289 |
+
snap = log_mem(f"{stage}_after_shed", log=log)
|
| 290 |
+
gc.collect()
|
| 291 |
+
if abort:
|
| 292 |
+
if snap["rss_gib"] >= abort_rss_gib():
|
| 293 |
+
raise MemAbort(
|
| 294 |
+
f"RSS_ABORT stage={stage} rss={snap['rss_gib']:.2f}G > {abort_rss_gib()}G"
|
| 295 |
+
)
|
| 296 |
+
if 0 <= snap["mem_avail_gib"] < abort_avail_gib():
|
| 297 |
+
raise MemAbort(
|
| 298 |
+
f"MEM_ABORT stage={stage} MemAvailable={snap['mem_avail_gib']:.2f}G "
|
| 299 |
+
f"< {abort_avail_gib()}G"
|
| 300 |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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Directory of one nation's assembled laws.
|
| 2 |
+
|
| 3 |
+
Reads legal-record rows after a corpus is assembled. Each row that fits the
|
| 4 |
+
national schema becomes one code listing, with a Bluebook citation where a
|
| 5 |
+
published form is known and a Bluebook analog otherwise. A code name or a
|
| 6 |
+
heading that is still in the text is filed when the record title is only an
|
| 7 |
+
article caption. Rows that do not fit, provisions that cannot be placed, and
|
| 8 |
+
dense numbering holes are written beside the listing. This module does not
|
| 9 |
+
rewrite statute text, does not download, and does not upload.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import re
|
| 16 |
+
import unicodedata
|
| 17 |
+
from dataclasses import dataclass, field
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Iterable, Mapping
|
| 20 |
+
|
| 21 |
+
from ipfs_datasets_py.processors.legal_data.iso_slug_crosswalk import (
|
| 22 |
+
_DEFAULT_NAMES,
|
| 23 |
+
resolve_jurisdiction,
|
| 24 |
+
)
|
| 25 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.schema import (
|
| 26 |
+
LEGAL_RECORD_FIELDS,
|
| 27 |
+
_INSTRUMENTS,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
DIRECTORY_VERSION = "national-directory/v1"
|
| 31 |
+
_SORT_LIMIT = 250_000
|
| 32 |
+
_GAP_MIN_PRESENT = 4
|
| 33 |
+
_GAP_MAX_SPAN = 400
|
| 34 |
+
_GAP_MIN_DENSITY = 0.75
|
| 35 |
+
_LOCATORS = ("title", "chapter", "part", "article", "section")
|
| 36 |
+
_NUMBER = re.compile(r"^[0-9]{1,5}$")
|
| 37 |
+
_SHA = re.compile(r"^[0-9a-f]{64}$")
|
| 38 |
+
_LABELS = {
|
| 39 |
+
"US": "United States",
|
| 40 |
+
"EU": "European Union",
|
| 41 |
+
"GB": "United Kingdom",
|
| 42 |
+
}
|
| 43 |
+
# Published code abbreviations. Anything else stays an analog.
|
| 44 |
+
_CODE_FORMS: tuple[tuple[str, str, str, str], ...] = (
|
| 45 |
+
("US", "united states code", "U.S.C.", "section"),
|
| 46 |
+
("US", "code of federal regulations", "C.F.R.", "section"),
|
| 47 |
+
("FR", "code civil", "C. civ.", "article"),
|
| 48 |
+
("FR", "code penal", "C. pén.", "article"),
|
| 49 |
+
("FR", "code de commerce", "C. com.", "article"),
|
| 50 |
+
("DE", "burgerliches gesetzbuch", "BGB", "section"),
|
| 51 |
+
("DE", "strafgesetzbuch", "StGB", "section"),
|
| 52 |
+
("DE", "handelsgesetzbuch", "HGB", "section"),
|
| 53 |
+
("DE", "grundgesetz", "GG", "article"),
|
| 54 |
+
)
|
| 55 |
+
_TITLE_PREFIX = frozenset({"U.S.C.", "C.F.R."})
|
| 56 |
+
_EU_ACT = re.compile(
|
| 57 |
+
r"(?i)\b(regulation|directive|decision)\b[^\n]{0,80}?\b((?:\(EU\)\s*)?\d{4}/\d+)\b"
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
class DirectoryEntry:
|
| 63 |
+
jurisdiction: str
|
| 64 |
+
instrument: str
|
| 65 |
+
title: str
|
| 66 |
+
book: str
|
| 67 |
+
chapter: str
|
| 68 |
+
part: str
|
| 69 |
+
article: str
|
| 70 |
+
section: str
|
| 71 |
+
citation: str
|
| 72 |
+
citation_form: str
|
| 73 |
+
path: str
|
| 74 |
+
entry_cid: str
|
| 75 |
+
|
| 76 |
+
def as_dict(self) -> dict[str, str]:
|
| 77 |
+
return {
|
| 78 |
+
"jurisdiction": self.jurisdiction,
|
| 79 |
+
"instrument": self.instrument,
|
| 80 |
+
"title": self.title,
|
| 81 |
+
"book": self.book,
|
| 82 |
+
"chapter": self.chapter,
|
| 83 |
+
"part": self.part,
|
| 84 |
+
"article": self.article,
|
| 85 |
+
"section": self.section,
|
| 86 |
+
"citation": self.citation,
|
| 87 |
+
"citation_form": self.citation_form,
|
| 88 |
+
"path": self.path,
|
| 89 |
+
"entry_cid": self.entry_cid,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
@dataclass
|
| 94 |
+
class DirectoryIndex:
|
| 95 |
+
entries: list[DirectoryEntry] = field(default_factory=list)
|
| 96 |
+
schema_problems: list[dict[str, str]] = field(default_factory=list)
|
| 97 |
+
unplaced: list[dict[str, str]] = field(default_factory=list)
|
| 98 |
+
gaps: list[dict[str, object]] = field(default_factory=list)
|
| 99 |
+
duplicates: int = 0
|
| 100 |
+
weak_instrument: int = 0
|
| 101 |
+
|
| 102 |
+
def report(self) -> dict[str, object]:
|
| 103 |
+
bluebook = sum(1 for entry in self.entries if entry.citation_form == "bluebook")
|
| 104 |
+
return {
|
| 105 |
+
"version": DIRECTORY_VERSION,
|
| 106 |
+
"listed": len(self.entries),
|
| 107 |
+
"bluebook": bluebook,
|
| 108 |
+
"bluebook_analog": len(self.entries) - bluebook,
|
| 109 |
+
"schema_problems": len(self.schema_problems),
|
| 110 |
+
"unplaced": len(self.unplaced),
|
| 111 |
+
"gaps": len(self.gaps),
|
| 112 |
+
"duplicates": self.duplicates,
|
| 113 |
+
"weak_instrument": self.weak_instrument,
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def index_national_laws(records: Iterable[Mapping[str, object]]) -> DirectoryIndex:
|
| 118 |
+
"""File assembled legal records into a national code listing."""
|
| 119 |
+
|
| 120 |
+
index = DirectoryIndex()
|
| 121 |
+
seen: set[tuple[str, ...]] = set()
|
| 122 |
+
numbers: dict[tuple[str, ...], tuple[str, set[int]]] = {}
|
| 123 |
+
for record in records:
|
| 124 |
+
problems = _schema_problems(record)
|
| 125 |
+
if problems:
|
| 126 |
+
index.schema_problems.extend(problems)
|
| 127 |
+
continue
|
| 128 |
+
entry = _entry(record)
|
| 129 |
+
if entry is None:
|
| 130 |
+
index.unplaced.append(_unplaced(record))
|
| 131 |
+
continue
|
| 132 |
+
key = _entry_key(entry)
|
| 133 |
+
if key in seen:
|
| 134 |
+
index.duplicates += 1
|
| 135 |
+
else:
|
| 136 |
+
seen.add(key)
|
| 137 |
+
index.entries.append(entry)
|
| 138 |
+
if _weak_instrument(entry):
|
| 139 |
+
index.weak_instrument += 1
|
| 140 |
+
_note_number(numbers, entry)
|
| 141 |
+
index.gaps.extend(_gaps(numbers))
|
| 142 |
+
index.entries.sort(key=_sort_key)
|
| 143 |
+
return index
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def write_national_directory(source_dir: Path | str, dest_dir: Path | str) -> dict[str, object]:
|
| 147 |
+
"""Write the listing, schema problems, unplaced rows, and numbering gaps.
|
| 148 |
+
|
| 149 |
+
``source_dir`` is one finished country folder of legal-record parts.
|
| 150 |
+
The corpus files are only read.
|
| 151 |
+
"""
|
| 152 |
+
|
| 153 |
+
source = Path(source_dir)
|
| 154 |
+
destination = Path(dest_dir)
|
| 155 |
+
parts = sorted(source.glob("part-*.parquet"))
|
| 156 |
+
if not parts:
|
| 157 |
+
raise ValueError("source")
|
| 158 |
+
destination.mkdir(parents=True, exist_ok=True)
|
| 159 |
+
rows = _parquet_rows(parts)
|
| 160 |
+
total = sum(count for _part, count in rows)
|
| 161 |
+
if total > _SORT_LIMIT:
|
| 162 |
+
report = _write_streaming(parts, destination, total)
|
| 163 |
+
else:
|
| 164 |
+
records = _iter_records(parts)
|
| 165 |
+
index = index_national_laws(records)
|
| 166 |
+
report = index.report()
|
| 167 |
+
report["order"] = "code"
|
| 168 |
+
_write_jsonl(destination / "directory.jsonl", (entry.as_dict() for entry in index.entries))
|
| 169 |
+
_write_jsonl(destination / "schema_problems.jsonl", index.schema_problems)
|
| 170 |
+
_write_jsonl(destination / "unplaced.jsonl", index.unplaced)
|
| 171 |
+
_write_jsonl(destination / "gaps.jsonl", index.gaps)
|
| 172 |
+
report["source_dir"] = str(source)
|
| 173 |
+
report["source_rows"] = total
|
| 174 |
+
report["files"] = [path.name for path in parts]
|
| 175 |
+
(destination / "report.json").write_text(
|
| 176 |
+
json.dumps(report, indent=2, sort_keys=True) + "\n",
|
| 177 |
+
encoding="utf-8",
|
| 178 |
+
)
|
| 179 |
+
return report
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def _write_streaming(parts: list[Path], destination: Path, total: int) -> dict[str, object]:
|
| 183 |
+
"""Stream a corpus that is too large to sort in memory."""
|
| 184 |
+
|
| 185 |
+
seen: set[tuple[str, ...]] = set()
|
| 186 |
+
numbers: dict[tuple[str, ...], tuple[str, set[int]]] = {}
|
| 187 |
+
listed = 0
|
| 188 |
+
bluebook = 0
|
| 189 |
+
duplicates = 0
|
| 190 |
+
weak = 0
|
| 191 |
+
schema_count = 0
|
| 192 |
+
unplaced_count = 0
|
| 193 |
+
with (destination / "directory.jsonl").open("w", encoding="utf-8") as directory, (
|
| 194 |
+
destination / "schema_problems.jsonl"
|
| 195 |
+
).open("w", encoding="utf-8") as problems, (destination / "unplaced.jsonl").open(
|
| 196 |
+
"w", encoding="utf-8"
|
| 197 |
+
) as unplaced:
|
| 198 |
+
for record in _iter_records(parts):
|
| 199 |
+
found = _schema_problems(record)
|
| 200 |
+
if found:
|
| 201 |
+
schema_count += len(found)
|
| 202 |
+
for problem in found:
|
| 203 |
+
problems.write(json.dumps(problem, sort_keys=True, ensure_ascii=False) + "\n")
|
| 204 |
+
continue
|
| 205 |
+
entry = _entry(record)
|
| 206 |
+
if entry is None:
|
| 207 |
+
unplaced_count += 1
|
| 208 |
+
unplaced.write(json.dumps(_unplaced(record), sort_keys=True, ensure_ascii=False) + "\n")
|
| 209 |
+
continue
|
| 210 |
+
key = _entry_key(entry)
|
| 211 |
+
if key in seen:
|
| 212 |
+
duplicates += 1
|
| 213 |
+
continue
|
| 214 |
+
seen.add(key)
|
| 215 |
+
listed += 1
|
| 216 |
+
if _weak_instrument(entry):
|
| 217 |
+
weak += 1
|
| 218 |
+
if entry.citation_form == "bluebook":
|
| 219 |
+
bluebook += 1
|
| 220 |
+
_note_number(numbers, entry)
|
| 221 |
+
directory.write(json.dumps(entry.as_dict(), sort_keys=True, ensure_ascii=False) + "\n")
|
| 222 |
+
gaps = _gaps(numbers)
|
| 223 |
+
_write_jsonl(destination / "gaps.jsonl", gaps)
|
| 224 |
+
return {
|
| 225 |
+
"version": DIRECTORY_VERSION,
|
| 226 |
+
"listed": listed,
|
| 227 |
+
"bluebook": bluebook,
|
| 228 |
+
"bluebook_analog": listed - bluebook,
|
| 229 |
+
"schema_problems": schema_count,
|
| 230 |
+
"unplaced": unplaced_count,
|
| 231 |
+
"gaps": len(gaps),
|
| 232 |
+
"duplicates": duplicates,
|
| 233 |
+
"weak_instrument": weak,
|
| 234 |
+
"order": "source",
|
| 235 |
+
"source_rows": total,
|
| 236 |
+
}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _schema_problems(record: Mapping[str, object]) -> list[dict[str, str]]:
|
| 240 |
+
cid = _text(record.get("entry_cid")) or _text(record.get("title")) or ""
|
| 241 |
+
problems: list[dict[str, str]] = []
|
| 242 |
+
|
| 243 |
+
def add(reason: str) -> None:
|
| 244 |
+
problems.append({"entry_cid": cid, "reason": reason})
|
| 245 |
+
|
| 246 |
+
for name in ("jurisdiction", "admin_level", "instrument_type", "text", "provenance"):
|
| 247 |
+
if name not in record:
|
| 248 |
+
add("missing_" + name)
|
| 249 |
+
if problems:
|
| 250 |
+
return problems
|
| 251 |
+
text = record.get("text")
|
| 252 |
+
if not isinstance(text, str) or not text.strip():
|
| 253 |
+
add("empty_text")
|
| 254 |
+
admin = _text(record.get("admin_level"))
|
| 255 |
+
if admin != "country":
|
| 256 |
+
add("not_national")
|
| 257 |
+
instrument = _text(record.get("instrument_type"))
|
| 258 |
+
if instrument not in _INSTRUMENTS:
|
| 259 |
+
add("bad_instrument")
|
| 260 |
+
resolved = resolve_jurisdiction(_text(record.get("jurisdiction")))
|
| 261 |
+
if resolved is None or resolved.admin_level not in {"country", "supranational"}:
|
| 262 |
+
add("bad_jurisdiction")
|
| 263 |
+
digest = record.get("content_sha256")
|
| 264 |
+
if not isinstance(digest, str) or _SHA.fullmatch(digest) is None:
|
| 265 |
+
add("bad_hash")
|
| 266 |
+
provenance = _provenance(record.get("provenance"))
|
| 267 |
+
if provenance is None:
|
| 268 |
+
add("bad_provenance")
|
| 269 |
+
elif provenance.get("document_role") != "law":
|
| 270 |
+
add("not_law")
|
| 271 |
+
return problems
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
_HEADING_LINE = re.compile(
|
| 275 |
+
r"(?i)^(partie|livre|titre|titulo|título|chapitre|chapter|section|part)\s*-\s*"
|
| 276 |
+
r"(?:partie|livre|titre|chapitre|chapter|section|part(?:ie)?)?\s*"
|
| 277 |
+
r"([0-9]{1,4}|[IVXLCDM]{1,12})\b"
|
| 278 |
+
)
|
| 279 |
+
_ARTICLE_DOT = re.compile(
|
| 280 |
+
r"(?i)^(?:article|art\.?)?\s*"
|
| 281 |
+
r"((?:[A-Z]-)?[0-9]{1,4}(?:\s*[-.]\s*[0-9]{1,4})?)\s*\.-\s*$"
|
| 282 |
+
)
|
| 283 |
+
_ARTICLE_ONLY = re.compile(
|
| 284 |
+
r"(?i)^(?:article|art\.?)\s+"
|
| 285 |
+
r"((?:[A-Z]-)?[0-9]{1,4}(?:-[0-9]{1,4})?[A-Za-z]?)\s*[.:]?\s*$"
|
| 286 |
+
)
|
| 287 |
+
_SECTION_ONLY = re.compile(r"(?i)^(?:section|sec\.?)\s+([0-9]{1,4}[A-Za-z]?)\s*[.:]?\s*$")
|
| 288 |
+
_TITLE_SECTION = re.compile(r"(?i)^(?:section|sec\.?)\s+([0-9]{1,4}[A-Za-z]?)\b")
|
| 289 |
+
_TITLE_ARTICLE = re.compile(
|
| 290 |
+
r"(?i)^(?:article|art\.?)\s+([0-9]{1,4}(?:-[0-9]{1,4})?[A-Za-z]?)\b"
|
| 291 |
+
)
|
| 292 |
+
_TITLE_NUM = re.compile(r"^([0-9]{1,4}[A-Za-z]?)\s*[.)]\s+\S")
|
| 293 |
+
_TITLE_LOI = re.compile(
|
| 294 |
+
r"(?i)^article\s+([0-9]{1,4})\b"
|
| 295 |
+
r"(?:\s*,\s*[^,\n]{1,16})*"
|
| 296 |
+
r"\s+de\s+(?:la\s+|l['’])?"
|
| 297 |
+
r"((?:loi|ordonnance)\b.+?)"
|
| 298 |
+
r"\.?\s*$"
|
| 299 |
+
)
|
| 300 |
+
_INSTRUMENT_WORD = re.compile(
|
| 301 |
+
r"(?i)\b(?:code|loi|ordonnance|ordinance|act|treaty|gesetz|constitution|statute|reglement|règlement)\b"
|
| 302 |
+
)
|
| 303 |
+
_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})$")
|
| 304 |
+
_HEADING_KIND = {
|
| 305 |
+
"partie": "part",
|
| 306 |
+
"part": "part",
|
| 307 |
+
"livre": "book",
|
| 308 |
+
"titre": "title",
|
| 309 |
+
"titulo": "title",
|
| 310 |
+
"título": "title",
|
| 311 |
+
"chapitre": "chapter",
|
| 312 |
+
"chapter": "chapter",
|
| 313 |
+
"section": "section",
|
| 314 |
+
}
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def recover_placement(title: str, text: str) -> dict[str, str]:
|
| 318 |
+
"""Read a code name and headings that the record did not already file.
|
| 319 |
+
|
| 320 |
+
Only a heading line near the start of the text is used. A sentence that
|
| 321 |
+
mentions another article is left alone.
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
found: dict[str, str] = {}
|
| 325 |
+
label = title.strip()
|
| 326 |
+
loi = _TITLE_LOI.match(label)
|
| 327 |
+
if loi:
|
| 328 |
+
found["article"] = loi.group(1)
|
| 329 |
+
found["instrument"] = loi.group(2).strip(" .")
|
| 330 |
+
elif _TITLE_ARTICLE.match(label) and len(label) < 80:
|
| 331 |
+
found["article"] = _TITLE_ARTICLE.match(label).group(1) # type: ignore[union-attr]
|
| 332 |
+
elif (section := _TITLE_SECTION.match(label)) is not None:
|
| 333 |
+
found["section"] = section.group(1)
|
| 334 |
+
elif (numbered := _TITLE_NUM.match(label)) is not None:
|
| 335 |
+
found["section"] = numbered.group(1)
|
| 336 |
+
lines = [item.strip() for item in text.splitlines() if item.strip()][:25]
|
| 337 |
+
for index, line in enumerate(lines):
|
| 338 |
+
if index == 0 and "instrument" not in found:
|
| 339 |
+
named = _TITLE_LOI.match(line)
|
| 340 |
+
if named:
|
| 341 |
+
found.setdefault("article", named.group(1))
|
| 342 |
+
found["instrument"] = named.group(2).strip(" .")
|
| 343 |
+
continue
|
| 344 |
+
if "instrument" not in found and _instrument_line(line):
|
| 345 |
+
found["instrument"] = line
|
| 346 |
+
continue
|
| 347 |
+
heading = _HEADING_LINE.match(line)
|
| 348 |
+
if heading:
|
| 349 |
+
kind = _HEADING_KIND[heading.group(1).casefold()]
|
| 350 |
+
number = heading.group(2)
|
| 351 |
+
number = number if number.isdigit() else number.upper()
|
| 352 |
+
if not number.isdigit() and _ROMAN.fullmatch(number) is None:
|
| 353 |
+
continue
|
| 354 |
+
found.setdefault(kind, number)
|
| 355 |
+
continue
|
| 356 |
+
article = _ARTICLE_DOT.match(line) or _ARTICLE_ONLY.match(line)
|
| 357 |
+
if article:
|
| 358 |
+
found.setdefault("article", re.sub(r"\s+", "", article.group(1)))
|
| 359 |
+
continue
|
| 360 |
+
section_line = _SECTION_ONLY.match(line)
|
| 361 |
+
if section_line:
|
| 362 |
+
found.setdefault("section", section_line.group(1))
|
| 363 |
+
return found
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _instrument_line(line: str) -> bool:
|
| 367 |
+
if len(line) < 8 or len(line) > 160:
|
| 368 |
+
return False
|
| 369 |
+
if (
|
| 370 |
+
_HEADING_LINE.match(line)
|
| 371 |
+
or _ARTICLE_DOT.match(line)
|
| 372 |
+
or _ARTICLE_ONLY.match(line)
|
| 373 |
+
or _SECTION_ONLY.match(line)
|
| 374 |
+
):
|
| 375 |
+
return False
|
| 376 |
+
letters = [char for char in line if char.isalpha()]
|
| 377 |
+
if len(letters) < 6:
|
| 378 |
+
return False
|
| 379 |
+
if sum(char.isupper() for char in letters) / len(letters) < 0.75:
|
| 380 |
+
return False
|
| 381 |
+
return _INSTRUMENT_WORD.search(line) is not None
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def _generic_instrument(title: str) -> bool:
|
| 385 |
+
folded = _fold(title)
|
| 386 |
+
if not folded:
|
| 387 |
+
return True
|
| 388 |
+
if folded in {"article", "section", "chapter", "chapitre", "titel", "title", "artikel"}:
|
| 389 |
+
return True
|
| 390 |
+
if re.match(r"(?i)^(article|art\.?|section|sec\.?)\b", title.strip()):
|
| 391 |
+
return True
|
| 392 |
+
if re.match(r"^[0-9]{1,4}[A-Za-z]?\s*[.)]\s+", title.strip()):
|
| 393 |
+
return True
|
| 394 |
+
return False
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def _weak_instrument(entry: DirectoryEntry) -> bool:
|
| 398 |
+
return _generic_instrument(entry.instrument) or _fold(entry.instrument) == _fold(
|
| 399 |
+
_country_label(entry.jurisdiction)
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def _entry(record: Mapping[str, object]) -> DirectoryEntry | None:
|
| 404 |
+
provenance = _provenance(record.get("provenance"))
|
| 405 |
+
if provenance is None:
|
| 406 |
+
return None
|
| 407 |
+
locators = {name: _text(provenance.get(name)) for name in _LOCATORS}
|
| 408 |
+
raw_title = _text(record.get("title"))
|
| 409 |
+
recovered: dict[str, str] = {}
|
| 410 |
+
if _generic_instrument(raw_title) or not any(locators.values()):
|
| 411 |
+
recovered = recover_placement(raw_title, _text(record.get("text")))
|
| 412 |
+
for name in _LOCATORS:
|
| 413 |
+
if not locators[name]:
|
| 414 |
+
locators[name] = recovered.get(name, "")
|
| 415 |
+
book = _text(provenance.get("book")) or recovered.get("book", "")
|
| 416 |
+
if not any(locators.values()) and not book:
|
| 417 |
+
return None
|
| 418 |
+
jurisdiction = _text(record.get("jurisdiction")).upper()
|
| 419 |
+
if _generic_instrument(raw_title):
|
| 420 |
+
instrument = recovered.get("instrument") or _country_label(jurisdiction)
|
| 421 |
+
else:
|
| 422 |
+
instrument = raw_title
|
| 423 |
+
placed = {**locators, "book": book}
|
| 424 |
+
citation, form = _citation(
|
| 425 |
+
jurisdiction=jurisdiction,
|
| 426 |
+
instrument=instrument,
|
| 427 |
+
locators=placed,
|
| 428 |
+
existing=_text(record.get("bluebook_citation")),
|
| 429 |
+
)
|
| 430 |
+
return DirectoryEntry(
|
| 431 |
+
jurisdiction=jurisdiction,
|
| 432 |
+
instrument=instrument,
|
| 433 |
+
title=locators["title"],
|
| 434 |
+
book=book,
|
| 435 |
+
chapter=locators["chapter"],
|
| 436 |
+
part=locators["part"],
|
| 437 |
+
article=locators["article"],
|
| 438 |
+
section=locators["section"],
|
| 439 |
+
citation=citation,
|
| 440 |
+
citation_form=form,
|
| 441 |
+
path=_path(instrument, placed),
|
| 442 |
+
entry_cid=_text(record.get("entry_cid")),
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def _citation(
|
| 447 |
+
*,
|
| 448 |
+
jurisdiction: str,
|
| 449 |
+
instrument: str,
|
| 450 |
+
locators: Mapping[str, str],
|
| 451 |
+
existing: str,
|
| 452 |
+
) -> tuple[str, str]:
|
| 453 |
+
if existing:
|
| 454 |
+
return existing, "bluebook"
|
| 455 |
+
form = _known_form(jurisdiction, instrument)
|
| 456 |
+
if form is not None:
|
| 457 |
+
abbreviation, pin = form
|
| 458 |
+
number = locators.get(pin) or ""
|
| 459 |
+
if not number and pin == "article":
|
| 460 |
+
number = locators.get("section") or ""
|
| 461 |
+
if not number and pin == "section":
|
| 462 |
+
number = locators.get("article") or ""
|
| 463 |
+
if number:
|
| 464 |
+
if abbreviation in _TITLE_PREFIX and locators.get("title"):
|
| 465 |
+
return f"{locators['title']} {abbreviation} § {number}", "bluebook"
|
| 466 |
+
if abbreviation not in _TITLE_PREFIX:
|
| 467 |
+
joiner = "art." if pin == "article" else "§"
|
| 468 |
+
return f"{abbreviation} {joiner} {number}", "bluebook"
|
| 469 |
+
eu = _EU_ACT.search(instrument)
|
| 470 |
+
if jurisdiction == "EU" and eu is not None:
|
| 471 |
+
kind = eu.group(1).casefold()
|
| 472 |
+
number = eu.group(2).upper().replace("(EU) ", "")
|
| 473 |
+
pin = locators.get("article") or locators.get("section")
|
| 474 |
+
if pin:
|
| 475 |
+
label = {"regulation": "Regulation", "directive": "Directive", "decision": "Decision"}[kind]
|
| 476 |
+
token = "art." if locators.get("article") else "§"
|
| 477 |
+
return f"{label} (EU) {number}, {token} {pin}", "bluebook_analog"
|
| 478 |
+
return _analog(jurisdiction, instrument, locators), "bluebook_analog"
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
def _analog(jurisdiction: str, instrument: str, locators: Mapping[str, str]) -> str:
|
| 482 |
+
pieces = [_country_label(jurisdiction)]
|
| 483 |
+
if _fold(instrument) != _fold(pieces[0]):
|
| 484 |
+
pieces.append(instrument)
|
| 485 |
+
pins = _pins(locators)
|
| 486 |
+
if pins:
|
| 487 |
+
pieces.append(pins)
|
| 488 |
+
return ", ".join(pieces)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _pins(locators: Mapping[str, str]) -> str:
|
| 492 |
+
labels = (
|
| 493 |
+
("part", "pt."),
|
| 494 |
+
("book", "bk."),
|
| 495 |
+
("title", "tit."),
|
| 496 |
+
("chapter", "ch."),
|
| 497 |
+
("section", "§"),
|
| 498 |
+
("article", "art."),
|
| 499 |
+
)
|
| 500 |
+
article = locators.get("article") or ""
|
| 501 |
+
parts: list[str] = []
|
| 502 |
+
for name, label in labels:
|
| 503 |
+
number = locators.get(name) or ""
|
| 504 |
+
if not number:
|
| 505 |
+
continue
|
| 506 |
+
if name == "section" and number == article:
|
| 507 |
+
continue
|
| 508 |
+
parts.append(f"{label} {number}")
|
| 509 |
+
return ", ".join(parts)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
def _known_form(jurisdiction: str, instrument: str) -> tuple[str, str] | None:
|
| 513 |
+
folded = _fold(instrument)
|
| 514 |
+
for code, name, abbreviation, pin in _CODE_FORMS:
|
| 515 |
+
if jurisdiction == code and (folded == name or folded.startswith(name + " ")):
|
| 516 |
+
return abbreviation, pin
|
| 517 |
+
return None
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def _path(instrument: str, locators: Mapping[str, str]) -> str:
|
| 521 |
+
labels = {
|
| 522 |
+
"part": "Part",
|
| 523 |
+
"book": "Book",
|
| 524 |
+
"title": "Title",
|
| 525 |
+
"chapter": "Chapter",
|
| 526 |
+
"section": "Section",
|
| 527 |
+
"article": "Article",
|
| 528 |
+
}
|
| 529 |
+
parts = [instrument]
|
| 530 |
+
article = locators.get("article") or ""
|
| 531 |
+
for name in ("part", "book", "title", "chapter", "section", "article"):
|
| 532 |
+
number = locators.get(name) or ""
|
| 533 |
+
if not number:
|
| 534 |
+
continue
|
| 535 |
+
if name == "section" and number == article:
|
| 536 |
+
continue
|
| 537 |
+
parts.append(f"{labels[name]} {number}")
|
| 538 |
+
return " / ".join(parts)
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
def _note_number(numbers: dict[tuple[str, ...], tuple[str, set[int]]], entry: DirectoryEntry) -> None:
|
| 542 |
+
if _weak_instrument(entry):
|
| 543 |
+
return
|
| 544 |
+
leaf = entry.article or entry.section
|
| 545 |
+
if _NUMBER.fullmatch(leaf) is None:
|
| 546 |
+
return
|
| 547 |
+
kind = "article" if entry.article else "section"
|
| 548 |
+
key = (
|
| 549 |
+
entry.jurisdiction,
|
| 550 |
+
_fold(entry.instrument),
|
| 551 |
+
entry.part,
|
| 552 |
+
entry.book,
|
| 553 |
+
entry.title,
|
| 554 |
+
entry.chapter,
|
| 555 |
+
kind,
|
| 556 |
+
)
|
| 557 |
+
slot = numbers.get(key)
|
| 558 |
+
if slot is None:
|
| 559 |
+
slot = (entry.instrument, set())
|
| 560 |
+
numbers[key] = slot
|
| 561 |
+
slot[1].add(int(leaf))
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def _gaps(numbers: Mapping[tuple[str, ...], tuple[str, set[int]]]) -> list[dict[str, object]]:
|
| 565 |
+
found: list[dict[str, object]] = []
|
| 566 |
+
for key, (instrument, present) in numbers.items():
|
| 567 |
+
if len(present) < _GAP_MIN_PRESENT:
|
| 568 |
+
continue
|
| 569 |
+
start, stop = min(present), max(present)
|
| 570 |
+
span = stop - start + 1
|
| 571 |
+
if span > _GAP_MAX_SPAN or len(present) / span < _GAP_MIN_DENSITY:
|
| 572 |
+
continue
|
| 573 |
+
missing = [number for number in range(start, stop + 1) if number not in present]
|
| 574 |
+
if not missing:
|
| 575 |
+
continue
|
| 576 |
+
jurisdiction, _folded, part, book, title, chapter, kind = key
|
| 577 |
+
found.append(
|
| 578 |
+
{
|
| 579 |
+
"jurisdiction": jurisdiction,
|
| 580 |
+
"instrument": instrument,
|
| 581 |
+
"part": part,
|
| 582 |
+
"book": book,
|
| 583 |
+
"title": title,
|
| 584 |
+
"chapter": chapter,
|
| 585 |
+
"unit": kind,
|
| 586 |
+
"missing": missing,
|
| 587 |
+
}
|
| 588 |
+
)
|
| 589 |
+
found.sort(key=lambda row: (str(row["instrument"]), str(row["title"]), str(row["chapter"])))
|
| 590 |
+
return found
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _unplaced(record: Mapping[str, object]) -> dict[str, str]:
|
| 594 |
+
return {
|
| 595 |
+
"entry_cid": _text(record.get("entry_cid")),
|
| 596 |
+
"jurisdiction": _text(record.get("jurisdiction")),
|
| 597 |
+
"instrument": _text(record.get("title")),
|
| 598 |
+
"reason": "no_locator",
|
| 599 |
+
}
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def _entry_key(entry: DirectoryEntry) -> tuple[str, ...]:
|
| 603 |
+
return (
|
| 604 |
+
entry.jurisdiction,
|
| 605 |
+
_fold(entry.instrument),
|
| 606 |
+
entry.part,
|
| 607 |
+
entry.book,
|
| 608 |
+
entry.title,
|
| 609 |
+
entry.chapter,
|
| 610 |
+
entry.article,
|
| 611 |
+
entry.section,
|
| 612 |
+
)
|
| 613 |
+
|
| 614 |
+
|
| 615 |
+
def _sort_key(entry: DirectoryEntry) -> tuple[object, ...]:
|
| 616 |
+
return (
|
| 617 |
+
entry.jurisdiction,
|
| 618 |
+
_fold(entry.instrument),
|
| 619 |
+
_number_key(entry.part),
|
| 620 |
+
_number_key(entry.book),
|
| 621 |
+
_number_key(entry.title),
|
| 622 |
+
_number_key(entry.chapter),
|
| 623 |
+
_number_key(entry.article or entry.section),
|
| 624 |
+
entry.entry_cid,
|
| 625 |
+
)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
def _number_key(value: str) -> tuple[int, int | str]:
|
| 629 |
+
if value.isdigit():
|
| 630 |
+
return (0, int(value))
|
| 631 |
+
return (1, value)
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def _country_label(code: str) -> str:
|
| 635 |
+
if code in _LABELS:
|
| 636 |
+
return _LABELS[code]
|
| 637 |
+
return _DEFAULT_NAMES.get(code) or code
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def _provenance(value: object) -> dict[str, object] | None:
|
| 641 |
+
if isinstance(value, dict):
|
| 642 |
+
return value
|
| 643 |
+
if isinstance(value, str) and value.strip().startswith("{"):
|
| 644 |
+
try:
|
| 645 |
+
loaded = json.loads(value)
|
| 646 |
+
except json.JSONDecodeError:
|
| 647 |
+
return None
|
| 648 |
+
if isinstance(loaded, dict):
|
| 649 |
+
return loaded
|
| 650 |
+
return None
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def _fold(value: str) -> str:
|
| 654 |
+
normal = unicodedata.normalize("NFKD", value).casefold()
|
| 655 |
+
letters = "".join(char for char in normal if not unicodedata.combining(char))
|
| 656 |
+
return re.sub(r"\s+", " ", letters).strip()
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def _text(value: object) -> str:
|
| 660 |
+
if isinstance(value, str):
|
| 661 |
+
return value.strip()
|
| 662 |
+
return ""
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def _parquet_rows(parts: list[Path]) -> list[tuple[Path, int]]:
|
| 666 |
+
import pyarrow.parquet as pq
|
| 667 |
+
|
| 668 |
+
return [(path, pq.ParquetFile(path).metadata.num_rows) for path in parts]
|
| 669 |
+
|
| 670 |
+
|
| 671 |
+
def _iter_records(parts: list[Path]) -> Iterable[dict[str, object]]:
|
| 672 |
+
import pyarrow.parquet as pq
|
| 673 |
+
|
| 674 |
+
wanted = {
|
| 675 |
+
"jurisdiction",
|
| 676 |
+
"admin_level",
|
| 677 |
+
"instrument_type",
|
| 678 |
+
"citation",
|
| 679 |
+
"bluebook_citation",
|
| 680 |
+
"title",
|
| 681 |
+
"text",
|
| 682 |
+
"content_sha256",
|
| 683 |
+
"entry_cid",
|
| 684 |
+
"provenance",
|
| 685 |
+
}
|
| 686 |
+
columns = [name for name in LEGAL_RECORD_FIELDS if name in wanted]
|
| 687 |
+
for path in parts:
|
| 688 |
+
present = [name for name in columns if name in pq.read_schema(path).names]
|
| 689 |
+
parquet = pq.ParquetFile(path)
|
| 690 |
+
for batch in parquet.iter_batches(batch_size=256, columns=present):
|
| 691 |
+
yield from batch.to_pylist()
|
| 692 |
+
|
| 693 |
+
|
| 694 |
+
def _write_jsonl(path: Path, rows: Iterable[Mapping[str, object]]) -> None:
|
| 695 |
+
with path.open("w", encoding="utf-8") as handle:
|
| 696 |
+
for row in rows:
|
| 697 |
+
handle.write(json.dumps(row, sort_keys=True, ensure_ascii=False) + "\n")
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize.py
ADDED
|
@@ -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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Normalize endomorphosis/ipfs_*_laws into a CID-keyed canonical corpus.
|
| 2 |
+
|
| 3 |
+
Prefer article/section as the retrieval unit; fall back to law-level when
|
| 4 |
+
articles are missing or empty. Strip leftover HTML, then detect multilingual
|
| 5 |
+
title/chapter/article/section headings (Oregon-style) when present. Never
|
| 6 |
+
invent legal text or a hierarchy that is not in the source.
|
| 7 |
+
|
| 8 |
+
Public Hub reads only (token=False). No Hugging Face token is read or stored.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import re
|
| 16 |
+
from collections import Counter
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
from typing import Any
|
| 19 |
+
|
| 20 |
+
import pandas as pd
|
| 21 |
+
from huggingface_hub import dataset_info, hf_hub_download
|
| 22 |
+
from huggingface_hub.errors import EntryNotFoundError
|
| 23 |
+
|
| 24 |
+
from . import ENTRY_IDENTITY_SCHEMA, LAW_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 25 |
+
from .auth import configure_hf, public_token
|
| 26 |
+
from .cidutil import cid_of_json, sha256_file, sha256_hex
|
| 27 |
+
from .schema import SchemaError, validate_articles, validate_laws
|
| 28 |
+
from .reconstruct import (
|
| 29 |
+
article_sort_key,
|
| 30 |
+
parent_needs_reconstruct,
|
| 31 |
+
reconstruct_on,
|
| 32 |
+
reconstruct_parent,
|
| 33 |
+
)
|
| 34 |
+
from .structure import normalize_legal_text, split_structured_units
|
| 35 |
+
|
| 36 |
+
COLLECTOR_DEFAULT = "endomorphosis/ipfs_datasets_py"
|
| 37 |
+
EMPTY_ARTICLE_COLUMNS = (
|
| 38 |
+
"law_id",
|
| 39 |
+
"id",
|
| 40 |
+
"title",
|
| 41 |
+
"text",
|
| 42 |
+
"source_url",
|
| 43 |
+
"document_number",
|
| 44 |
+
"article_number",
|
| 45 |
+
"record_type",
|
| 46 |
+
"metadata_json",
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _empty_articles() -> pd.DataFrame:
|
| 51 |
+
return pd.DataFrame(columns=list(EMPTY_ARTICLE_COLUMNS))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def normalize_text(value: Any) -> str:
|
| 55 |
+
if value is None or (isinstance(value, float) and pd.isna(value)):
|
| 56 |
+
return ""
|
| 57 |
+
return normalize_legal_text(value)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _s(value: Any) -> str:
|
| 61 |
+
return normalize_text(value)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _download(repo_id: str, filename: str, cache_dir: Path) -> Path:
|
| 65 |
+
configure_hf()
|
| 66 |
+
path = hf_hub_download(
|
| 67 |
+
repo_id=repo_id,
|
| 68 |
+
filename=filename,
|
| 69 |
+
repo_type="dataset",
|
| 70 |
+
token=public_token(),
|
| 71 |
+
cache_dir=str(cache_dir / "hf"),
|
| 72 |
+
)
|
| 73 |
+
return Path(path)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _repo_filenames(info: Any) -> set[str]:
|
| 77 |
+
return {str(getattr(s, "rfilename", "") or "") for s in (getattr(info, "siblings", None) or [])}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def _pick_repo_file(filenames: set[str], name: str) -> str | None:
|
| 81 |
+
for cand in (f"data/{name}.parquet", f"{name}.parquet"):
|
| 82 |
+
if cand in filenames:
|
| 83 |
+
return cand
|
| 84 |
+
return None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _resolve_local_parquet(root: Path, name: str, *, required: bool = True) -> Path | None:
|
| 88 |
+
"""Accept either <root>/data/<name>.parquet or <root>/<name>.parquet."""
|
| 89 |
+
for cand in (root / "data" / f"{name}.parquet", root / f"{name}.parquet"):
|
| 90 |
+
if cand.is_file():
|
| 91 |
+
return cand
|
| 92 |
+
if required:
|
| 93 |
+
raise FileNotFoundError(f"missing {name}.parquet under {root} (tried data/ and root)")
|
| 94 |
+
return None
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def load_local_source(local_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 98 |
+
"""Load a local country-laws pack (filtered preprocess layout)."""
|
| 99 |
+
local_dir = Path(local_dir).resolve()
|
| 100 |
+
laws_path = _resolve_local_parquet(local_dir, "laws")
|
| 101 |
+
articles_path = _resolve_local_parquet(local_dir, "articles", required=False)
|
| 102 |
+
laws = pd.read_parquet(laws_path)
|
| 103 |
+
articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
|
| 104 |
+
validate_laws(laws)
|
| 105 |
+
validate_articles(articles)
|
| 106 |
+
pack_meta: dict[str, Any] = {}
|
| 107 |
+
meta_path = local_dir / "pack_meta.json"
|
| 108 |
+
if meta_path.is_file():
|
| 109 |
+
try:
|
| 110 |
+
pack_meta = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 111 |
+
except Exception:
|
| 112 |
+
pack_meta = {}
|
| 113 |
+
source_dataset = (
|
| 114 |
+
pack_meta.get("source_dataset")
|
| 115 |
+
or pack_meta.get("repo")
|
| 116 |
+
or f"local/{local_dir.name}"
|
| 117 |
+
)
|
| 118 |
+
source_revision = str(
|
| 119 |
+
pack_meta.get("source_revision")
|
| 120 |
+
or pack_meta.get("revision")
|
| 121 |
+
or f"local:{local_dir.name}"
|
| 122 |
+
)
|
| 123 |
+
meta = {
|
| 124 |
+
"source_dataset": source_dataset,
|
| 125 |
+
"source_revision": source_revision,
|
| 126 |
+
"laws_path": str(laws_path),
|
| 127 |
+
"articles_path": str(articles_path) if articles_path is not None else None,
|
| 128 |
+
"laws_sha256": sha256_file(laws_path),
|
| 129 |
+
"articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
|
| 130 |
+
"n_laws_source": int(len(laws)),
|
| 131 |
+
"n_articles_source": int(len(articles)),
|
| 132 |
+
"laws_columns": list(map(str, laws.columns)),
|
| 133 |
+
"articles_columns": list(map(str, articles.columns)),
|
| 134 |
+
"article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None,
|
| 135 |
+
"schema_surprises": _schema_surprises(laws, articles),
|
| 136 |
+
"local_source_dir": str(local_dir),
|
| 137 |
+
"pack_meta": pack_meta,
|
| 138 |
+
}
|
| 139 |
+
return laws, articles, meta
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _law_shards(local: Path) -> list[Path]:
|
| 143 |
+
data = local / "data"
|
| 144 |
+
if not data.is_dir():
|
| 145 |
+
return []
|
| 146 |
+
return [
|
| 147 |
+
path
|
| 148 |
+
for path in sorted(data.glob("laws-*.parquet"))
|
| 149 |
+
if "_html" not in path.name
|
| 150 |
+
]
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def _pack_local_shards(local: Path, cache_dir: Path) -> Path:
|
| 154 |
+
"""Concatenate a local shard directory. Does not contact the Hub."""
|
| 155 |
+
|
| 156 |
+
meta: dict[str, Any] = {}
|
| 157 |
+
meta_path = local / "pack_meta.json"
|
| 158 |
+
if meta_path.is_file():
|
| 159 |
+
try:
|
| 160 |
+
loaded = json.loads(meta_path.read_text(encoding="utf-8"))
|
| 161 |
+
if isinstance(loaded, dict):
|
| 162 |
+
meta = loaded
|
| 163 |
+
except Exception:
|
| 164 |
+
meta = {}
|
| 165 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.load_sharded_laws import (
|
| 166 |
+
load_sharded_laws,
|
| 167 |
+
require_source_revision,
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
revision = require_source_revision(local)
|
| 171 |
+
slug = str(meta.get("slug") or local.name)
|
| 172 |
+
dataset = str(meta.get("source_dataset") or f"endomorphosis/ipfs_{slug}_laws")
|
| 173 |
+
dest = Path(cache_dir) / "packed-shards" / slug
|
| 174 |
+
|
| 175 |
+
load_sharded_laws(
|
| 176 |
+
local,
|
| 177 |
+
dest,
|
| 178 |
+
slug=slug,
|
| 179 |
+
source_dataset=dataset,
|
| 180 |
+
source_revision=revision,
|
| 181 |
+
)
|
| 182 |
+
return dest
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def preflight_local_shard_source(source: str) -> None:
|
| 186 |
+
"""Reject an unpacked shard directory before ``build_country`` starts.
|
| 187 |
+
|
| 188 |
+
Hub ids and directories that already contain ``laws.parquet`` return
|
| 189 |
+
without reading them. A shard directory whose ``source_revision`` is
|
| 190 |
+
missing or not 40 lowercase hex characters raises ``ValueError``.
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
local = Path(source)
|
| 194 |
+
if not local.is_dir():
|
| 195 |
+
return
|
| 196 |
+
if (local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file():
|
| 197 |
+
return
|
| 198 |
+
if not _law_shards(local):
|
| 199 |
+
return
|
| 200 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.load_sharded_laws import (
|
| 201 |
+
require_source_revision,
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
require_source_revision(local)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def load_source(repo_id: str, cache_dir: Path) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 208 |
+
"""Load Hub dataset id OR a local directory with laws/articles parquet.
|
| 209 |
+
|
| 210 |
+
A local directory of ``data/laws-*.parquet`` is packed with
|
| 211 |
+
``load_sharded_laws`` before it is read. That path requires a 40-hex
|
| 212 |
+
``source_revision`` in ``pack_meta.json`` and does not call the Hub.
|
| 213 |
+
"""
|
| 214 |
+
local = Path(repo_id)
|
| 215 |
+
if local.is_dir() and (
|
| 216 |
+
(local / "data" / "laws.parquet").is_file() or (local / "laws.parquet").is_file()
|
| 217 |
+
):
|
| 218 |
+
return load_local_source(local)
|
| 219 |
+
if local.is_dir() and _law_shards(local):
|
| 220 |
+
return load_local_source(_pack_local_shards(local, cache_dir))
|
| 221 |
+
|
| 222 |
+
configure_hf()
|
| 223 |
+
os.environ.setdefault("HF_HOME", str(cache_dir / "hf"))
|
| 224 |
+
info = dataset_info(repo_id, token=public_token())
|
| 225 |
+
revision = info.sha
|
| 226 |
+
filenames = _repo_filenames(info)
|
| 227 |
+
laws_file = _pick_repo_file(filenames, "laws") or "data/laws.parquet"
|
| 228 |
+
articles_file = _pick_repo_file(filenames, "articles")
|
| 229 |
+
laws_path = _download(repo_id, laws_file, cache_dir)
|
| 230 |
+
articles_path: Path | None = None
|
| 231 |
+
if articles_file is not None:
|
| 232 |
+
try:
|
| 233 |
+
articles_path = _download(repo_id, articles_file, cache_dir)
|
| 234 |
+
except EntryNotFoundError:
|
| 235 |
+
articles_path = None
|
| 236 |
+
laws = pd.read_parquet(laws_path)
|
| 237 |
+
articles = pd.read_parquet(articles_path) if articles_path is not None else _empty_articles()
|
| 238 |
+
validate_laws(laws)
|
| 239 |
+
validate_articles(articles)
|
| 240 |
+
meta = {
|
| 241 |
+
"source_dataset": repo_id,
|
| 242 |
+
"source_revision": revision,
|
| 243 |
+
"laws_path": str(laws_path),
|
| 244 |
+
"articles_path": str(articles_path) if articles_path is not None else None,
|
| 245 |
+
"laws_sha256": sha256_file(laws_path),
|
| 246 |
+
"articles_sha256": sha256_file(articles_path) if articles_path is not None else None,
|
| 247 |
+
"n_laws_source": int(len(laws)),
|
| 248 |
+
"n_articles_source": int(len(articles)),
|
| 249 |
+
"laws_columns": list(map(str, laws.columns)),
|
| 250 |
+
"articles_columns": list(map(str, articles.columns)),
|
| 251 |
+
"article_count_dtype": str(laws["article_count"].dtype) if "article_count" in laws.columns else None,
|
| 252 |
+
"schema_surprises": _schema_surprises(laws, articles),
|
| 253 |
+
}
|
| 254 |
+
return laws, articles, meta
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _schema_surprises(laws: pd.DataFrame, articles: pd.DataFrame) -> list[str]:
|
| 258 |
+
notes: list[str] = []
|
| 259 |
+
if articles is None or articles.empty:
|
| 260 |
+
notes.append("articles.parquet has 0 rows; corpus falls back to law-level units")
|
| 261 |
+
if "article_count" in laws.columns:
|
| 262 |
+
dtype = str(laws["article_count"].dtype)
|
| 263 |
+
notes.append(f"laws.article_count dtype={dtype}")
|
| 264 |
+
try:
|
| 265 |
+
if int((laws["article_count"].fillna(0) == 0).sum()) == len(laws):
|
| 266 |
+
notes.append("every law has article_count=0")
|
| 267 |
+
except Exception:
|
| 268 |
+
pass
|
| 269 |
+
for col in ("date", "date_issued"):
|
| 270 |
+
if col in laws.columns and laws[col].isna().all():
|
| 271 |
+
notes.append(f"laws.{col} is entirely null")
|
| 272 |
+
if "eli" in laws.columns:
|
| 273 |
+
n_eli = int(laws["eli"].notna().sum()) if hasattr(laws["eli"], "notna") else 0
|
| 274 |
+
notes.append(f"laws.eli non-null={n_eli}/{len(laws)}")
|
| 275 |
+
if "language" in laws.columns:
|
| 276 |
+
langs = sorted({str(x) for x in laws["language"].dropna().unique()})
|
| 277 |
+
notes.append(f"laws.language values={langs}")
|
| 278 |
+
return notes
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def _parse_meta(raw: str) -> dict[str, Any]:
|
| 282 |
+
if not raw:
|
| 283 |
+
return {}
|
| 284 |
+
try:
|
| 285 |
+
obj = json.loads(raw)
|
| 286 |
+
return obj if isinstance(obj, dict) else {}
|
| 287 |
+
except Exception:
|
| 288 |
+
return {}
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def _law_cid(instrument_id: str, instrument_title: str, jurisdiction: str, language: str, source_dataset: str) -> str:
|
| 292 |
+
identity = {
|
| 293 |
+
"schema": LAW_IDENTITY_SCHEMA,
|
| 294 |
+
"source_dataset": source_dataset,
|
| 295 |
+
"instrument_id": instrument_id,
|
| 296 |
+
"instrument_title": instrument_title,
|
| 297 |
+
"jurisdiction": jurisdiction,
|
| 298 |
+
"language": language,
|
| 299 |
+
}
|
| 300 |
+
return cid_of_json(identity)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _entry_cid(record: dict[str, Any]) -> str:
|
| 304 |
+
identity = {
|
| 305 |
+
"schema": ENTRY_IDENTITY_SCHEMA,
|
| 306 |
+
"record_type": record["record_type"],
|
| 307 |
+
"source_dataset": record["source_dataset"],
|
| 308 |
+
"instrument_id": record["instrument_id"],
|
| 309 |
+
"article_number": record.get("article_number") or "",
|
| 310 |
+
"article_title": record.get("article_title") or "",
|
| 311 |
+
"body_sha256": record["body_sha256"],
|
| 312 |
+
"language": record.get("language") or "",
|
| 313 |
+
"jurisdiction": record.get("jurisdiction") or "",
|
| 314 |
+
"source_url": record.get("source_url") or "",
|
| 315 |
+
}
|
| 316 |
+
return cid_of_json(identity)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _row_get(row: pd.Series, col: str, default: str = "") -> str:
|
| 320 |
+
if col not in row.index:
|
| 321 |
+
return default
|
| 322 |
+
return _s(row[col])
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _coverage_from(
|
| 326 |
+
row: pd.Series,
|
| 327 |
+
meta: dict[str, Any],
|
| 328 |
+
articles_empty: bool,
|
| 329 |
+
sparse_fallback: bool = False,
|
| 330 |
+
) -> str:
|
| 331 |
+
for key in ("coverage", "coverage_note"):
|
| 332 |
+
if key in meta and meta[key]:
|
| 333 |
+
return normalize_text(meta[key])
|
| 334 |
+
status = normalize_text(meta.get("article_extraction_status") or "")
|
| 335 |
+
if sparse_fallback:
|
| 336 |
+
note = "law-level (article coverage below 10% of laws; sparse articles table)"
|
| 337 |
+
if status:
|
| 338 |
+
return f"{note}; extraction_status={status}"
|
| 339 |
+
return note
|
| 340 |
+
if articles_empty:
|
| 341 |
+
if status:
|
| 342 |
+
return f"law-level (articles empty or unavailable in source snapshot); extraction_status={status}"
|
| 343 |
+
return "law-level (articles empty or unavailable in source snapshot)"
|
| 344 |
+
if status:
|
| 345 |
+
return f"article-level; extraction_status={status}"
|
| 346 |
+
return "article-level"
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def _snapshot_date(row: pd.Series, meta: dict[str, Any], source_meta: dict[str, Any]) -> str:
|
| 350 |
+
for col in ("retrieved_at", "date_issued", "date"):
|
| 351 |
+
val = _row_get(row, col)
|
| 352 |
+
if val:
|
| 353 |
+
return val[:10] if len(val) >= 10 and val[4] == "-" else val
|
| 354 |
+
for key in ("snapshot_date", "retrieved_at"):
|
| 355 |
+
if key in meta and meta[key]:
|
| 356 |
+
return normalize_text(str(meta[key]))[:10]
|
| 357 |
+
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 358 |
+
for key in ("snapshot_date", "retrieved_at"):
|
| 359 |
+
if nested.get(key):
|
| 360 |
+
return normalize_text(str(nested[key]))[:10]
|
| 361 |
+
return ""
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def _hierarchy_fields(
|
| 365 |
+
title: str, body: str, article_number: str, *, language: str = ""
|
| 366 |
+
) -> dict[str, Any]:
|
| 367 |
+
"""Best-effort hierarchy from a single already-split article/section body."""
|
| 368 |
+
units = split_structured_units(
|
| 369 |
+
f"{title}\n{body}" if title else body, language=language
|
| 370 |
+
)
|
| 371 |
+
if not units:
|
| 372 |
+
return {
|
| 373 |
+
"hierarchy_kind": "article" if article_number else "law",
|
| 374 |
+
"hierarchy_path": "",
|
| 375 |
+
"title_number": "",
|
| 376 |
+
"chapter_number": "",
|
| 377 |
+
"part_number": "",
|
| 378 |
+
"section_number": "",
|
| 379 |
+
"subsections": [],
|
| 380 |
+
}
|
| 381 |
+
unit = units[0]
|
| 382 |
+
return {
|
| 383 |
+
"hierarchy_kind": unit.kind,
|
| 384 |
+
"hierarchy_path": unit.hierarchy_path,
|
| 385 |
+
"title_number": unit.title_number,
|
| 386 |
+
"chapter_number": unit.chapter_number,
|
| 387 |
+
"part_number": unit.part_number,
|
| 388 |
+
"section_number": unit.section_number,
|
| 389 |
+
"subsections": list(unit.subsections),
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
|
| 393 |
+
def _compact_line(text: str) -> str:
|
| 394 |
+
return re.sub(r"\s+", " ", text or "").strip().casefold()
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def _is_title_shell(body: str, title: str) -> bool:
|
| 398 |
+
"""True when the article row is only its heading, repeated once."""
|
| 399 |
+
folded_body = _compact_line(body)
|
| 400 |
+
folded_title = _compact_line(title)
|
| 401 |
+
if len(folded_title) < 24 or not folded_body:
|
| 402 |
+
return False
|
| 403 |
+
return folded_body == folded_title or folded_body == f"{folded_title} {folded_title}"
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
_NOTICE_RE = re.compile(
|
| 407 |
+
r"(?i)(\bnewsletter\b|\bblog\b|press release|communiqu[eé]|"
|
| 408 |
+
r"\bnews item\b|\bnotice board\b)"
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _instrument_record_type(
|
| 413 |
+
metadata: dict[str, Any],
|
| 414 |
+
title: str,
|
| 415 |
+
*,
|
| 416 |
+
text: str = "",
|
| 417 |
+
source_url: str = "",
|
| 418 |
+
language: str = "",
|
| 419 |
+
) -> str:
|
| 420 |
+
"""A normative instrument is a law, even when its title says Article.
|
| 421 |
+
|
| 422 |
+
Newsletters, blogs, press notices, title-only cards, and informative
|
| 423 |
+
website pages are not laws. A provision inside a law stays an article;
|
| 424 |
+
this label is only for the instrument itself.
|
| 425 |
+
"""
|
| 426 |
+
meta = metadata or {}
|
| 427 |
+
document_type = str(meta.get("document_type") or "").strip().casefold()
|
| 428 |
+
meta_type = str(meta.get("record_type") or "").strip().casefold()
|
| 429 |
+
if _NOTICE_RE.search(title or "") or document_type in {
|
| 430 |
+
"newsletter",
|
| 431 |
+
"blog",
|
| 432 |
+
"press",
|
| 433 |
+
"press_release",
|
| 434 |
+
"notice",
|
| 435 |
+
}:
|
| 436 |
+
return "notice"
|
| 437 |
+
if document_type in {"gazette", "gazette_pdf"} and meta_type not in {
|
| 438 |
+
"law",
|
| 439 |
+
"statute",
|
| 440 |
+
"constitution",
|
| 441 |
+
}:
|
| 442 |
+
return "notice"
|
| 443 |
+
from ipfs_datasets_py.processors.legal_scrapers.world_law.document_role import (
|
| 444 |
+
classify_document_role,
|
| 445 |
+
)
|
| 446 |
+
|
| 447 |
+
role, _reason = classify_document_role(
|
| 448 |
+
{
|
| 449 |
+
"title": title,
|
| 450 |
+
"text": text,
|
| 451 |
+
"source_url": source_url,
|
| 452 |
+
"language": language,
|
| 453 |
+
"doc_type": document_type,
|
| 454 |
+
}
|
| 455 |
+
)
|
| 456 |
+
if role in {"metadata", "informative"}:
|
| 457 |
+
return "notice"
|
| 458 |
+
return "law"
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def _unit_record_type(unit: Any, instrument_type: str, *, n_units: int, parent_body: str) -> str:
|
| 462 |
+
"""One unit that is the whole instrument keeps the instrument label."""
|
| 463 |
+
if instrument_type == "notice":
|
| 464 |
+
return "notice"
|
| 465 |
+
if (
|
| 466 |
+
n_units == 1
|
| 467 |
+
and parent_body
|
| 468 |
+
and len(getattr(unit, "body", "") or "") >= int(0.8 * len(parent_body))
|
| 469 |
+
):
|
| 470 |
+
return "law"
|
| 471 |
+
kind = getattr(unit, "kind", "") or ""
|
| 472 |
+
if kind in {"article", "section"}:
|
| 473 |
+
return kind
|
| 474 |
+
return "article"
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _children_are_rich(kids: list[dict[str, Any]], parent_body: str) -> bool:
|
| 478 |
+
"""True when the article rows already carry the statute, not just headings."""
|
| 479 |
+
if not kids:
|
| 480 |
+
return False
|
| 481 |
+
total = sum(len((kid.get("body") or "").strip()) for kid in kids)
|
| 482 |
+
if total >= max(int(len(parent_body) * 0.5), 200):
|
| 483 |
+
return True
|
| 484 |
+
return any(
|
| 485 |
+
len((kid.get("body") or "").strip()) >= 80
|
| 486 |
+
and not _is_title_shell(kid.get("body") or "", kid.get("title") or "")
|
| 487 |
+
for kid in kids
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def _needs_parent_split(kids: list[dict[str, Any]], parent_body: str) -> bool:
|
| 492 |
+
"""Split the parent when it holds the text and the article rows do not."""
|
| 493 |
+
if len(parent_body) < 250 or len(parent_body) > 1_200_000:
|
| 494 |
+
return False
|
| 495 |
+
return not _children_are_rich(kids, parent_body)
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
def _expand_title_shell(parent: str, title: str, sibling_titles: set[str]) -> str | None:
|
| 499 |
+
"""Copy the parent span from this heading to the next sibling heading.
|
| 500 |
+
|
| 501 |
+
The span is taken only from lines already in the parent. A short heading
|
| 502 |
+
such as "Article 1" is left alone, because it matches too many lines.
|
| 503 |
+
"""
|
| 504 |
+
key = _compact_line(title)
|
| 505 |
+
peers = {item for item in sibling_titles if item and item != key and len(item) >= 24}
|
| 506 |
+
if len(key) < 24 or not peers or not parent:
|
| 507 |
+
return None
|
| 508 |
+
lines = [ln.strip() for ln in parent.splitlines() if ln.strip()]
|
| 509 |
+
compact = [_compact_line(ln) for ln in lines]
|
| 510 |
+
best = ""
|
| 511 |
+
for index, folded in enumerate(compact):
|
| 512 |
+
if folded != key:
|
| 513 |
+
continue
|
| 514 |
+
chunk = [lines[index]]
|
| 515 |
+
for later, later_folded in zip(lines[index + 1 :], compact[index + 1 :]):
|
| 516 |
+
if later_folded in peers:
|
| 517 |
+
break
|
| 518 |
+
chunk.append(later)
|
| 519 |
+
text = "\n".join(chunk).strip()
|
| 520 |
+
if len(text) > len(best):
|
| 521 |
+
best = text
|
| 522 |
+
# The heading alone is not enough. Require a following sentence from the parent.
|
| 523 |
+
if len(best) < len(key) + 40:
|
| 524 |
+
return None
|
| 525 |
+
return best
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _collector(meta: dict[str, Any], source_dataset: str) -> str:
|
| 529 |
+
nested = meta.get("metadata") if isinstance(meta.get("metadata"), dict) else {}
|
| 530 |
+
for blob in (meta, nested):
|
| 531 |
+
for key in ("collector", "collector_id", "harvester"):
|
| 532 |
+
if blob.get(key):
|
| 533 |
+
return normalize_text(blob[key])
|
| 534 |
+
return f"{COLLECTOR_DEFAULT} ({source_dataset})"
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
def laws_index(laws: pd.DataFrame, source_dataset: str) -> dict[str, dict[str, Any]]:
|
| 538 |
+
"""Map instrument_id -> law facet fields (always computed; not always corpus units)."""
|
| 539 |
+
out: dict[str, dict[str, Any]] = {}
|
| 540 |
+
for _, row in laws.iterrows():
|
| 541 |
+
instrument_id = _row_get(row, "id")
|
| 542 |
+
instrument_title = _row_get(row, "title")
|
| 543 |
+
jurisdiction = _row_get(row, "jurisdiction") or _row_get(row, "country")
|
| 544 |
+
language = _row_get(row, "language")
|
| 545 |
+
law_cid = _law_cid(instrument_id, instrument_title, jurisdiction, language, source_dataset)
|
| 546 |
+
meta = _parse_meta(_row_get(row, "metadata_json"))
|
| 547 |
+
out[instrument_id] = {
|
| 548 |
+
"instrument_id": instrument_id,
|
| 549 |
+
"instrument_title": instrument_title,
|
| 550 |
+
"law_cid": law_cid,
|
| 551 |
+
"jurisdiction": jurisdiction,
|
| 552 |
+
"language": language,
|
| 553 |
+
"source_url": _row_get(row, "source_url"),
|
| 554 |
+
"license": _row_get(row, "license"),
|
| 555 |
+
"eli": _row_get(row, "eli"),
|
| 556 |
+
"identifier": _row_get(row, "identifier") or instrument_id,
|
| 557 |
+
"official_identifier": _row_get(row, "official_identifier"),
|
| 558 |
+
"source_type": _row_get(row, "source_type"),
|
| 559 |
+
"country": _row_get(row, "country"),
|
| 560 |
+
"law_status": _row_get(row, "law_status"),
|
| 561 |
+
"body": _row_get(row, "text"),
|
| 562 |
+
"metadata": meta,
|
| 563 |
+
"row": row,
|
| 564 |
+
}
|
| 565 |
+
return out
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def _base_record(
|
| 569 |
+
*,
|
| 570 |
+
record_type: str,
|
| 571 |
+
source_dataset: str,
|
| 572 |
+
source_revision: str,
|
| 573 |
+
instrument_id: str,
|
| 574 |
+
instrument_title: str,
|
| 575 |
+
law_cid: str,
|
| 576 |
+
article_number: str,
|
| 577 |
+
article_title: str,
|
| 578 |
+
body: str,
|
| 579 |
+
jurisdiction: str,
|
| 580 |
+
language: str,
|
| 581 |
+
source_url: str,
|
| 582 |
+
snapshot_date: str,
|
| 583 |
+
coverage: str,
|
| 584 |
+
license_expr: str,
|
| 585 |
+
collector: str,
|
| 586 |
+
source_id: str,
|
| 587 |
+
extra: dict[str, Any] | None = None,
|
| 588 |
+
) -> dict[str, Any]:
|
| 589 |
+
title_for_bm25 = article_title if record_type == "article" and article_title else instrument_title
|
| 590 |
+
rec: dict[str, Any] = {
|
| 591 |
+
"record_type": record_type,
|
| 592 |
+
"source_dataset": source_dataset,
|
| 593 |
+
"source_revision": source_revision,
|
| 594 |
+
"source_id": source_id,
|
| 595 |
+
"instrument_id": instrument_id,
|
| 596 |
+
"instrument_title": instrument_title,
|
| 597 |
+
"law_id": instrument_id,
|
| 598 |
+
"law_cid": law_cid,
|
| 599 |
+
"article_number": article_number,
|
| 600 |
+
"article_title": article_title,
|
| 601 |
+
"title": title_for_bm25,
|
| 602 |
+
"body": body,
|
| 603 |
+
"body_sha256": sha256_hex(body.encode("utf-8")),
|
| 604 |
+
"jurisdiction": jurisdiction,
|
| 605 |
+
"language": language,
|
| 606 |
+
"source_url": source_url,
|
| 607 |
+
"snapshot_date": snapshot_date,
|
| 608 |
+
"coverage": coverage,
|
| 609 |
+
"license": license_expr,
|
| 610 |
+
"collector": collector,
|
| 611 |
+
"schema_version": SCHEMA_VERSION,
|
| 612 |
+
"entry_identity_schema_version": ENTRY_IDENTITY_SCHEMA,
|
| 613 |
+
}
|
| 614 |
+
if extra:
|
| 615 |
+
rec.update(extra)
|
| 616 |
+
from .citations import assign_citation, citation_fields
|
| 617 |
+
|
| 618 |
+
slug = ""
|
| 619 |
+
if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
|
| 620 |
+
slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 621 |
+
year = ""
|
| 622 |
+
if snapshot_date and len(snapshot_date) >= 4 and snapshot_date[:4].isdigit():
|
| 623 |
+
year = snapshot_date[:4]
|
| 624 |
+
extra = extra or {}
|
| 625 |
+
rec.update(
|
| 626 |
+
citation_fields(
|
| 627 |
+
assign_citation(
|
| 628 |
+
eli=str(rec.get("eli") or extra.get("eli") or ""),
|
| 629 |
+
official_identifier=str(
|
| 630 |
+
rec.get("official_identifier") or extra.get("official_identifier") or ""
|
| 631 |
+
),
|
| 632 |
+
identifier=str(rec.get("identifier") or extra.get("identifier") or ""),
|
| 633 |
+
instrument_title=instrument_title,
|
| 634 |
+
article_number=article_number,
|
| 635 |
+
section_number=str(extra.get("section_number") or ""),
|
| 636 |
+
record_type=record_type,
|
| 637 |
+
jurisdiction=jurisdiction,
|
| 638 |
+
country=str(extra.get("country") or ""),
|
| 639 |
+
slug=slug,
|
| 640 |
+
year=year,
|
| 641 |
+
)
|
| 642 |
+
)
|
| 643 |
+
)
|
| 644 |
+
rec["entry_cid"] = _entry_cid(rec)
|
| 645 |
+
rec["title_length"] = len(title_for_bm25)
|
| 646 |
+
rec["body_length"] = len(body)
|
| 647 |
+
rec["document_length"] = len(title_for_bm25) + len(body)
|
| 648 |
+
return rec
|
| 649 |
+
|
| 650 |
+
|
| 651 |
+
def _cid_worker_count(n_articles: int, requested: int | None) -> int:
|
| 652 |
+
"""Cores for a CID-set check. Small corpora stay on one core."""
|
| 653 |
+
if requested is not None:
|
| 654 |
+
return max(1, int(requested))
|
| 655 |
+
if n_articles < 8000:
|
| 656 |
+
return 1
|
| 657 |
+
cpus = os.cpu_count() or 2
|
| 658 |
+
return max(2, min(12, cpus // 4, max(2, n_articles // 20000)))
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
def _article_outcome(
|
| 662 |
+
row: pd.Series,
|
| 663 |
+
*,
|
| 664 |
+
law_map: dict[str, dict[str, Any]],
|
| 665 |
+
promoted: dict[str, list[Any]],
|
| 666 |
+
sibling_titles: dict[str, set[str]],
|
| 667 |
+
source_meta: dict[str, Any],
|
| 668 |
+
source_dataset: str,
|
| 669 |
+
source_revision: str,
|
| 670 |
+
) -> tuple[dict[str, Any] | None, str, Any]:
|
| 671 |
+
"""One article row as a corpus record, or a drop reason.
|
| 672 |
+
|
| 673 |
+
``("", promoted skip)`` is ``(None, "", None)`` and is not a drop.
|
| 674 |
+
"""
|
| 675 |
+
source_id = _row_get(row, "id")
|
| 676 |
+
instrument_id = _row_get(row, "law_id")
|
| 677 |
+
body = _row_get(row, "text")
|
| 678 |
+
article_title = _row_get(row, "title")
|
| 679 |
+
article_number = _row_get(row, "article_number")
|
| 680 |
+
if not body:
|
| 681 |
+
return None, "empty_body", source_id
|
| 682 |
+
if instrument_id in promoted:
|
| 683 |
+
return None, "", None
|
| 684 |
+
parent = law_map.get(instrument_id)
|
| 685 |
+
if parent and _is_title_shell(body, article_title):
|
| 686 |
+
expanded = _expand_title_shell(
|
| 687 |
+
parent["body"],
|
| 688 |
+
article_title,
|
| 689 |
+
sibling_titles.get(instrument_id) or set(),
|
| 690 |
+
)
|
| 691 |
+
if expanded:
|
| 692 |
+
body = expanded
|
| 693 |
+
if not parent:
|
| 694 |
+
return None, "missing_instrument", {"article_id": source_id, "law_id": instrument_id}
|
| 695 |
+
meta = parent["metadata"]
|
| 696 |
+
art_meta = _parse_meta(_row_get(row, "metadata_json"))
|
| 697 |
+
merged_meta = {**meta, **art_meta}
|
| 698 |
+
record = _base_record(
|
| 699 |
+
record_type="article",
|
| 700 |
+
source_dataset=source_dataset,
|
| 701 |
+
source_revision=source_revision,
|
| 702 |
+
instrument_id=instrument_id,
|
| 703 |
+
instrument_title=parent["instrument_title"],
|
| 704 |
+
law_cid=parent["law_cid"],
|
| 705 |
+
article_number=article_number,
|
| 706 |
+
article_title=article_title,
|
| 707 |
+
body=body,
|
| 708 |
+
jurisdiction=parent["jurisdiction"],
|
| 709 |
+
language=parent["language"] or _row_get(row, "language"),
|
| 710 |
+
source_url=_row_get(row, "source_url") or parent["source_url"],
|
| 711 |
+
snapshot_date=_snapshot_date(parent["row"], merged_meta, source_meta),
|
| 712 |
+
coverage=_coverage_from(parent["row"], merged_meta, articles_empty=False),
|
| 713 |
+
license_expr=parent["license"],
|
| 714 |
+
collector=_collector(merged_meta, source_dataset),
|
| 715 |
+
source_id=source_id,
|
| 716 |
+
extra={
|
| 717 |
+
"eli": parent["eli"],
|
| 718 |
+
"identifier": parent["identifier"],
|
| 719 |
+
"official_identifier": parent["official_identifier"],
|
| 720 |
+
"source_type": parent["source_type"],
|
| 721 |
+
"country": parent["country"],
|
| 722 |
+
"law_status": parent["law_status"],
|
| 723 |
+
"parent_law_id": instrument_id,
|
| 724 |
+
"article_id": source_id,
|
| 725 |
+
**_hierarchy_fields(
|
| 726 |
+
article_title, body, article_number, language=parent["language"]
|
| 727 |
+
),
|
| 728 |
+
},
|
| 729 |
+
)
|
| 730 |
+
return record, "", None
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
# Forked CID workers read this. It is set only for the duration of a pool.
|
| 734 |
+
_CID_JOB: dict[str, Any] = {}
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def _cid_article_span(span: tuple[int, int]) -> list[tuple[str, str, Any]]:
|
| 738 |
+
start, end = span
|
| 739 |
+
job = _CID_JOB
|
| 740 |
+
articles = job["articles"]
|
| 741 |
+
out: list[tuple[str, str, Any]] = []
|
| 742 |
+
for i in range(start, end):
|
| 743 |
+
record, drop, sample = _article_outcome(
|
| 744 |
+
articles.iloc[i],
|
| 745 |
+
law_map=job["law_map"],
|
| 746 |
+
promoted=job["promoted"],
|
| 747 |
+
sibling_titles=job["sibling_titles"],
|
| 748 |
+
source_meta=job["source_meta"],
|
| 749 |
+
source_dataset=job["source_dataset"],
|
| 750 |
+
source_revision=job["source_revision"],
|
| 751 |
+
)
|
| 752 |
+
if record is None:
|
| 753 |
+
out.append(("", drop, sample))
|
| 754 |
+
else:
|
| 755 |
+
out.append((str(record["entry_cid"]), "", record.get("source_id")))
|
| 756 |
+
return out
|
| 757 |
+
|
| 758 |
+
|
| 759 |
+
def build_corpus(
|
| 760 |
+
laws: pd.DataFrame,
|
| 761 |
+
articles: pd.DataFrame,
|
| 762 |
+
source_meta: dict[str, Any],
|
| 763 |
+
*,
|
| 764 |
+
cid_only: bool = False,
|
| 765 |
+
cid_workers: int | None = None,
|
| 766 |
+
) -> tuple[pd.DataFrame, dict[str, Any]]:
|
| 767 |
+
source_dataset = source_meta["source_dataset"]
|
| 768 |
+
source_revision = source_meta["source_revision"]
|
| 769 |
+
law_map = laws_index(laws, source_dataset)
|
| 770 |
+
articles_empty = articles is None or articles.empty
|
| 771 |
+
n_laws = int(len(laws))
|
| 772 |
+
n_arts = int(len(articles) if articles is not None else 0)
|
| 773 |
+
article_law_coverage = (n_arts / n_laws) if n_laws else 0.0
|
| 774 |
+
# Empty articles.parquet already falls back. Also fall back when the table is
|
| 775 |
+
# present but covers under ~10% as many rows as laws (Estonia: 2 vs 3484).
|
| 776 |
+
sparse_fallback = (not articles_empty) and article_law_coverage < 0.10
|
| 777 |
+
use_articles = (not articles_empty) and not sparse_fallback
|
| 778 |
+
|
| 779 |
+
extraction_statuses: Counter[str] = Counter()
|
| 780 |
+
for parent in law_map.values():
|
| 781 |
+
st = normalize_text(parent["metadata"].get("article_extraction_status") or "")
|
| 782 |
+
if st:
|
| 783 |
+
extraction_statuses[st] += 1
|
| 784 |
+
|
| 785 |
+
report: dict[str, Any] = {
|
| 786 |
+
"source_dataset": source_dataset,
|
| 787 |
+
"source_revision": source_revision,
|
| 788 |
+
"laws_sha256": source_meta.get("laws_sha256"),
|
| 789 |
+
"articles_sha256": source_meta.get("articles_sha256"),
|
| 790 |
+
"n_laws_in": int(len(laws)),
|
| 791 |
+
"n_articles_in": int(len(articles) if articles is not None else 0),
|
| 792 |
+
"unit": "article" if use_articles else "law",
|
| 793 |
+
"article_law_coverage": article_law_coverage,
|
| 794 |
+
"sparse_article_fallback": sparse_fallback,
|
| 795 |
+
"drops": {
|
| 796 |
+
"empty_body": 0,
|
| 797 |
+
"missing_instrument": 0,
|
| 798 |
+
"duplicate_cid": 0,
|
| 799 |
+
"duplicate_source_kept_first": 0,
|
| 800 |
+
},
|
| 801 |
+
"drop_samples": {
|
| 802 |
+
"empty_body": [],
|
| 803 |
+
"missing_instrument": [],
|
| 804 |
+
"duplicate_cid": [],
|
| 805 |
+
},
|
| 806 |
+
"language_breakdown": {},
|
| 807 |
+
"quality_flags": {},
|
| 808 |
+
"schema_surprises": list(source_meta.get("schema_surprises") or []),
|
| 809 |
+
"n_out": 0,
|
| 810 |
+
"never_invented_legal_text": True,
|
| 811 |
+
"n_reconstructed_parents": 0,
|
| 812 |
+
"n_reconstructed_truncated": 0,
|
| 813 |
+
"n_reconstructed_stubs": 0,
|
| 814 |
+
"n_empty_parents_with_articles_not_reconstructed": 0,
|
| 815 |
+
"n_thin_instruments_replaced": 0,
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
entries: list[dict[str, Any]] = []
|
| 819 |
+
cid_seen: set[str] = set()
|
| 820 |
+
n_emitted = 0
|
| 821 |
+
|
| 822 |
+
def _keep(rec: dict[str, Any]) -> None:
|
| 823 |
+
nonlocal n_emitted
|
| 824 |
+
if not cid_only:
|
| 825 |
+
entries.append(rec)
|
| 826 |
+
return
|
| 827 |
+
n_emitted += 1
|
| 828 |
+
cid = str(rec.get("entry_cid") or "")
|
| 829 |
+
if not cid:
|
| 830 |
+
return
|
| 831 |
+
if cid in cid_seen:
|
| 832 |
+
report["drops"]["duplicate_cid"] += 1
|
| 833 |
+
report["drops"]["duplicate_source_kept_first"] += 1
|
| 834 |
+
if len(report["drop_samples"]["duplicate_cid"]) < 20:
|
| 835 |
+
report["drop_samples"]["duplicate_cid"].append(rec.get("source_id"))
|
| 836 |
+
return
|
| 837 |
+
cid_seen.add(cid)
|
| 838 |
+
|
| 839 |
+
slug = ""
|
| 840 |
+
if source_dataset.startswith("endomorphosis/ipfs_") and source_dataset.endswith("_laws"):
|
| 841 |
+
slug = source_dataset.split("ipfs_", 1)[1].removesuffix("_laws")
|
| 842 |
+
|
| 843 |
+
children_by_law: dict[str, list[dict[str, Any]]] = {}
|
| 844 |
+
if not articles_empty:
|
| 845 |
+
for _, row in articles.iterrows():
|
| 846 |
+
lid = _row_get(row, "law_id")
|
| 847 |
+
if not lid:
|
| 848 |
+
continue
|
| 849 |
+
children_by_law.setdefault(lid, []).append(
|
| 850 |
+
{
|
| 851 |
+
"id": _row_get(row, "id"),
|
| 852 |
+
"title": _row_get(row, "title"),
|
| 853 |
+
"article_number": _row_get(row, "article_number"),
|
| 854 |
+
"body": _row_get(row, "text"),
|
| 855 |
+
"row": row,
|
| 856 |
+
}
|
| 857 |
+
)
|
| 858 |
+
|
| 859 |
+
reconstructed_ids: set[str] = set()
|
| 860 |
+
running_extra_bytes = 0
|
| 861 |
+
|
| 862 |
+
def _append_law_row(
|
| 863 |
+
instrument_id: str,
|
| 864 |
+
parent: dict[str, Any],
|
| 865 |
+
recon=None,
|
| 866 |
+
) -> None:
|
| 867 |
+
body = parent["body"]
|
| 868 |
+
recon_extra: dict[str, Any] = {}
|
| 869 |
+
coverage = _coverage_from(
|
| 870 |
+
parent["row"],
|
| 871 |
+
parent["metadata"],
|
| 872 |
+
articles_empty=articles_empty,
|
| 873 |
+
sparse_fallback=sparse_fallback,
|
| 874 |
+
)
|
| 875 |
+
if recon is not None and recon.reconstructed_from_articles:
|
| 876 |
+
body = recon.body
|
| 877 |
+
recon_extra = recon.extra_fields()
|
| 878 |
+
coverage = f"{coverage}; reconstructed_from_articles"
|
| 879 |
+
if not body:
|
| 880 |
+
kids = children_by_law.get(instrument_id) or []
|
| 881 |
+
# Article rows that normalize to nothing are not recoverable text.
|
| 882 |
+
if any(str(kid.get("body") or "").strip() for kid in kids):
|
| 883 |
+
report["n_empty_parents_with_articles_not_reconstructed"] += 1
|
| 884 |
+
report["drops"]["empty_body"] += 1
|
| 885 |
+
if len(report["drop_samples"]["empty_body"]) < 20:
|
| 886 |
+
report["drop_samples"]["empty_body"].append(instrument_id)
|
| 887 |
+
return
|
| 888 |
+
meta = parent["metadata"]
|
| 889 |
+
_keep(
|
| 890 |
+
_base_record(
|
| 891 |
+
record_type=_instrument_record_type(
|
| 892 |
+
meta,
|
| 893 |
+
parent["instrument_title"],
|
| 894 |
+
text=body,
|
| 895 |
+
source_url=str(parent.get("source_url") or ""),
|
| 896 |
+
language=str(parent.get("language") or ""),
|
| 897 |
+
),
|
| 898 |
+
source_dataset=source_dataset,
|
| 899 |
+
source_revision=source_revision,
|
| 900 |
+
instrument_id=instrument_id,
|
| 901 |
+
instrument_title=parent["instrument_title"],
|
| 902 |
+
law_cid=parent["law_cid"],
|
| 903 |
+
article_number="",
|
| 904 |
+
article_title="",
|
| 905 |
+
body=body,
|
| 906 |
+
jurisdiction=parent["jurisdiction"],
|
| 907 |
+
language=parent["language"],
|
| 908 |
+
source_url=parent["source_url"],
|
| 909 |
+
snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
|
| 910 |
+
coverage=coverage,
|
| 911 |
+
license_expr=parent["license"],
|
| 912 |
+
collector=_collector(meta, source_dataset),
|
| 913 |
+
source_id=instrument_id,
|
| 914 |
+
extra={
|
| 915 |
+
"eli": parent["eli"],
|
| 916 |
+
"identifier": parent["identifier"],
|
| 917 |
+
"official_identifier": parent["official_identifier"],
|
| 918 |
+
"source_type": parent["source_type"],
|
| 919 |
+
"country": parent["country"],
|
| 920 |
+
"law_status": parent["law_status"],
|
| 921 |
+
"parent_law_id": "",
|
| 922 |
+
"article_id": "",
|
| 923 |
+
"reconstructed_from_articles": False,
|
| 924 |
+
**_hierarchy_fields(
|
| 925 |
+
parent["instrument_title"], body, "", language=parent["language"]
|
| 926 |
+
),
|
| 927 |
+
**recon_extra,
|
| 928 |
+
},
|
| 929 |
+
)
|
| 930 |
+
)
|
| 931 |
+
|
| 932 |
+
if sparse_fallback:
|
| 933 |
+
report["schema_surprises"].append(
|
| 934 |
+
f"article coverage {article_law_coverage:.4f} < 0.10 of laws; falling back to law-level units"
|
| 935 |
+
)
|
| 936 |
+
|
| 937 |
+
for instrument_id, parent in law_map.items():
|
| 938 |
+
kids = children_by_law.get(instrument_id) or []
|
| 939 |
+
recon = None
|
| 940 |
+
if reconstruct_on() and parent_needs_reconstruct(parent["body"], len(kids)):
|
| 941 |
+
recon = reconstruct_parent(
|
| 942 |
+
slug=slug,
|
| 943 |
+
parent_body=parent["body"],
|
| 944 |
+
parent_title=parent["instrument_title"],
|
| 945 |
+
children=[
|
| 946 |
+
{
|
| 947 |
+
"id": k["id"],
|
| 948 |
+
"title": k["title"],
|
| 949 |
+
"article_number": k["article_number"],
|
| 950 |
+
"body": k["body"],
|
| 951 |
+
}
|
| 952 |
+
for k in kids
|
| 953 |
+
],
|
| 954 |
+
running_extra_bytes=running_extra_bytes,
|
| 955 |
+
sha256_hex=sha256_hex,
|
| 956 |
+
)
|
| 957 |
+
running_extra_bytes += recon.extra_bytes
|
| 958 |
+
reconstructed_ids.add(instrument_id)
|
| 959 |
+
report["n_reconstructed_parents"] += 1
|
| 960 |
+
if recon.reconstruction_truncated:
|
| 961 |
+
report["n_reconstructed_truncated"] += 1
|
| 962 |
+
if recon.is_stub:
|
| 963 |
+
report["n_reconstructed_stubs"] += 1
|
| 964 |
+
_append_law_row(instrument_id, parent, recon)
|
| 965 |
+
|
| 966 |
+
emit_articles = use_articles or bool(reconstructed_ids)
|
| 967 |
+
skip_body_split = emit_articles
|
| 968 |
+
sibling_titles = {
|
| 969 |
+
instrument_id: {_compact_line(kid["title"]) for kid in kids}
|
| 970 |
+
for instrument_id, kids in children_by_law.items()
|
| 971 |
+
}
|
| 972 |
+
promoted: dict[str, list[Any]] = {}
|
| 973 |
+
if emit_articles:
|
| 974 |
+
for instrument_id, parent in law_map.items():
|
| 975 |
+
kids = children_by_law.get(instrument_id) or []
|
| 976 |
+
if not _needs_parent_split(kids, parent["body"]):
|
| 977 |
+
continue
|
| 978 |
+
units = split_structured_units(parent["body"], language=parent["language"])
|
| 979 |
+
covered = sum(len(unit.body) for unit in units)
|
| 980 |
+
if len(units) >= 2 and covered >= int(0.35 * len(parent["body"])):
|
| 981 |
+
promoted[instrument_id] = units
|
| 982 |
+
if promoted:
|
| 983 |
+
report["n_thin_instruments_replaced"] = len(promoted)
|
| 984 |
+
report["schema_surprises"].append(
|
| 985 |
+
"parent headings used for "
|
| 986 |
+
f"{len(promoted)} instruments whose article rows were missing or thin"
|
| 987 |
+
)
|
| 988 |
+
|
| 989 |
+
workers = 1
|
| 990 |
+
if emit_articles:
|
| 991 |
+
def _note_drop(drop: str, sample: Any) -> None:
|
| 992 |
+
if not drop:
|
| 993 |
+
return
|
| 994 |
+
report["drops"][drop] += 1
|
| 995 |
+
if sample is not None and len(report["drop_samples"][drop]) < 20:
|
| 996 |
+
report["drop_samples"][drop].append(sample)
|
| 997 |
+
|
| 998 |
+
def _take(record: dict[str, Any] | None, drop: str, sample: Any) -> None:
|
| 999 |
+
if drop:
|
| 1000 |
+
_note_drop(drop, sample)
|
| 1001 |
+
return
|
| 1002 |
+
if record is not None:
|
| 1003 |
+
_keep(record)
|
| 1004 |
+
|
| 1005 |
+
outcome_kwargs = {
|
| 1006 |
+
"law_map": law_map,
|
| 1007 |
+
"promoted": promoted,
|
| 1008 |
+
"sibling_titles": sibling_titles,
|
| 1009 |
+
"source_meta": source_meta,
|
| 1010 |
+
"source_dataset": source_dataset,
|
| 1011 |
+
"source_revision": source_revision,
|
| 1012 |
+
}
|
| 1013 |
+
workers = _cid_worker_count(int(len(articles)), cid_workers) if cid_only else 1
|
| 1014 |
+
if workers > 1 and len(articles):
|
| 1015 |
+
import multiprocessing as mp
|
| 1016 |
+
|
| 1017 |
+
_CID_JOB.clear()
|
| 1018 |
+
_CID_JOB.update({"articles": articles, **outcome_kwargs})
|
| 1019 |
+
span = 4000
|
| 1020 |
+
spans = [
|
| 1021 |
+
(start, min(start + span, int(len(articles))))
|
| 1022 |
+
for start in range(0, int(len(articles)), span)
|
| 1023 |
+
]
|
| 1024 |
+
ctx = mp.get_context("fork")
|
| 1025 |
+
with ctx.Pool(workers) as pool:
|
| 1026 |
+
for batch in pool.imap_unordered(_cid_article_span, spans, chunksize=1):
|
| 1027 |
+
for cid, drop, sample in batch:
|
| 1028 |
+
if drop:
|
| 1029 |
+
_note_drop(drop, sample)
|
| 1030 |
+
elif cid:
|
| 1031 |
+
_keep({"entry_cid": cid, "source_id": sample})
|
| 1032 |
+
_CID_JOB.clear()
|
| 1033 |
+
else:
|
| 1034 |
+
for _, row in articles.iterrows():
|
| 1035 |
+
_take(*_article_outcome(row, **outcome_kwargs))
|
| 1036 |
+
for instrument_id, units in promoted.items():
|
| 1037 |
+
parent = law_map[instrument_id]
|
| 1038 |
+
meta = parent["metadata"]
|
| 1039 |
+
report["unit"] = "structured"
|
| 1040 |
+
instrument_type = _instrument_record_type(
|
| 1041 |
+
meta,
|
| 1042 |
+
parent["instrument_title"],
|
| 1043 |
+
text=str(parent.get("body") or ""),
|
| 1044 |
+
source_url=str(parent.get("source_url") or ""),
|
| 1045 |
+
language=str(parent.get("language") or ""),
|
| 1046 |
+
)
|
| 1047 |
+
for unit in units:
|
| 1048 |
+
_keep(
|
| 1049 |
+
_base_record(
|
| 1050 |
+
record_type=_unit_record_type(
|
| 1051 |
+
unit,
|
| 1052 |
+
instrument_type,
|
| 1053 |
+
n_units=len(units),
|
| 1054 |
+
parent_body=parent["body"],
|
| 1055 |
+
),
|
| 1056 |
+
source_dataset=source_dataset,
|
| 1057 |
+
source_revision=source_revision,
|
| 1058 |
+
instrument_id=instrument_id,
|
| 1059 |
+
instrument_title=parent["instrument_title"],
|
| 1060 |
+
law_cid=parent["law_cid"],
|
| 1061 |
+
article_number=unit.article_number or unit.number,
|
| 1062 |
+
article_title=unit.heading,
|
| 1063 |
+
body=unit.body,
|
| 1064 |
+
jurisdiction=parent["jurisdiction"],
|
| 1065 |
+
language=parent["language"],
|
| 1066 |
+
source_url=parent["source_url"],
|
| 1067 |
+
snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
|
| 1068 |
+
coverage="structured (thin article rows replaced from the parent law)",
|
| 1069 |
+
license_expr=parent["license"],
|
| 1070 |
+
collector=_collector(meta, source_dataset),
|
| 1071 |
+
source_id=f"{instrument_id}-{unit.kind}-{unit.number}",
|
| 1072 |
+
extra={
|
| 1073 |
+
"eli": parent["eli"],
|
| 1074 |
+
"identifier": parent["identifier"],
|
| 1075 |
+
"official_identifier": parent["official_identifier"],
|
| 1076 |
+
"source_type": parent["source_type"],
|
| 1077 |
+
"country": parent["country"],
|
| 1078 |
+
"law_status": parent["law_status"],
|
| 1079 |
+
"parent_law_id": instrument_id,
|
| 1080 |
+
"article_id": "",
|
| 1081 |
+
"hierarchy_kind": unit.kind,
|
| 1082 |
+
"hierarchy_path": unit.hierarchy_path,
|
| 1083 |
+
"title_number": unit.title_number,
|
| 1084 |
+
"chapter_number": unit.chapter_number,
|
| 1085 |
+
"part_number": unit.part_number,
|
| 1086 |
+
"section_number": unit.section_number,
|
| 1087 |
+
"subsections": list(unit.subsections),
|
| 1088 |
+
},
|
| 1089 |
+
)
|
| 1090 |
+
)
|
| 1091 |
+
elif not skip_body_split:
|
| 1092 |
+
for instrument_id, parent in law_map.items():
|
| 1093 |
+
body = parent["body"]
|
| 1094 |
+
if not body:
|
| 1095 |
+
continue
|
| 1096 |
+
meta = parent["metadata"]
|
| 1097 |
+
units = split_structured_units(body, language=parent["language"])
|
| 1098 |
+
if units:
|
| 1099 |
+
report["unit"] = "structured"
|
| 1100 |
+
instrument_type = _instrument_record_type(
|
| 1101 |
+
meta,
|
| 1102 |
+
parent["instrument_title"],
|
| 1103 |
+
text=body,
|
| 1104 |
+
source_url=str(parent.get("source_url") or ""),
|
| 1105 |
+
language=str(parent.get("language") or ""),
|
| 1106 |
+
)
|
| 1107 |
+
for unit in units:
|
| 1108 |
+
_keep(
|
| 1109 |
+
_base_record(
|
| 1110 |
+
record_type=_unit_record_type(
|
| 1111 |
+
unit,
|
| 1112 |
+
instrument_type,
|
| 1113 |
+
n_units=len(units),
|
| 1114 |
+
parent_body=body,
|
| 1115 |
+
),
|
| 1116 |
+
source_dataset=source_dataset,
|
| 1117 |
+
source_revision=source_revision,
|
| 1118 |
+
instrument_id=instrument_id,
|
| 1119 |
+
instrument_title=parent["instrument_title"],
|
| 1120 |
+
law_cid=parent["law_cid"],
|
| 1121 |
+
article_number=unit.article_number or unit.number,
|
| 1122 |
+
article_title=unit.heading,
|
| 1123 |
+
body=unit.body,
|
| 1124 |
+
jurisdiction=parent["jurisdiction"],
|
| 1125 |
+
language=parent["language"],
|
| 1126 |
+
source_url=parent["source_url"],
|
| 1127 |
+
snapshot_date=_snapshot_date(parent["row"], meta, source_meta),
|
| 1128 |
+
coverage="structured (headings detected in law body)",
|
| 1129 |
+
license_expr=parent["license"],
|
| 1130 |
+
collector=_collector(meta, source_dataset),
|
| 1131 |
+
source_id=f"{instrument_id}-{unit.kind}-{unit.number}",
|
| 1132 |
+
extra={
|
| 1133 |
+
"eli": parent["eli"],
|
| 1134 |
+
"identifier": parent["identifier"],
|
| 1135 |
+
"official_identifier": parent["official_identifier"],
|
| 1136 |
+
"source_type": parent["source_type"],
|
| 1137 |
+
"country": parent["country"],
|
| 1138 |
+
"law_status": parent["law_status"],
|
| 1139 |
+
"parent_law_id": instrument_id,
|
| 1140 |
+
"article_id": "",
|
| 1141 |
+
"hierarchy_kind": unit.kind,
|
| 1142 |
+
"hierarchy_path": unit.hierarchy_path,
|
| 1143 |
+
"title_number": unit.title_number,
|
| 1144 |
+
"chapter_number": unit.chapter_number,
|
| 1145 |
+
"part_number": unit.part_number,
|
| 1146 |
+
"section_number": unit.section_number,
|
| 1147 |
+
"subsections": list(unit.subsections),
|
| 1148 |
+
},
|
| 1149 |
+
)
|
| 1150 |
+
)
|
| 1151 |
+
|
| 1152 |
+
if cid_only:
|
| 1153 |
+
# The set comparison only needs entry_cid. Bodies stay in the source
|
| 1154 |
+
# frame and are not copied into a second corpus of Python dicts.
|
| 1155 |
+
report["cid_only"] = True
|
| 1156 |
+
report["cid_workers"] = workers
|
| 1157 |
+
report["n_before_dedupe"] = n_emitted
|
| 1158 |
+
report["n_out"] = len(cid_seen)
|
| 1159 |
+
report["n_dropped_total"] = (
|
| 1160 |
+
report["drops"]["empty_body"]
|
| 1161 |
+
+ report["drops"]["missing_instrument"]
|
| 1162 |
+
+ report["drops"]["duplicate_cid"]
|
| 1163 |
+
)
|
| 1164 |
+
frame = pd.DataFrame({"entry_cid": sorted(cid_seen)})
|
| 1165 |
+
frame.attrs["normalization_report"] = report
|
| 1166 |
+
return frame, report
|
| 1167 |
+
|
| 1168 |
+
entries.sort(
|
| 1169 |
+
key=lambda r: (
|
| 1170 |
+
r["instrument_id"],
|
| 1171 |
+
article_sort_key(r.get("article_number") or "", r["source_id"]),
|
| 1172 |
+
)
|
| 1173 |
+
)
|
| 1174 |
+
n_before = len(entries)
|
| 1175 |
+
seen: set[str] = set()
|
| 1176 |
+
deduped: list[dict[str, Any]] = []
|
| 1177 |
+
for rec in entries:
|
| 1178 |
+
cid = rec["entry_cid"]
|
| 1179 |
+
if cid in seen:
|
| 1180 |
+
report["drops"]["duplicate_cid"] += 1
|
| 1181 |
+
report["drops"]["duplicate_source_kept_first"] += 1
|
| 1182 |
+
if len(report["drop_samples"]["duplicate_cid"]) < 20:
|
| 1183 |
+
report["drop_samples"]["duplicate_cid"].append(rec["source_id"])
|
| 1184 |
+
continue
|
| 1185 |
+
seen.add(cid)
|
| 1186 |
+
deduped.append(rec)
|
| 1187 |
+
for i, rec in enumerate(deduped):
|
| 1188 |
+
rec["document_index"] = i
|
| 1189 |
+
rec["corpus_index"] = i
|
| 1190 |
+
|
| 1191 |
+
df = pd.DataFrame(deduped)
|
| 1192 |
+
if not df.empty and df["entry_cid"].duplicated().any():
|
| 1193 |
+
raise SchemaError("Duplicate entry_cid remained after dedupe")
|
| 1194 |
+
report["n_before_dedupe"] = n_before
|
| 1195 |
+
report["n_out"] = int(len(df))
|
| 1196 |
+
if not df.empty and "record_type" in df.columns:
|
| 1197 |
+
n_law_rows = int((df["record_type"] == "law").sum())
|
| 1198 |
+
n_child_rows = int(df["record_type"].isin(["article", "section"]).sum())
|
| 1199 |
+
report["n_law_rows"] = n_law_rows
|
| 1200 |
+
report["n_child_rows"] = n_child_rows
|
| 1201 |
+
report["n_instruments"] = int(df["instrument_id"].nunique()) if "instrument_id" in df.columns else n_law_rows
|
| 1202 |
+
if n_law_rows and n_child_rows:
|
| 1203 |
+
report["unit"] = (
|
| 1204 |
+
"law+structured" if report.get("unit") == "structured" else "law+article"
|
| 1205 |
+
)
|
| 1206 |
+
elif n_law_rows:
|
| 1207 |
+
report["unit"] = "law"
|
| 1208 |
+
elif n_child_rows:
|
| 1209 |
+
report["unit"] = "article"
|
| 1210 |
+
report["n_dropped_total"] = (
|
| 1211 |
+
report["drops"]["empty_body"]
|
| 1212 |
+
+ report["drops"]["missing_instrument"]
|
| 1213 |
+
+ report["drops"]["duplicate_cid"]
|
| 1214 |
+
)
|
| 1215 |
+
if not df.empty:
|
| 1216 |
+
report["language_breakdown"] = {
|
| 1217 |
+
str(k): int(v) for k, v in df["language"].fillna("").value_counts().items()
|
| 1218 |
+
}
|
| 1219 |
+
report["record_type_breakdown"] = {
|
| 1220 |
+
str(k): int(v) for k, v in df["record_type"].value_counts().items()
|
| 1221 |
+
}
|
| 1222 |
+
report["jurisdiction_breakdown"] = {
|
| 1223 |
+
str(k): int(v) for k, v in df["jurisdiction"].fillna("").value_counts().items()
|
| 1224 |
+
}
|
| 1225 |
+
snapshot_dates = sorted({str(x) for x in df["snapshot_date"].fillna("") if str(x)})
|
| 1226 |
+
report["snapshot_dates"] = snapshot_dates
|
| 1227 |
+
else:
|
| 1228 |
+
report["language_breakdown"] = {}
|
| 1229 |
+
report["record_type_breakdown"] = {}
|
| 1230 |
+
report["jurisdiction_breakdown"] = {}
|
| 1231 |
+
report["snapshot_dates"] = []
|
| 1232 |
+
|
| 1233 |
+
all_article_count_zero = False
|
| 1234 |
+
if "article_count" in laws.columns and len(laws):
|
| 1235 |
+
try:
|
| 1236 |
+
all_article_count_zero = int((laws["article_count"].fillna(0) == 0).sum()) == len(laws)
|
| 1237 |
+
except Exception:
|
| 1238 |
+
all_article_count_zero = False
|
| 1239 |
+
|
| 1240 |
+
report["quality_flags"] = {
|
| 1241 |
+
"articles_table_empty": bool(articles_empty),
|
| 1242 |
+
"sparse_article_fallback": bool(sparse_fallback),
|
| 1243 |
+
"article_law_coverage": article_law_coverage,
|
| 1244 |
+
"all_source_article_counts_zero": all_article_count_zero,
|
| 1245 |
+
"article_extraction_status_counts": dict(extraction_statuses),
|
| 1246 |
+
"missing_date": bool("date" in laws.columns and laws["date"].isna().all()) if len(laws) else False,
|
| 1247 |
+
"missing_date_issued": bool("date_issued" in laws.columns and laws["date_issued"].isna().all()) if len(laws) else False,
|
| 1248 |
+
"eli_present": bool("eli" in laws.columns and laws["eli"].notna().any()) if len(laws) else False,
|
| 1249 |
+
"never_invented_legal_text": True,
|
| 1250 |
+
"empty_bodies_dropped": report["drops"]["empty_body"],
|
| 1251 |
+
"duplicate_cids_dropped": report["drops"]["duplicate_cid"],
|
| 1252 |
+
}
|
| 1253 |
+
from .profiles import majority_language, score_heading_languages
|
| 1254 |
+
|
| 1255 |
+
sample_text = ""
|
| 1256 |
+
if not df.empty and "body" in df.columns:
|
| 1257 |
+
sample_text = "\n".join(str(x) for x in df["body"].head(40).tolist())
|
| 1258 |
+
if "title" in df.columns:
|
| 1259 |
+
sample_text = "\n".join(str(x) for x in df["title"].head(40).tolist()) + "\n" + sample_text
|
| 1260 |
+
heading_langs = score_heading_languages(sample_text)
|
| 1261 |
+
report["heading_language_counts"] = dict(heading_langs)
|
| 1262 |
+
report["heading_language_majority"] = majority_language(heading_langs)
|
| 1263 |
+
report["document_language_majority"] = None
|
| 1264 |
+
if report.get("language_breakdown"):
|
| 1265 |
+
report["document_language_majority"] = max(
|
| 1266 |
+
report["language_breakdown"].items(), key=lambda kv: kv[1]
|
| 1267 |
+
)[0]
|
| 1268 |
+
from .verify import verify_normalized_corpus
|
| 1269 |
+
|
| 1270 |
+
report["verification"] = verify_normalized_corpus(df, report)
|
| 1271 |
+
df.attrs["normalization_report"] = report
|
| 1272 |
+
return df, report
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/normalize_loop.py
ADDED
|
@@ -0,0 +1,621 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Improve the row normalizer, then let that script normalize every row.
|
| 2 |
+
|
| 3 |
+
``scan`` and ``apply`` only call ``normalize_legal_text``. They do not import
|
| 4 |
+
the LLM router, so one subprocess per country does not boot a model.
|
| 5 |
+
|
| 6 |
+
``improve`` imports ``llm_router`` once. Each pass sends a short batch of
|
| 7 |
+
lines the current script still leaves in place. The model proposes whole-line
|
| 8 |
+
patterns. A pattern is stored only when it matches one of those lines, misses
|
| 9 |
+
every held-out legal sentence, and the script then actually drops the line.
|
| 10 |
+
Accepted patterns live in ``data/learned_line_patterns.json`` and are applied
|
| 11 |
+
by the same script that normalizes the rows. The model never rewrites a row.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import hashlib
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
from collections import Counter
|
| 21 |
+
from concurrent.futures import ProcessPoolExecutor, as_completed
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
from typing import Any, Callable, Sequence
|
| 24 |
+
|
| 25 |
+
from .catalog import EXCLUDED_SLUGS
|
| 26 |
+
from .structure import learned_patterns_path, normalize_legal_text
|
| 27 |
+
|
| 28 |
+
GenerateText = Callable[[str], str]
|
| 29 |
+
|
| 30 |
+
# Sentences the learned rules must not delete. Whole-line patterns that
|
| 31 |
+
# full-match any of these are discarded.
|
| 32 |
+
KEEP_LINES = (
|
| 33 |
+
"Article 1 The present Act applies throughout the territory and binds every person.",
|
| 34 |
+
"The court in Malawi shall apply the Public Roads Act throughout the territory.",
|
| 35 |
+
"2. Amendment of section 5 of Cap. 122A",
|
| 36 |
+
"publié au Journal Officiel et entre en vigueur sur tout le territoire.",
|
| 37 |
+
"10 dicembre 1948",
|
| 38 |
+
"Quarta-Feira de Cinzas continua a ser feriado nacional.",
|
| 39 |
+
"Phone: +1 202 555 0100 is the number appointed under this section.",
|
| 40 |
+
"Troubleshoot faulty system.",
|
| 41 |
+
"100 GENERAL PROVISIONS",
|
| 42 |
+
"applicable rule applies throughout the territory.",
|
| 43 |
+
"The register is published at www.example.com for public inspection under this Act.",
|
| 44 |
+
"بسم الله الرحمن الرحيم",
|
| 45 |
+
"Done at Brussels, 25 June 1999.",
|
| 46 |
+
"2",
|
| 47 |
+
"10",
|
| 48 |
+
"published in the Gazette.",
|
| 49 |
+
"Gazetted 1 October 2009",
|
| 50 |
+
"Lycée : séries ES, L et S",
|
| 51 |
+
"au Journal Officiel",
|
| 52 |
+
"Subs. ibid., for “local official Gazette”.",
|
| 53 |
+
"(a) books (excluding printed music and periodicals) ;",
|
| 54 |
+
"Act 19 Copyright and Neighbouring Rights Act 2006",
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
# One local-model window is 1024 tokens. Keep the prompt well under that.
|
| 58 |
+
PROMPT_CHAR_BUDGET = 1600
|
| 59 |
+
_PROMPT_PREFIX = (
|
| 60 |
+
"These lines survived legal-text normalization. "
|
| 61 |
+
'Propose JSON only: {"line_patterns": ["^...$"]}. '
|
| 62 |
+
"Each pattern must match one whole chrome line (page header, site footer, "
|
| 63 |
+
"printer stamp) and must not match a legal sentence. Do not write legal text. "
|
| 64 |
+
'If none are safe, return {"line_patterns": []}.\n'
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def cache_packs(cache_dir: Path, slug: str | None = None) -> list[tuple[str, Path]]:
|
| 69 |
+
packs: list[tuple[str, Path]] = []
|
| 70 |
+
for path in sorted(cache_dir.glob("*_corpus.parquet")):
|
| 71 |
+
name = path.name[: -len("_corpus.parquet")]
|
| 72 |
+
if name in EXCLUDED_SLUGS or not name:
|
| 73 |
+
continue
|
| 74 |
+
if slug is not None and name != slug:
|
| 75 |
+
continue
|
| 76 |
+
packs.append((name, path))
|
| 77 |
+
return packs
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
_HEADING_LINE = re.compile(
|
| 81 |
+
r"(?i)^(article|art\.|section|chapter|part|subtopic|§)\b"
|
| 82 |
+
)
|
| 83 |
+
_CHROME_HINT = re.compile(
|
| 84 |
+
r"(?i)(translated|serial number|copyright|gazette|https?://|www\.|"
|
| 85 |
+
r"\bpage\b|printed|journal officiel|série|series\b)"
|
| 86 |
+
)
|
| 87 |
+
# Repeated lines that are still the law, not a banner. The router must not see them.
|
| 88 |
+
_PROVISION_LINE = re.compile(
|
| 89 |
+
r"(?i)(publi[eé]|lycée|lycee|newspaper|days after|série cei|série en |"
|
| 90 |
+
r"\bshall\b|\bmust\b|inserted sig|the gazette\.$|in the gazette\.$|"
|
| 91 |
+
r"\bgazetted\b|\bau journal officiel\b|subs\.\s*ibid|"
|
| 92 |
+
r"excluding printed|whether or not printed|neighbouring rights|"
|
| 93 |
+
r"série de classe|note de bas de page|communaut[eé]s europ)"
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def scan_pack(path: Path, *, sample_lines: int = 40) -> dict[str, Any]:
|
| 98 |
+
"""Count rows and keep the repeated short lines the script did not remove."""
|
| 99 |
+
import pyarrow.parquet as pq
|
| 100 |
+
|
| 101 |
+
pf = pq.ParquetFile(path)
|
| 102 |
+
if "body" not in set(pf.schema_arrow.names):
|
| 103 |
+
raise ValueError(f"{path.name} has no body column")
|
| 104 |
+
short: Counter[str] = Counter()
|
| 105 |
+
n = 0
|
| 106 |
+
n_changed = 0
|
| 107 |
+
n_unstable = 0
|
| 108 |
+
for batch in pf.iter_batches(batch_size=512, columns=["body"]):
|
| 109 |
+
for body in batch.column("body").to_pylist():
|
| 110 |
+
if body is None:
|
| 111 |
+
continue
|
| 112 |
+
original = body if isinstance(body, str) else str(body)
|
| 113 |
+
n += 1
|
| 114 |
+
normalized = normalize_legal_text(original)
|
| 115 |
+
if normalized != original:
|
| 116 |
+
n_changed += 1
|
| 117 |
+
if normalize_legal_text(normalized) != normalized:
|
| 118 |
+
n_unstable += 1
|
| 119 |
+
for line in normalized.splitlines():
|
| 120 |
+
stripped = line.strip()
|
| 121 |
+
if not stripped or len(stripped) > 60 or _HEADING_LINE.match(stripped):
|
| 122 |
+
continue
|
| 123 |
+
if not _CHROME_HINT.search(stripped):
|
| 124 |
+
continue
|
| 125 |
+
if stripped in short or len(short) < 20000:
|
| 126 |
+
short[stripped] += 1
|
| 127 |
+
leftovers = [
|
| 128 |
+
{"line": line, "count": count}
|
| 129 |
+
for line, count in short.most_common(sample_lines)
|
| 130 |
+
if count >= 3
|
| 131 |
+
]
|
| 132 |
+
return {
|
| 133 |
+
"n": n,
|
| 134 |
+
"n_changed": n_changed,
|
| 135 |
+
"n_unstable": n_unstable,
|
| 136 |
+
"leftovers": leftovers,
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def apply_pack(path: Path, out_path: Path) -> dict[str, Any]:
|
| 141 |
+
"""Rewrite every body with the current script. No model is loaded."""
|
| 142 |
+
import pyarrow as pa
|
| 143 |
+
import pyarrow.parquet as pq
|
| 144 |
+
|
| 145 |
+
pf = pq.ParquetFile(path)
|
| 146 |
+
if "body" not in set(pf.schema_arrow.names):
|
| 147 |
+
raise ValueError(f"{path.name} has no body column")
|
| 148 |
+
out_path.parent.mkdir(parents=True, exist_ok=True)
|
| 149 |
+
tmp = out_path.with_suffix(out_path.suffix + ".partial")
|
| 150 |
+
writer = pq.ParquetWriter(tmp, pf.schema_arrow)
|
| 151 |
+
n = 0
|
| 152 |
+
n_changed = 0
|
| 153 |
+
try:
|
| 154 |
+
for batch in pf.iter_batches(batch_size=256):
|
| 155 |
+
bodies = batch.column("body").to_pylist()
|
| 156 |
+
rewritten: list[Any] = []
|
| 157 |
+
for body in bodies:
|
| 158 |
+
if body is None:
|
| 159 |
+
rewritten.append(None)
|
| 160 |
+
continue
|
| 161 |
+
original = body if isinstance(body, str) else str(body)
|
| 162 |
+
n += 1
|
| 163 |
+
normalized = normalize_legal_text(original)
|
| 164 |
+
if normalized != original:
|
| 165 |
+
n_changed += 1
|
| 166 |
+
rewritten.append(normalized)
|
| 167 |
+
index = batch.schema.get_field_index("body")
|
| 168 |
+
arrays = [batch.column(i) for i in range(batch.num_columns)]
|
| 169 |
+
arrays[index] = pa.array(rewritten, type=batch.schema.field("body").type)
|
| 170 |
+
writer.write_batch(pa.record_batch(arrays, schema=batch.schema))
|
| 171 |
+
except Exception:
|
| 172 |
+
writer.close()
|
| 173 |
+
tmp.unlink(missing_ok=True)
|
| 174 |
+
raise
|
| 175 |
+
writer.close()
|
| 176 |
+
tmp.replace(out_path)
|
| 177 |
+
return {"n": n, "n_changed": n_changed}
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def _safe_pattern(pattern: str) -> bool:
|
| 181 |
+
if not isinstance(pattern, str) or not pattern.startswith("^") or not pattern.endswith("$"):
|
| 182 |
+
return False
|
| 183 |
+
if not 4 <= len(pattern) <= 180:
|
| 184 |
+
return False
|
| 185 |
+
if len(re.findall(r"\.\*|\.\+", pattern)) > 2:
|
| 186 |
+
return False
|
| 187 |
+
if re.search(r"\([^)]*[+*][^)]*\)[+*{]", pattern):
|
| 188 |
+
return False
|
| 189 |
+
try:
|
| 190 |
+
re.compile(pattern, re.IGNORECASE)
|
| 191 |
+
except re.error:
|
| 192 |
+
return False
|
| 193 |
+
return True
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _blocked_candidate(line: str) -> bool:
|
| 197 |
+
"""Publication sentences, headings, and mid-sentence fragments stay in the row."""
|
| 198 |
+
if _PROVISION_LINE.search(line) or _HEADING_LINE.match(line):
|
| 199 |
+
return True
|
| 200 |
+
if len(line) <= 3:
|
| 201 |
+
return True
|
| 202 |
+
return line.endswith((",", ";", " or", " and"))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def accept_line_patterns(
|
| 206 |
+
proposals: Sequence[str],
|
| 207 |
+
leftovers: Sequence[str],
|
| 208 |
+
existing: Sequence[str] = (),
|
| 209 |
+
*,
|
| 210 |
+
must_hit: Sequence[str] | None = None,
|
| 211 |
+
) -> list[str]:
|
| 212 |
+
"""Keep a proposal only when it hits a leftover and misses every held-out sentence."""
|
| 213 |
+
accepted: list[str] = []
|
| 214 |
+
seen = set(existing)
|
| 215 |
+
pool = [line.strip() for line in leftovers if line and str(line).strip()]
|
| 216 |
+
required = pool if must_hit is None else [line.strip() for line in must_hit if line and str(line).strip()]
|
| 217 |
+
for pattern in proposals:
|
| 218 |
+
if pattern in seen or not _safe_pattern(pattern):
|
| 219 |
+
continue
|
| 220 |
+
compiled = re.compile(pattern, re.IGNORECASE)
|
| 221 |
+
if any(compiled.fullmatch(line.strip()) for line in KEEP_LINES):
|
| 222 |
+
continue
|
| 223 |
+
if compiled.fullmatch("2") or compiled.fullmatch("10"):
|
| 224 |
+
continue
|
| 225 |
+
hits = [line for line in pool if compiled.fullmatch(line)]
|
| 226 |
+
if not hits:
|
| 227 |
+
continue
|
| 228 |
+
if required and not any(compiled.fullmatch(line) for line in required):
|
| 229 |
+
continue
|
| 230 |
+
if any(_blocked_candidate(line) for line in hits):
|
| 231 |
+
continue
|
| 232 |
+
accepted.append(pattern)
|
| 233 |
+
seen.add(pattern)
|
| 234 |
+
return accepted
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def line_still_present(line: str) -> bool:
|
| 238 |
+
"""True when the current script still leaves this exact line in place."""
|
| 239 |
+
probe = (
|
| 240 |
+
line
|
| 241 |
+
+ "\nArticle 1 The present Act applies throughout the territory and binds every person."
|
| 242 |
+
)
|
| 243 |
+
normalized = normalize_legal_text(probe)
|
| 244 |
+
return line in normalized.splitlines()
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def router_candidates(
|
| 248 |
+
leftovers: Sequence[dict[str, Any]],
|
| 249 |
+
limit: int = 40,
|
| 250 |
+
*,
|
| 251 |
+
skip: set[str] | None = None,
|
| 252 |
+
presence: dict[str, bool] | None = None,
|
| 253 |
+
) -> list[dict[str, Any]]:
|
| 254 |
+
"""Banners the script still keeps, in leftover order, excluding provision lines."""
|
| 255 |
+
chosen: list[dict[str, Any]] = []
|
| 256 |
+
seen: set[str] = set()
|
| 257 |
+
held = skip or set()
|
| 258 |
+
known = presence if presence is not None else {}
|
| 259 |
+
for item in leftovers:
|
| 260 |
+
line = str(item.get("line") or "").strip()
|
| 261 |
+
if not line or line in seen or line in held:
|
| 262 |
+
continue
|
| 263 |
+
if line not in known:
|
| 264 |
+
known[line] = line_still_present(line)
|
| 265 |
+
if not known[line] or _blocked_candidate(line):
|
| 266 |
+
continue
|
| 267 |
+
seen.add(line)
|
| 268 |
+
chosen.append({"line": line, "count": int(item.get("count") or 0)})
|
| 269 |
+
if len(chosen) >= limit:
|
| 270 |
+
break
|
| 271 |
+
return chosen
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def _cluster_key(line: str) -> str:
|
| 275 |
+
shape = re.sub(r"\d+", "0", line.casefold())
|
| 276 |
+
shape = re.sub(r"[^\w\s]+", " ", shape, flags=re.UNICODE)
|
| 277 |
+
shape = re.sub(r"\s+", " ", shape).strip()
|
| 278 |
+
return " ".join(shape.split()[:4])
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
def largest_cluster(candidates: Sequence[dict[str, Any]], limit: int) -> list[dict[str, Any]]:
|
| 282 |
+
"""The repeated family with the highest total count, capped to one prompt."""
|
| 283 |
+
groups: dict[str, list[dict[str, Any]]] = {}
|
| 284 |
+
for item in candidates:
|
| 285 |
+
groups.setdefault(_cluster_key(str(item["line"])), []).append(item)
|
| 286 |
+
best = max(groups.values(), key=lambda group: sum(int(item["count"]) for item in group))
|
| 287 |
+
best.sort(key=lambda item: int(item["count"]), reverse=True)
|
| 288 |
+
return best[:limit]
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
_BARE_PATTERN = re.compile(r"\^[^\n]{1,180}\$")
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def _patterns_from_model_text(raw: str) -> list[str]:
|
| 295 |
+
"""Read whole-line patterns from JSON, or from a model that skipped the JSON."""
|
| 296 |
+
start, end = raw.find("{"), raw.rfind("}")
|
| 297 |
+
if start >= 0 and end > start:
|
| 298 |
+
try:
|
| 299 |
+
payload = json.loads(raw[start : end + 1])
|
| 300 |
+
except json.JSONDecodeError:
|
| 301 |
+
payload = None
|
| 302 |
+
found = payload.get("line_patterns") if isinstance(payload, dict) else None
|
| 303 |
+
if isinstance(found, list):
|
| 304 |
+
return [item for item in found if isinstance(item, str)]
|
| 305 |
+
seen: set[str] = set()
|
| 306 |
+
bare: list[str] = []
|
| 307 |
+
for item in _BARE_PATTERN.findall(raw):
|
| 308 |
+
if item not in seen and item != "^...$":
|
| 309 |
+
seen.add(item)
|
| 310 |
+
bare.append(item)
|
| 311 |
+
return bare
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def propose_line_patterns(
|
| 315 |
+
leftovers: Sequence[dict[str, Any]],
|
| 316 |
+
generate_text: GenerateText,
|
| 317 |
+
*,
|
| 318 |
+
char_budget: int = PROMPT_CHAR_BUDGET,
|
| 319 |
+
) -> list[str]:
|
| 320 |
+
"""One router call. The model proposes whole-line patterns, not statute text."""
|
| 321 |
+
if not leftovers:
|
| 322 |
+
return []
|
| 323 |
+
body: list[str] = []
|
| 324 |
+
used = len(_PROMPT_PREFIX)
|
| 325 |
+
for item in leftovers:
|
| 326 |
+
row = f"- {item['count']}× {item['line']}\n"
|
| 327 |
+
if used + len(row) > char_budget:
|
| 328 |
+
break
|
| 329 |
+
body.append(row)
|
| 330 |
+
used += len(row)
|
| 331 |
+
if not body:
|
| 332 |
+
room = max(0, char_budget - len(_PROMPT_PREFIX) - 16)
|
| 333 |
+
snippet = str(leftovers[0]["line"])[:room]
|
| 334 |
+
body.append(f"- {leftovers[0]['count']}× {snippet}\n")
|
| 335 |
+
raw = str(generate_text(_PROMPT_PREFIX + "".join(body)))
|
| 336 |
+
return _patterns_from_model_text(raw)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def load_learned_patterns() -> list[str]:
|
| 340 |
+
path = learned_patterns_path()
|
| 341 |
+
if not path.is_file():
|
| 342 |
+
return []
|
| 343 |
+
try:
|
| 344 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 345 |
+
except (OSError, json.JSONDecodeError):
|
| 346 |
+
return []
|
| 347 |
+
return [item for item in payload.get("patterns") or [] if isinstance(item, str)]
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def save_learned_patterns(patterns: Sequence[str]) -> None:
|
| 351 |
+
path = learned_patterns_path()
|
| 352 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 353 |
+
path.write_text(
|
| 354 |
+
json.dumps({"patterns": list(patterns)}, ensure_ascii=False, indent=2) + "\n",
|
| 355 |
+
encoding="utf-8",
|
| 356 |
+
)
|
| 357 |
+
# The structure cache keys on mtime; the write updates it.
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def unresolved_path(report_dir: Path) -> Path:
|
| 361 |
+
return report_dir / "_unresolved.json"
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
def load_unresolved(report_dir: Path) -> set[str]:
|
| 365 |
+
path = unresolved_path(report_dir)
|
| 366 |
+
if not path.is_file():
|
| 367 |
+
return set()
|
| 368 |
+
try:
|
| 369 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 370 |
+
except (OSError, json.JSONDecodeError):
|
| 371 |
+
return set()
|
| 372 |
+
return {item.strip() for item in payload.get("lines") or [] if isinstance(item, str) and item.strip()}
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def save_unresolved(report_dir: Path, lines: set[str]) -> None:
|
| 376 |
+
path = unresolved_path(report_dir)
|
| 377 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 378 |
+
path.write_text(
|
| 379 |
+
json.dumps({"lines": sorted(lines)}, ensure_ascii=False, indent=2) + "\n",
|
| 380 |
+
encoding="utf-8",
|
| 381 |
+
)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def collect_leftovers(report_dir: Path) -> list[dict[str, Any]]:
|
| 385 |
+
"""Merge per-country residual lines. Counts for the same line are summed."""
|
| 386 |
+
counts: Counter[str] = Counter()
|
| 387 |
+
if not report_dir.is_dir():
|
| 388 |
+
return []
|
| 389 |
+
for path in sorted(report_dir.glob("*.json")):
|
| 390 |
+
if path.name.startswith("_"):
|
| 391 |
+
continue
|
| 392 |
+
try:
|
| 393 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 394 |
+
except (OSError, json.JSONDecodeError):
|
| 395 |
+
continue
|
| 396 |
+
for item in payload.get("leftovers") or []:
|
| 397 |
+
if isinstance(item, dict) and isinstance(item.get("line"), str):
|
| 398 |
+
line = item["line"].strip()
|
| 399 |
+
if line:
|
| 400 |
+
counts[line] += int(item.get("count") or 0)
|
| 401 |
+
return [{"line": line, "count": count} for line, count in counts.most_common()]
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def improve_from_reports(
|
| 405 |
+
report_dir: Path,
|
| 406 |
+
generate_text: GenerateText,
|
| 407 |
+
*,
|
| 408 |
+
max_passes: int = 40,
|
| 409 |
+
batch_size: int = 12,
|
| 410 |
+
char_budget: int = PROMPT_CHAR_BUDGET,
|
| 411 |
+
on_pass: Callable[[dict[str, Any]], None] | None = None,
|
| 412 |
+
reset_unresolved: bool = False,
|
| 413 |
+
) -> dict[str, Any]:
|
| 414 |
+
"""Ask the router, one short batch at a time, for rules the script can apply.
|
| 415 |
+
|
| 416 |
+
A batch is one repeated family. Patterns that do not remove a line, or that
|
| 417 |
+
also match a publication sentence, are not stored. Families the model cannot
|
| 418 |
+
safely pattern are remembered so the next batch is a different family.
|
| 419 |
+
"""
|
| 420 |
+
merged = collect_leftovers(report_dir)
|
| 421 |
+
pool_lines = [str(item["line"]) for item in merged]
|
| 422 |
+
presence: dict[str, bool] = {}
|
| 423 |
+
skip = set() if reset_unresolved else load_unresolved(report_dir)
|
| 424 |
+
existing = load_learned_patterns()
|
| 425 |
+
accepted_all: list[str] = []
|
| 426 |
+
removed_lines: list[str] = []
|
| 427 |
+
proposed = 0
|
| 428 |
+
passes = 0
|
| 429 |
+
|
| 430 |
+
def _emit(row: dict[str, Any]) -> None:
|
| 431 |
+
if on_pass is not None:
|
| 432 |
+
on_pass(row)
|
| 433 |
+
|
| 434 |
+
for pass_no in range(1, max(1, max_passes) + 1):
|
| 435 |
+
pending = router_candidates(merged, limit=100_000, skip=skip, presence=presence)
|
| 436 |
+
if not pending:
|
| 437 |
+
break
|
| 438 |
+
batch = largest_cluster(pending, batch_size)
|
| 439 |
+
cluster = _cluster_key(str(batch[0]["line"]))
|
| 440 |
+
_emit({
|
| 441 |
+
"event": "prompt",
|
| 442 |
+
"pass": pass_no,
|
| 443 |
+
"cluster": cluster,
|
| 444 |
+
"batch_id": hashlib.sha256(cluster.encode("utf-8")).hexdigest()[:8],
|
| 445 |
+
"candidates": len(batch),
|
| 446 |
+
"lines": [str(item["line"]) for item in batch],
|
| 447 |
+
})
|
| 448 |
+
try:
|
| 449 |
+
proposals = propose_line_patterns(batch, generate_text, char_budget=char_budget)
|
| 450 |
+
except Exception as exc:
|
| 451 |
+
passes += 1
|
| 452 |
+
_emit({"event": "pass", "pass": pass_no, "cluster": cluster, "error": str(exc)})
|
| 453 |
+
break
|
| 454 |
+
proposed += len(proposals)
|
| 455 |
+
accepted = accept_line_patterns(proposals, pool_lines, existing, must_hit=[str(item["line"]) for item in batch])
|
| 456 |
+
before = list(existing)
|
| 457 |
+
kept: list[str] = []
|
| 458 |
+
removed_now: list[str] = []
|
| 459 |
+
if accepted:
|
| 460 |
+
save_learned_patterns([*before, *accepted])
|
| 461 |
+
for pattern in accepted:
|
| 462 |
+
compiled = re.compile(pattern, re.IGNORECASE)
|
| 463 |
+
hits = [line for line in pool_lines if compiled.fullmatch(line)]
|
| 464 |
+
dropped = [line for line in hits if not line_still_present(line)]
|
| 465 |
+
if not dropped:
|
| 466 |
+
continue
|
| 467 |
+
kept.append(pattern)
|
| 468 |
+
removed_now.extend(dropped)
|
| 469 |
+
if kept != accepted:
|
| 470 |
+
save_learned_patterns([*before, *kept])
|
| 471 |
+
if not kept:
|
| 472 |
+
skip.update(str(item["line"]) for item in batch)
|
| 473 |
+
else:
|
| 474 |
+
for line in removed_now:
|
| 475 |
+
presence[line] = False
|
| 476 |
+
skip.discard(line)
|
| 477 |
+
if line not in removed_lines:
|
| 478 |
+
removed_lines.append(line)
|
| 479 |
+
existing = [*before, *kept]
|
| 480 |
+
accepted_all.extend(kept)
|
| 481 |
+
passes += 1
|
| 482 |
+
_emit({
|
| 483 |
+
"event": "pass",
|
| 484 |
+
"pass": pass_no,
|
| 485 |
+
"cluster": cluster,
|
| 486 |
+
"proposed": len(proposals),
|
| 487 |
+
"accepted": kept,
|
| 488 |
+
"removed": len(removed_now),
|
| 489 |
+
})
|
| 490 |
+
|
| 491 |
+
save_unresolved(report_dir, skip)
|
| 492 |
+
withheld = 0
|
| 493 |
+
for item in merged:
|
| 494 |
+
line = str(item["line"])
|
| 495 |
+
if line not in presence:
|
| 496 |
+
presence[line] = line_still_present(line)
|
| 497 |
+
if presence[line] and _blocked_candidate(line):
|
| 498 |
+
withheld += 1
|
| 499 |
+
remaining = router_candidates(merged, limit=100_000, skip=skip, presence=presence)
|
| 500 |
+
return {
|
| 501 |
+
"proposed": proposed,
|
| 502 |
+
"accepted": accepted_all,
|
| 503 |
+
"leftover_lines": len(merged),
|
| 504 |
+
"removed": len(removed_lines),
|
| 505 |
+
"removed_lines": removed_lines[:40],
|
| 506 |
+
"unresolved": len(skip),
|
| 507 |
+
"withheld": withheld,
|
| 508 |
+
"remaining": len(remaining),
|
| 509 |
+
"passes": passes,
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def worker_count(requested: int | None) -> int:
|
| 514 |
+
if requested is not None:
|
| 515 |
+
return max(1, int(requested))
|
| 516 |
+
return max(1, os.cpu_count() or 1)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _scan_job(job: tuple[str, str, str]) -> dict[str, Any]:
|
| 520 |
+
slug, path, report_dir = job
|
| 521 |
+
stats = scan_pack(Path(path))
|
| 522 |
+
write_scan(Path(report_dir), slug, stats)
|
| 523 |
+
return {"slug": slug, "n": stats["n"], "n_changed": stats["n_changed"], "n_unstable": stats["n_unstable"], "leftovers": len(stats["leftovers"])}
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _apply_job(job: tuple[str, str, str]) -> dict[str, Any]:
|
| 527 |
+
slug, path, out_dir = job
|
| 528 |
+
out_path = Path(out_dir) / Path(path).name
|
| 529 |
+
stats = apply_pack(Path(path), out_path)
|
| 530 |
+
return {"slug": slug, "out": str(out_path), **stats}
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def run_parallel(
|
| 534 |
+
jobs: Sequence[tuple[str, str, str]],
|
| 535 |
+
worker,
|
| 536 |
+
workers: int | None,
|
| 537 |
+
*,
|
| 538 |
+
progress_path: Path | None = None,
|
| 539 |
+
on_done: Callable[[dict[str, Any]], None] | None = None,
|
| 540 |
+
) -> list[dict[str, Any]]:
|
| 541 |
+
"""One process per batch of countries. Each country writes its own file.
|
| 542 |
+
|
| 543 |
+
Progress is recorded in the parent as each country finishes, so a later
|
| 544 |
+
run can skip those slugs.
|
| 545 |
+
"""
|
| 546 |
+
count = worker_count(workers)
|
| 547 |
+
|
| 548 |
+
def _finish(row: dict[str, Any]) -> dict[str, Any]:
|
| 549 |
+
if progress_path is not None:
|
| 550 |
+
append_progress(progress_path, row)
|
| 551 |
+
if on_done is not None:
|
| 552 |
+
on_done(row)
|
| 553 |
+
return row
|
| 554 |
+
|
| 555 |
+
if count == 1 or len(jobs) <= 1:
|
| 556 |
+
return [_finish(worker(job)) for job in jobs]
|
| 557 |
+
rows: list[dict[str, Any]] = []
|
| 558 |
+
with ProcessPoolExecutor(max_workers=min(count, len(jobs))) as pool:
|
| 559 |
+
futures = {pool.submit(worker, job): job[0] for job in jobs}
|
| 560 |
+
for future in as_completed(futures):
|
| 561 |
+
slug = futures[future]
|
| 562 |
+
try:
|
| 563 |
+
row = future.result()
|
| 564 |
+
except Exception as exc:
|
| 565 |
+
row = {"slug": slug, "error": str(exc)}
|
| 566 |
+
rows.append(_finish(row))
|
| 567 |
+
rows.sort(key=lambda row: str(row.get("slug") or ""))
|
| 568 |
+
return rows
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def write_scan(report_dir: Path, slug: str, stats: dict[str, Any]) -> Path:
|
| 572 |
+
report_dir.mkdir(parents=True, exist_ok=True)
|
| 573 |
+
path = report_dir / f"{slug}.json"
|
| 574 |
+
tmp = path.with_suffix(".json.tmp")
|
| 575 |
+
tmp.write_text(json.dumps({"slug": slug, **stats}, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
| 576 |
+
tmp.replace(path)
|
| 577 |
+
return path
|
| 578 |
+
|
| 579 |
+
|
| 580 |
+
def scan_done(report_dir: Path, slug: str) -> bool:
|
| 581 |
+
path = report_dir / f"{slug}.json"
|
| 582 |
+
if not path.is_file():
|
| 583 |
+
return False
|
| 584 |
+
try:
|
| 585 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 586 |
+
except (OSError, json.JSONDecodeError):
|
| 587 |
+
return False
|
| 588 |
+
return isinstance(payload.get("n"), int)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def apply_done(out_dir: Path, slug: str) -> bool:
|
| 592 |
+
path = out_dir / f"{slug}_corpus.parquet"
|
| 593 |
+
if not path.is_file() or path.stat().st_size < 12:
|
| 594 |
+
return False
|
| 595 |
+
with path.open("rb") as handle:
|
| 596 |
+
if handle.read(4) != b"PAR1":
|
| 597 |
+
return False
|
| 598 |
+
handle.seek(-4, 2)
|
| 599 |
+
return handle.read(4) == b"PAR1"
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def append_progress(path: Path, row: dict[str, Any]) -> None:
|
| 603 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 604 |
+
with path.open("a", encoding="utf-8") as handle:
|
| 605 |
+
handle.write(json.dumps(row, ensure_ascii=False) + "\n")
|
| 606 |
+
handle.flush()
|
| 607 |
+
|
| 608 |
+
|
| 609 |
+
def load_generate_text() -> GenerateText:
|
| 610 |
+
"""Import the router once per process. Scan and apply never call this."""
|
| 611 |
+
from ipfs_datasets_py.llm_router import generate_text
|
| 612 |
+
|
| 613 |
+
return generate_text
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def default_paths(root: Path) -> dict[str, Path]:
|
| 617 |
+
return {
|
| 618 |
+
"cache": root / "cache",
|
| 619 |
+
"reports": root / "reports" / "residuals",
|
| 620 |
+
"out": root / "llm-normalized",
|
| 621 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/package.py
ADDED
|
@@ -0,0 +1,1010 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write country-laws-ir-graphrag/v1 thin-client layout (SkillCenter / publicus-ir family)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import gc
|
| 6 |
+
import json
|
| 7 |
+
import pickle
|
| 8 |
+
import shutil
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import Any
|
| 11 |
+
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from . import LAYOUT_FAMILY, MAX_ROWS_PER_FILE, SCHEMA_VERSION, __version__
|
| 15 |
+
from .catalog import target_repo
|
| 16 |
+
from .cidutil import file_descriptor
|
| 17 |
+
from .parquet_io import write_parquet, write_sharded
|
| 18 |
+
|
| 19 |
+
ADJ_POINTERS_PER_ROW = 4096
|
| 20 |
+
ADJ_POINTERS_PER_SHARD = 8192
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _index_df(rows: list[dict[str, Any]]) -> pd.DataFrame:
|
| 24 |
+
return pd.DataFrame(rows)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def package_release(
|
| 28 |
+
out: Path,
|
| 29 |
+
corpus: pd.DataFrame,
|
| 30 |
+
bm25: dict[str, Any],
|
| 31 |
+
graph: dict[str, Any],
|
| 32 |
+
vectors: dict[str, Any],
|
| 33 |
+
source_meta: dict[str, Any],
|
| 34 |
+
country: dict[str, Any],
|
| 35 |
+
code_root: Path,
|
| 36 |
+
normalization_report: dict[str, Any] | None = None,
|
| 37 |
+
extra_manifest: dict[str, Any] | None = None,
|
| 38 |
+
wipe: bool = True,
|
| 39 |
+
skip_bm25_graph: bool = False,
|
| 40 |
+
) -> dict[str, Any]:
|
| 41 |
+
if wipe and out.exists():
|
| 42 |
+
shutil.rmtree(out)
|
| 43 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 44 |
+
indexes_dir = out / "indexes"
|
| 45 |
+
indexes_dir.mkdir(parents=True, exist_ok=True)
|
| 46 |
+
|
| 47 |
+
corpus_idx = write_sharded(
|
| 48 |
+
corpus,
|
| 49 |
+
out / "data" / "corpus",
|
| 50 |
+
"data/corpus",
|
| 51 |
+
kind="corpus",
|
| 52 |
+
key_col="entry_cid",
|
| 53 |
+
index_col="document_index",
|
| 54 |
+
)
|
| 55 |
+
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 56 |
+
|
| 57 |
+
if skip_bm25_graph:
|
| 58 |
+
bm25_doc_idx = []
|
| 59 |
+
posting_idx = []
|
| 60 |
+
postings = pd.DataFrame()
|
| 61 |
+
node_idx = []
|
| 62 |
+
edge_idx = []
|
| 63 |
+
in_idx = []
|
| 64 |
+
out_idx = []
|
| 65 |
+
incoming = pd.DataFrame()
|
| 66 |
+
outgoing = pd.DataFrame()
|
| 67 |
+
bm25 = bm25 or {"documents": pd.DataFrame(), "postings": pd.DataFrame(), "stats": {}}
|
| 68 |
+
graph = graph or {"nodes": pd.DataFrame(), "edges": pd.DataFrame(), "stats": {}}
|
| 69 |
+
else:
|
| 70 |
+
bm25_doc_idx = write_sharded(
|
| 71 |
+
bm25["documents"],
|
| 72 |
+
out / "data" / "bm25" / "documents",
|
| 73 |
+
"data/bm25/documents",
|
| 74 |
+
kind="bm25_documents",
|
| 75 |
+
key_col="entry_cid",
|
| 76 |
+
index_col="document_index",
|
| 77 |
+
)
|
| 78 |
+
write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
|
| 79 |
+
|
| 80 |
+
postings = bm25["postings"]
|
| 81 |
+
posting_idx = write_sharded(
|
| 82 |
+
postings,
|
| 83 |
+
out / "data" / "bm25" / "postings",
|
| 84 |
+
"data/bm25/postings",
|
| 85 |
+
kind="bm25_postings",
|
| 86 |
+
key_col="term",
|
| 87 |
+
)
|
| 88 |
+
for row, part_start in zip(posting_idx, range(len(posting_idx))):
|
| 89 |
+
shard_df = postings.iloc[
|
| 90 |
+
part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE
|
| 91 |
+
]
|
| 92 |
+
row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
|
| 93 |
+
row["posting_count"] = (
|
| 94 |
+
int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
|
| 95 |
+
)
|
| 96 |
+
row["token_instance_count"] = row["posting_count"]
|
| 97 |
+
write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
|
| 98 |
+
|
| 99 |
+
node_idx = write_sharded(
|
| 100 |
+
graph["nodes"],
|
| 101 |
+
out / "data" / "graph" / "nodes",
|
| 102 |
+
"data/graph/nodes",
|
| 103 |
+
kind="graph_nodes",
|
| 104 |
+
key_col="node_cid",
|
| 105 |
+
)
|
| 106 |
+
write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
|
| 107 |
+
|
| 108 |
+
edge_idx = write_sharded(
|
| 109 |
+
graph["edges"],
|
| 110 |
+
out / "data" / "graph" / "edges",
|
| 111 |
+
"data/graph/edges",
|
| 112 |
+
kind="graph_edges",
|
| 113 |
+
key_col="edge_cid",
|
| 114 |
+
)
|
| 115 |
+
write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
|
| 116 |
+
|
| 117 |
+
incoming = graph["incoming"]
|
| 118 |
+
outgoing = graph["outgoing"]
|
| 119 |
+
in_idx = write_sharded(
|
| 120 |
+
incoming
|
| 121 |
+
if incoming is not None and not incoming.empty
|
| 122 |
+
else pd.DataFrame(columns=["node_cid", "page_index", "direction"]),
|
| 123 |
+
out / "data" / "graph" / "adjacency" / "incoming",
|
| 124 |
+
"data/graph/adjacency/incoming",
|
| 125 |
+
kind="graph_incoming_adjacency",
|
| 126 |
+
key_col="node_cid",
|
| 127 |
+
)
|
| 128 |
+
out_idx = write_sharded(
|
| 129 |
+
outgoing
|
| 130 |
+
if outgoing is not None and not outgoing.empty
|
| 131 |
+
else pd.DataFrame(columns=["node_cid", "page_index", "direction"]),
|
| 132 |
+
out / "data" / "graph" / "adjacency" / "outgoing",
|
| 133 |
+
"data/graph/adjacency/outgoing",
|
| 134 |
+
kind="graph_outgoing_adjacency",
|
| 135 |
+
key_col="node_cid",
|
| 136 |
+
)
|
| 137 |
+
for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
|
| 138 |
+
for r in rows:
|
| 139 |
+
r["direction"] = direction
|
| 140 |
+
r["adjacency_count"] = r.get("row_count", 0)
|
| 141 |
+
r["node_count"] = r.get("row_count", 0)
|
| 142 |
+
r["first_page_index"] = 0
|
| 143 |
+
r["last_page_index"] = 0
|
| 144 |
+
write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
|
| 145 |
+
write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
|
| 146 |
+
|
| 147 |
+
vectors_df = vectors["vectors"]
|
| 148 |
+
# Drop null embeddings for stub releases so parquet stays typed; keep rows when present.
|
| 149 |
+
if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all():
|
| 150 |
+
vectors_write = vectors_df.drop(columns=["embedding"])
|
| 151 |
+
vectors_write["embedding_status"] = "stub_missing"
|
| 152 |
+
else:
|
| 153 |
+
vectors_write = vectors_df
|
| 154 |
+
vec_idx = write_sharded(
|
| 155 |
+
vectors_write,
|
| 156 |
+
out / "data" / "vectors",
|
| 157 |
+
"data/vectors",
|
| 158 |
+
kind="vectors",
|
| 159 |
+
key_col="entry_cid",
|
| 160 |
+
index_col="document_index",
|
| 161 |
+
)
|
| 162 |
+
meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]}
|
| 163 |
+
for r in vec_idx:
|
| 164 |
+
m = meta_by_cluster.get(r["shard_id"], {})
|
| 165 |
+
r["centroid"] = m.get("centroid", [])
|
| 166 |
+
r["shard_centroid"] = m.get("shard_centroid", [])
|
| 167 |
+
r["centroid_min_score"] = m.get("centroid_min_score", 0.0)
|
| 168 |
+
r["centroid_shard_count"] = m.get("centroid_shard_count", 1)
|
| 169 |
+
r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0)
|
| 170 |
+
r["cluster_id"] = m.get("cluster_id", r["shard_id"])
|
| 171 |
+
r["dimension"] = 384
|
| 172 |
+
r["model_name"] = "thenlper/gte-small"
|
| 173 |
+
if m.get("stub"):
|
| 174 |
+
r["stub"] = True
|
| 175 |
+
r["stub_reason"] = m.get("stub_reason", "")
|
| 176 |
+
write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx))
|
| 177 |
+
|
| 178 |
+
# Bundle package + scripts into the release
|
| 179 |
+
pkg_src = Path(__file__).resolve().parent
|
| 180 |
+
dest_pkg = out / "country_laws_ir"
|
| 181 |
+
shutil.copytree(
|
| 182 |
+
pkg_src,
|
| 183 |
+
dest_pkg,
|
| 184 |
+
dirs_exist_ok=True,
|
| 185 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"),
|
| 186 |
+
)
|
| 187 |
+
scripts_dir = out / "scripts"
|
| 188 |
+
scripts_dir.mkdir(exist_ok=True)
|
| 189 |
+
for name in (
|
| 190 |
+
"build_country_laws_ir.py",
|
| 191 |
+
"normalize_country_laws.py",
|
| 192 |
+
"query_country_laws_hf.py",
|
| 193 |
+
"query_country_laws_ir.py",
|
| 194 |
+
"generate_country_laws_ir.py",
|
| 195 |
+
):
|
| 196 |
+
src = code_root / "scripts" / name
|
| 197 |
+
if src.exists():
|
| 198 |
+
shutil.copy2(src, scripts_dir / name)
|
| 199 |
+
shutil.copy2(pkg_src / "normalize.py", out / "normalize.py")
|
| 200 |
+
shutil.copy2(pkg_src / "query.py", out / "query.py")
|
| 201 |
+
shutil.copy2(pkg_src / "build.py", out / "build.py")
|
| 202 |
+
_write_skill(out, country, hub_id=target_repo(country["slug"]))
|
| 203 |
+
|
| 204 |
+
reports_dir = out / "reports"
|
| 205 |
+
reports_dir.mkdir(exist_ok=True)
|
| 206 |
+
if normalization_report is not None:
|
| 207 |
+
payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n"
|
| 208 |
+
(out / "normalization_report.json").write_text(payload, encoding="utf-8")
|
| 209 |
+
(reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
|
| 210 |
+
|
| 211 |
+
n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0
|
| 212 |
+
n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0
|
| 213 |
+
counts = {
|
| 214 |
+
"bm25_document_chunks": len(bm25_doc_idx),
|
| 215 |
+
"bm25_documents": int(len(bm25["documents"])),
|
| 216 |
+
"bm25_keyword_shards": len(posting_idx),
|
| 217 |
+
"bm25_posting_rows": int(len(postings)),
|
| 218 |
+
"bm25_postings": int((bm25.get("stats") or {}).get("n_postings") or 0),
|
| 219 |
+
"bm25_terms": int((bm25.get("stats") or {}).get("n_terms") or 0),
|
| 220 |
+
"corpus_chunks": len(corpus_idx),
|
| 221 |
+
"corpus_rows": int(len(corpus)),
|
| 222 |
+
"graph_edge_chunks": len(edge_idx),
|
| 223 |
+
"graph_edges": int(len(graph["edges"])),
|
| 224 |
+
"graph_incoming_adjacency_edges": int(len(graph["edges"])),
|
| 225 |
+
"graph_incoming_adjacency_rows": int(len(incoming)) if incoming is not None else 0,
|
| 226 |
+
"graph_incoming_adjacency_shards": len(in_idx),
|
| 227 |
+
"graph_node_chunks": len(node_idx),
|
| 228 |
+
"graph_nodes": int(len(graph["nodes"])),
|
| 229 |
+
"graph_outgoing_adjacency_edges": int(len(graph["edges"])),
|
| 230 |
+
"graph_outgoing_adjacency_rows": int(len(outgoing)) if outgoing is not None else 0,
|
| 231 |
+
"graph_outgoing_adjacency_shards": len(out_idx),
|
| 232 |
+
"vector_chunks": len(vec_idx),
|
| 233 |
+
"vector_rows": int(len(vectors_df)),
|
| 234 |
+
"n_laws": n_laws,
|
| 235 |
+
"n_articles": n_articles,
|
| 236 |
+
}
|
| 237 |
+
if skip_bm25_graph and extra_manifest and extra_manifest.get("sparse"):
|
| 238 |
+
sparse = extra_manifest["sparse"]
|
| 239 |
+
bm25_counts = (sparse.get("bm25") or {}).get("counts") or {}
|
| 240 |
+
graph_counts = sparse.get("graph") or {}
|
| 241 |
+
counts.update(
|
| 242 |
+
{k: int(v) for k, v in bm25_counts.items() if isinstance(v, (int, float))}
|
| 243 |
+
)
|
| 244 |
+
if graph_counts.get("node_count") is not None:
|
| 245 |
+
counts["graph_nodes"] = int(graph_counts["node_count"])
|
| 246 |
+
if graph_counts.get("edge_count") is not None:
|
| 247 |
+
counts["graph_edges"] = int(graph_counts["edge_count"])
|
| 248 |
+
|
| 249 |
+
def idx_desc(name: str) -> dict[str, Any]:
|
| 250 |
+
path = indexes_dir / name
|
| 251 |
+
if not path.is_file():
|
| 252 |
+
return {"relative_path": f"indexes/{name}", "present": False}
|
| 253 |
+
return file_descriptor(path, f"indexes/{name}")
|
| 254 |
+
|
| 255 |
+
hub_id = target_repo(country["slug"])
|
| 256 |
+
bm25_stats = bm25.get("stats") if isinstance(bm25.get("stats"), dict) else {}
|
| 257 |
+
graph_stats = graph.get("stats") if isinstance(graph.get("stats"), dict) else {}
|
| 258 |
+
edge_types = graph_stats.get("edge_types") or [
|
| 259 |
+
"HAS_JURISDICTION",
|
| 260 |
+
"HAS_LANGUAGE",
|
| 261 |
+
"BELONGS_TO_LAW",
|
| 262 |
+
"HAS_ARTICLE",
|
| 263 |
+
"BM25_NEIGHBOR_OF",
|
| 264 |
+
]
|
| 265 |
+
manifest = {
|
| 266 |
+
"schema_version": SCHEMA_VERSION,
|
| 267 |
+
"layout_family": LAYOUT_FAMILY,
|
| 268 |
+
"packager_version": __version__,
|
| 269 |
+
"primary_key": "entry_cid",
|
| 270 |
+
"dataset_id": source_meta["source_dataset"],
|
| 271 |
+
"dataset_repo_id": hub_id,
|
| 272 |
+
"dataset_revision": source_meta["source_revision"],
|
| 273 |
+
"country": country,
|
| 274 |
+
"disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
|
| 275 |
+
"bm25": {
|
| 276 |
+
k: bm25_stats.get(k)
|
| 277 |
+
for k in (
|
| 278 |
+
"k1",
|
| 279 |
+
"b",
|
| 280 |
+
"title_weight",
|
| 281 |
+
"body_weight",
|
| 282 |
+
"average_document_length",
|
| 283 |
+
"tokenizer",
|
| 284 |
+
"max_query_terms",
|
| 285 |
+
"posting_rows_per_record",
|
| 286 |
+
"terms_per_shard",
|
| 287 |
+
)
|
| 288 |
+
},
|
| 289 |
+
"counts": counts,
|
| 290 |
+
"parquet": {
|
| 291 |
+
"compression": "zstd",
|
| 292 |
+
"compression_level": 6,
|
| 293 |
+
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 294 |
+
"row_group_size": MAX_ROWS_PER_FILE,
|
| 295 |
+
"query_engine": "duckdb",
|
| 296 |
+
},
|
| 297 |
+
"graph": {
|
| 298 |
+
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
| 299 |
+
"adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD,
|
| 300 |
+
"directions": ["incoming", "outgoing"],
|
| 301 |
+
"max_remote_walk_depth": 8,
|
| 302 |
+
"ordering": "score_desc_nulls_last",
|
| 303 |
+
"edge_types": edge_types,
|
| 304 |
+
},
|
| 305 |
+
"vector": vectors["stats"],
|
| 306 |
+
"canonical_fields": [
|
| 307 |
+
"entry_cid",
|
| 308 |
+
"law_cid",
|
| 309 |
+
"record_type",
|
| 310 |
+
"jurisdiction",
|
| 311 |
+
"language",
|
| 312 |
+
"instrument_id",
|
| 313 |
+
"instrument_title",
|
| 314 |
+
"article_number",
|
| 315 |
+
"article_title",
|
| 316 |
+
"title",
|
| 317 |
+
"body",
|
| 318 |
+
"source_url",
|
| 319 |
+
"snapshot_date",
|
| 320 |
+
"coverage",
|
| 321 |
+
"license",
|
| 322 |
+
"collector",
|
| 323 |
+
"source_dataset",
|
| 324 |
+
"source_revision",
|
| 325 |
+
],
|
| 326 |
+
"input_sha256": {
|
| 327 |
+
"laws.parquet": source_meta.get("laws_sha256"),
|
| 328 |
+
"articles.parquet": source_meta.get("articles_sha256"),
|
| 329 |
+
},
|
| 330 |
+
"model_id": (vectors.get("stats") or {}).get("model_name", "thenlper/gte-small"),
|
| 331 |
+
"cid": {
|
| 332 |
+
"codec": "raw",
|
| 333 |
+
"hash": "sha2-256",
|
| 334 |
+
"multibase": "base32",
|
| 335 |
+
"payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')",
|
| 336 |
+
},
|
| 337 |
+
"normalization": normalization_report or {},
|
| 338 |
+
"schema_mapping": {
|
| 339 |
+
"laws": {
|
| 340 |
+
"id": "instrument_id",
|
| 341 |
+
"title": "instrument_title",
|
| 342 |
+
"text": "body",
|
| 343 |
+
"article_count_dtype_source": source_meta.get("article_count_dtype"),
|
| 344 |
+
},
|
| 345 |
+
"articles": {
|
| 346 |
+
"id": "source_id / article identity",
|
| 347 |
+
"law_id": "instrument_id",
|
| 348 |
+
"title": "article_title",
|
| 349 |
+
"text": "body",
|
| 350 |
+
},
|
| 351 |
+
"unit_policy": "prefer articles; fall back to law-level when articles empty",
|
| 352 |
+
"required_law_columns": ["id", "title", "text"],
|
| 353 |
+
"required_article_columns": ["id", "law_id", "title", "text"],
|
| 354 |
+
"fail_closed": True,
|
| 355 |
+
"notes": (
|
| 356 |
+
"Malta and Germany share the same column names. Drift: Malta article_count "
|
| 357 |
+
"is int64, Germany article_count is int32; Germany eli is often null. "
|
| 358 |
+
"Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family."
|
| 359 |
+
),
|
| 360 |
+
},
|
| 361 |
+
"indexes": {
|
| 362 |
+
"bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"),
|
| 363 |
+
"bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"),
|
| 364 |
+
"corpus_chunks": idx_desc("corpus_chunks.parquet"),
|
| 365 |
+
"graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"),
|
| 366 |
+
"graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"),
|
| 367 |
+
"graph_node_chunks": idx_desc("graph_node_chunks.parquet"),
|
| 368 |
+
"graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"),
|
| 369 |
+
"vector_chunks": idx_desc("vector_chunks.parquet"),
|
| 370 |
+
},
|
| 371 |
+
"source": source_meta,
|
| 372 |
+
}
|
| 373 |
+
if extra_manifest:
|
| 374 |
+
manifest.update(extra_manifest)
|
| 375 |
+
(out / "manifest.json").write_text(json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
| 376 |
+
_write_readme(
|
| 377 |
+
out,
|
| 378 |
+
country,
|
| 379 |
+
source_meta,
|
| 380 |
+
counts,
|
| 381 |
+
bm25_stats,
|
| 382 |
+
graph_stats,
|
| 383 |
+
vectors.get("stats") if isinstance(vectors.get("stats"), dict) else {},
|
| 384 |
+
hub_id,
|
| 385 |
+
normalization_report=normalization_report,
|
| 386 |
+
)
|
| 387 |
+
_write_gitattributes(out)
|
| 388 |
+
_write_dataset_configs(out)
|
| 389 |
+
return manifest
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def _write_dataset_configs(out: Path) -> None:
|
| 393 |
+
configs = {
|
| 394 |
+
"country-laws-ir-graphrag/v1": {
|
| 395 |
+
"data_files": {
|
| 396 |
+
"corpus": "data/corpus/*.parquet",
|
| 397 |
+
"bm25_documents": "data/bm25/documents/*.parquet",
|
| 398 |
+
"bm25_postings": "data/bm25/postings/*.parquet",
|
| 399 |
+
"graph_nodes": "data/graph/nodes/*.parquet",
|
| 400 |
+
"graph_edges": "data/graph/edges/*.parquet",
|
| 401 |
+
"graph_adjacency_out": "data/graph/adjacency/out/*.parquet",
|
| 402 |
+
"graph_adjacency_in": "data/graph/adjacency/in/*.parquet",
|
| 403 |
+
"vectors": "data/vectors/*.parquet",
|
| 404 |
+
}
|
| 405 |
+
}
|
| 406 |
+
}
|
| 407 |
+
(out / "dataset_configs.json").write_text(
|
| 408 |
+
json.dumps(configs, indent=2) + "\n", encoding="utf-8"
|
| 409 |
+
)
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def _write_gitattributes(out: Path) -> None:
|
| 413 |
+
(out / ".gitattributes").write_text(
|
| 414 |
+
"*.parquet filter=lfs diff=lfs merge=lfs -text\n"
|
| 415 |
+
"*.bin filter=lfs diff=lfs merge=lfs -text\n",
|
| 416 |
+
encoding="utf-8",
|
| 417 |
+
)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
def _size_category(n: int) -> str:
|
| 421 |
+
if n < 1000:
|
| 422 |
+
return "n<1K"
|
| 423 |
+
if n < 10_000:
|
| 424 |
+
return "1K<n<10K"
|
| 425 |
+
if n < 100_000:
|
| 426 |
+
return "10K<n<100K"
|
| 427 |
+
if n < 1_000_000:
|
| 428 |
+
return "100K<n<1M"
|
| 429 |
+
if n < 10_000_000:
|
| 430 |
+
return "1M<n<10M"
|
| 431 |
+
return "n>10M"
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
def _card_languages(normalization_report: dict[str, Any] | None) -> list[str]:
|
| 435 |
+
if not normalization_report:
|
| 436 |
+
return []
|
| 437 |
+
seen: list[str] = []
|
| 438 |
+
majority = str(normalization_report.get("document_language_majority") or "").strip()
|
| 439 |
+
breakdown = normalization_report.get("language_breakdown") or {}
|
| 440 |
+
ordered = []
|
| 441 |
+
if majority:
|
| 442 |
+
ordered.append(majority)
|
| 443 |
+
ordered.extend(
|
| 444 |
+
sorted(
|
| 445 |
+
(str(k) for k in breakdown if k),
|
| 446 |
+
key=lambda k: -int(breakdown.get(k) or 0),
|
| 447 |
+
)
|
| 448 |
+
)
|
| 449 |
+
for raw in ordered:
|
| 450 |
+
lang = str(raw).strip().lower().replace("_", "-").split("-")[0]
|
| 451 |
+
if lang and lang not in seen and lang not in {"und", "none", "null"}:
|
| 452 |
+
seen.append(lang)
|
| 453 |
+
if len(seen) >= 8:
|
| 454 |
+
break
|
| 455 |
+
return seen
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
def _adj_glob(out: Path, direction: str) -> str:
|
| 459 |
+
aliases = {
|
| 460 |
+
"out": ("out", "outgoing"),
|
| 461 |
+
"in": ("in", "incoming"),
|
| 462 |
+
}
|
| 463 |
+
for name in aliases.get(direction, (direction,)):
|
| 464 |
+
if (out / "data" / "graph" / "adjacency" / name).is_dir():
|
| 465 |
+
return f"data/graph/adjacency/{name}/*.parquet"
|
| 466 |
+
return f"data/graph/adjacency/{direction}/*.parquet"
|
| 467 |
+
|
| 468 |
+
|
| 469 |
+
def _write_readme(
|
| 470 |
+
out: Path,
|
| 471 |
+
country: dict[str, Any],
|
| 472 |
+
source_meta: dict[str, Any],
|
| 473 |
+
counts: dict[str, Any],
|
| 474 |
+
bm25_stats: dict[str, Any],
|
| 475 |
+
graph_stats: dict[str, Any],
|
| 476 |
+
vector_stats: dict[str, Any],
|
| 477 |
+
hub_id: str,
|
| 478 |
+
normalization_report: dict[str, Any] | None = None,
|
| 479 |
+
) -> None:
|
| 480 |
+
slug = country["slug"]
|
| 481 |
+
name = country.get("name") or slug
|
| 482 |
+
src = source_meta.get("source_dataset") or ""
|
| 483 |
+
rev = source_meta.get("source_revision") or ""
|
| 484 |
+
vec_status = (vector_stats or {}).get("status", "embedded")
|
| 485 |
+
n_docs = int((counts or {}).get("corpus_rows") or 0)
|
| 486 |
+
languages = _card_languages(normalization_report)
|
| 487 |
+
import yaml
|
| 488 |
+
|
| 489 |
+
card = {
|
| 490 |
+
"license": "other",
|
| 491 |
+
"task_categories": ["text-retrieval"],
|
| 492 |
+
"tags": [
|
| 493 |
+
"legal",
|
| 494 |
+
"law",
|
| 495 |
+
"graphrag",
|
| 496 |
+
"bm25",
|
| 497 |
+
"research",
|
| 498 |
+
"not-legal-advice",
|
| 499 |
+
str(slug),
|
| 500 |
+
],
|
| 501 |
+
"pretty_name": f"{name} laws IR (CID-keyed GraphRAG)",
|
| 502 |
+
"size_categories": [_size_category(n_docs)],
|
| 503 |
+
"configs": [
|
| 504 |
+
{"config_name": "corpus", "data_files": [{"split": "train", "path": "data/corpus/*.parquet"}]},
|
| 505 |
+
{"config_name": "bm25_documents", "data_files": [{"split": "train", "path": "data/bm25/documents/*.parquet"}]},
|
| 506 |
+
{"config_name": "bm25_postings", "data_files": [{"split": "train", "path": "data/bm25/postings/*.parquet"}]},
|
| 507 |
+
{"config_name": "bm25_keyword_index", "data_files": [{"split": "train", "path": "indexes/bm25_keyword_shards.parquet"}]},
|
| 508 |
+
{"config_name": "vectors", "data_files": [{"split": "train", "path": "data/vectors/*.parquet"}]},
|
| 509 |
+
{"config_name": "vector_meta_index", "data_files": [{"split": "train", "path": "indexes/vector_chunks.parquet"}]},
|
| 510 |
+
{"config_name": "graph_nodes", "data_files": [{"split": "train", "path": "data/graph/nodes/*.parquet"}]},
|
| 511 |
+
{"config_name": "graph_edges", "data_files": [{"split": "train", "path": "data/graph/edges/*.parquet"}]},
|
| 512 |
+
{"config_name": "graph_outgoing_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "out")}]},
|
| 513 |
+
{"config_name": "graph_incoming_adjacency", "data_files": [{"split": "train", "path": _adj_glob(out, "in")}]},
|
| 514 |
+
],
|
| 515 |
+
}
|
| 516 |
+
if languages:
|
| 517 |
+
card["language"] = languages
|
| 518 |
+
front = yaml.safe_dump(card, sort_keys=False, allow_unicode=True)
|
| 519 |
+
text = f"""---
|
| 520 |
+
{front}---
|
| 521 |
+
|
| 522 |
+
# {name} legislation IR (CID-keyed sparse GraphRAG)
|
| 523 |
+
|
| 524 |
+
Research retrieval release of `{src}` (revision `{rev}`) packaged as
|
| 525 |
+
`{SCHEMA_VERSION}` (layout family `{LAYOUT_FAMILY}` / publicus-ir).
|
| 526 |
+
|
| 527 |
+
**Not legal advice.** This is a research snapshot. The official gazette /
|
| 528 |
+
authentic source of {name} prevails over this corpus. Retrieved documents
|
| 529 |
+
and graph edges are retrieval evidence only. No legal text was invented.
|
| 530 |
+
|
| 531 |
+
Primary key: `entry_cid` (CIDv1 raw sha2-256 of a canonical identity record).
|
| 532 |
+
Integer `document_index` values are compact shard pointers, not identities.
|
| 533 |
+
|
| 534 |
+
Target Hub id (packaging metadata only): `{hub_id}`.
|
| 535 |
+
|
| 536 |
+
## Counts
|
| 537 |
+
|
| 538 |
+
| Field | Value |
|
| 539 |
+
| --- | --- |
|
| 540 |
+
| Laws (corpus units) | {(counts or {}).get('n_laws', 0)} |
|
| 541 |
+
| Articles (corpus units) | {(counts or {}).get('n_articles', 0)} |
|
| 542 |
+
| Canonical docs | {(counts or {}).get('corpus_rows', 0)} |
|
| 543 |
+
| BM25 terms | {(counts or {}).get('bm25_terms', 0)} |
|
| 544 |
+
| BM25 postings | {(counts or {}).get('bm25_postings', 0)} |
|
| 545 |
+
| Graph nodes | {(counts or {}).get('graph_nodes', 0)} |
|
| 546 |
+
| Graph edges | {(counts or {}).get('graph_edges', 0)} |
|
| 547 |
+
| 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}) |
|
| 548 |
+
|
| 549 |
+
## Canonical fields
|
| 550 |
+
|
| 551 |
+
`entry_cid`, `law_cid`, `record_type`, `jurisdiction`, `language`,
|
| 552 |
+
`instrument_id`, `instrument_title`, `article_number`, `article_title`,
|
| 553 |
+
`title`, `body`, `source_url`, `snapshot_date`, `coverage`, `license`,
|
| 554 |
+
`collector`, `source_dataset`, `source_revision`.
|
| 555 |
+
|
| 556 |
+
Unit policy: prefer article/section rows; fall back to law-level when
|
| 557 |
+
`articles.parquet` is empty.
|
| 558 |
+
|
| 559 |
+
## Index layout
|
| 560 |
+
|
| 561 |
+
Zstandard parquet shards with at most 4,096 rows.
|
| 562 |
+
|
| 563 |
+
- `indexes/bm25_keyword_shards.parquet` — lexical term ranges → BM25 posting shards
|
| 564 |
+
- `indexes/vector_chunks.parquet` — semantic routing centroids (rows sorted by cosine to shard centroid)
|
| 565 |
+
- `indexes/corpus_chunks.parquet` — document ranges → corpus shards
|
| 566 |
+
- `data/graph/nodes` / `data/graph/edges` — property graph
|
| 567 |
+
- `data/graph/adjacency/{{incoming,outgoing}}` — score-ordered neighbor pages
|
| 568 |
+
|
| 569 |
+
BM25: Okapi k1=1.2, b=0.75, title_weight=5, body_weight=1 (FTS5 unicode61-style tokenizer).
|
| 570 |
+
|
| 571 |
+
Graph: one node per `entry_cid` plus facet nodes (`_facet_cid(kind, value)` for
|
| 572 |
+
jurisdiction, language, instrument, source, status). Neighbor edges
|
| 573 |
+
`BM25_NEIGHBOR_OF` (k=8) carry score and matched terms. Structural edges:
|
| 574 |
+
`ARTICLE_OF` (article → parent law) when articles exist, plus `IDENTIFIED_BY_ELI`
|
| 575 |
+
/ `IDENTIFIED_BY` only when those identifiers are present in the source.
|
| 576 |
+
|
| 577 |
+
## Query
|
| 578 |
+
|
| 579 |
+
```
|
| 580 |
+
python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 10
|
| 581 |
+
python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 10
|
| 582 |
+
python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
|
| 583 |
+
```
|
| 584 |
+
|
| 585 |
+
## Publish later (operator)
|
| 586 |
+
|
| 587 |
+
```
|
| 588 |
+
export HF_TOKEN=... # never commit
|
| 589 |
+
hf upload-large-folder {hub_id} . \\
|
| 590 |
+
--repo-type dataset --no-private --num-workers 8 \\
|
| 591 |
+
--exclude "**/__pycache__/**" --exclude "**/*.pyc"
|
| 592 |
+
```
|
| 593 |
+
|
| 594 |
+
## Provenance
|
| 595 |
+
|
| 596 |
+
Packaged by country-laws-ir. Upstream collector and official license remain those
|
| 597 |
+
of `{src}`. CIDs identify local content; they do not prove public IPFS pinning.
|
| 598 |
+
"""
|
| 599 |
+
(out / "README.md").write_text(text, encoding="utf-8")
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def _write_skill(out: Path, country: dict[str, Any], hub_id: str) -> None:
|
| 603 |
+
skill_dir = out / "skill" / "query-country-laws-hf"
|
| 604 |
+
skill_dir.mkdir(parents=True, exist_ok=True)
|
| 605 |
+
name = country.get("name") or country.get("slug")
|
| 606 |
+
slug = country.get("slug")
|
| 607 |
+
text = f"""---
|
| 608 |
+
name: query-country-laws-hf
|
| 609 |
+
description: Query a local or Hub country-laws-ir GraphRAG release (BM25, vectors, graph neighbors). Research retrieval only — not legal advice.
|
| 610 |
+
---
|
| 611 |
+
|
| 612 |
+
# Query country-laws-ir (SkillCenter-style sparse GraphRAG)
|
| 613 |
+
|
| 614 |
+
Thin client for `{hub_id}` / local release roots that follow
|
| 615 |
+
`country-laws-ir-graphrag/v1` (layout family `skillcenter-huggingface-release/v3`).
|
| 616 |
+
|
| 617 |
+
**Not legal advice.** Official gazettes prevail. Retrieved hits are context only.
|
| 618 |
+
|
| 619 |
+
## Local
|
| 620 |
+
|
| 621 |
+
```bash
|
| 622 |
+
python scripts/query_country_laws_hf.py --local-dir . bm25 "constitution" --top-k 5
|
| 623 |
+
python scripts/query_country_laws_hf.py --local-dir . vector "money laundering" --top-k 5
|
| 624 |
+
python scripts/query_country_laws_hf.py --local-dir . graph neighbors <entry_cid>
|
| 625 |
+
```
|
| 626 |
+
|
| 627 |
+
Or:
|
| 628 |
+
|
| 629 |
+
```bash
|
| 630 |
+
python -m country_laws_ir query --local-dir /workspace/country-laws-ir/releases/ipfs_{slug}_laws_ir -- bm25 "constitution"
|
| 631 |
+
```
|
| 632 |
+
|
| 633 |
+
## Method
|
| 634 |
+
|
| 635 |
+
- Primary key `entry_cid` (CIDv1 raw sha2-256). `document_index` is a shard pointer.
|
| 636 |
+
- BM25 Okapi k1=1.2 b=0.75, title_weight=5, body_weight=1, FTS5-style tokenizer.
|
| 637 |
+
- Vectors `thenlper/gte-small` 384-d, mean-pool, L2, centroid-sorted shards.
|
| 638 |
+
- Graph: facets + `BM25_NEIGHBOR_OF` (k=8, score + matched terms) + `ARTICLE_OF`.
|
| 639 |
+
|
| 640 |
+
Do not treat retrieval as proof. Do not invent citations.
|
| 641 |
+
"""
|
| 642 |
+
(skill_dir / "SKILL.md").write_text(text, encoding="utf-8")
|
| 643 |
+
|
| 644 |
+
|
| 645 |
+
def package_release_sequential(
|
| 646 |
+
out: Path,
|
| 647 |
+
*,
|
| 648 |
+
corpus_path: Path,
|
| 649 |
+
bm25_documents_path: Path,
|
| 650 |
+
bm25_postings_path: Path,
|
| 651 |
+
bm25_stats: dict[str, Any],
|
| 652 |
+
graph: dict[str, Any] | Path,
|
| 653 |
+
vectors: dict[str, Any] | Path,
|
| 654 |
+
source_meta: dict[str, Any],
|
| 655 |
+
country: dict[str, Any],
|
| 656 |
+
code_root: Path,
|
| 657 |
+
normalization_report: dict[str, Any] | None = None,
|
| 658 |
+
expected_rows: int | None = None,
|
| 659 |
+
extra_manifest: dict[str, Any] | None = None,
|
| 660 |
+
) -> dict[str, Any]:
|
| 661 |
+
"""Write release layout one section at a time (never hold corpus+bm25+graph+vectors).
|
| 662 |
+
|
| 663 |
+
``graph`` / ``vectors`` may be in-memory dicts or pickle Paths.
|
| 664 |
+
Loads and frees each artifact before the next. Prefer this for n>=40k.
|
| 665 |
+
"""
|
| 666 |
+
from .mem import checkpoint, log_mem
|
| 667 |
+
|
| 668 |
+
def _load_obj(obj_or_path):
|
| 669 |
+
if isinstance(obj_or_path, (str, Path)):
|
| 670 |
+
p = Path(obj_or_path)
|
| 671 |
+
with p.open("rb") as f:
|
| 672 |
+
return pickle.load(f)
|
| 673 |
+
return obj_or_path
|
| 674 |
+
|
| 675 |
+
if out.exists():
|
| 676 |
+
shutil.rmtree(out)
|
| 677 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 678 |
+
indexes_dir = out / "indexes"
|
| 679 |
+
indexes_dir.mkdir(parents=True, exist_ok=True)
|
| 680 |
+
log_mem("package_seq_start")
|
| 681 |
+
|
| 682 |
+
# --- corpus ---
|
| 683 |
+
corpus = pd.read_parquet(corpus_path)
|
| 684 |
+
if expected_rows is not None and len(corpus) != expected_rows:
|
| 685 |
+
raise ValueError(f"corpus rows {len(corpus)} != expected {expected_rows}")
|
| 686 |
+
n_laws = int((corpus["record_type"] == "law").sum()) if "record_type" in corpus else 0
|
| 687 |
+
n_articles = int((corpus["record_type"] == "article").sum()) if "record_type" in corpus else 0
|
| 688 |
+
corpus_rows = int(len(corpus))
|
| 689 |
+
corpus_idx = write_sharded(
|
| 690 |
+
corpus, out / "data" / "corpus", "data/corpus",
|
| 691 |
+
kind="corpus", key_col="entry_cid", index_col="document_index",
|
| 692 |
+
)
|
| 693 |
+
write_parquet(indexes_dir / "corpus_chunks.parquet", _index_df(corpus_idx))
|
| 694 |
+
del corpus
|
| 695 |
+
gc.collect()
|
| 696 |
+
checkpoint("package_corpus_done")
|
| 697 |
+
|
| 698 |
+
# --- bm25 documents ---
|
| 699 |
+
documents = pd.read_parquet(bm25_documents_path)
|
| 700 |
+
bm25_doc_idx = write_sharded(
|
| 701 |
+
documents, out / "data" / "bm25" / "documents", "data/bm25/documents",
|
| 702 |
+
kind="bm25_documents", key_col="entry_cid", index_col="document_index",
|
| 703 |
+
)
|
| 704 |
+
write_parquet(indexes_dir / "bm25_document_chunks.parquet", _index_df(bm25_doc_idx))
|
| 705 |
+
n_bm25_docs = int(len(documents))
|
| 706 |
+
del documents
|
| 707 |
+
gc.collect()
|
| 708 |
+
|
| 709 |
+
postings = pd.read_parquet(bm25_postings_path)
|
| 710 |
+
posting_idx = write_sharded(
|
| 711 |
+
postings, out / "data" / "bm25" / "postings", "data/bm25/postings",
|
| 712 |
+
kind="bm25_postings", key_col="term",
|
| 713 |
+
)
|
| 714 |
+
for row, part_start in zip(posting_idx, range(len(posting_idx))):
|
| 715 |
+
shard_df = postings.iloc[part_start * MAX_ROWS_PER_FILE : (part_start + 1) * MAX_ROWS_PER_FILE]
|
| 716 |
+
row["term_count"] = int(shard_df["term"].nunique()) if not shard_df.empty else 0
|
| 717 |
+
row["posting_count"] = int(shard_df["document_indices"].map(len).sum()) if not shard_df.empty else 0
|
| 718 |
+
row["token_instance_count"] = row["posting_count"]
|
| 719 |
+
write_parquet(indexes_dir / "bm25_keyword_shards.parquet", _index_df(posting_idx))
|
| 720 |
+
n_posting_rows = int(len(postings))
|
| 721 |
+
del postings
|
| 722 |
+
gc.collect()
|
| 723 |
+
checkpoint("package_bm25_done")
|
| 724 |
+
|
| 725 |
+
# --- graph ---
|
| 726 |
+
graph = _load_obj(graph)
|
| 727 |
+
node_idx = write_sharded(
|
| 728 |
+
graph["nodes"], out / "data" / "graph" / "nodes", "data/graph/nodes",
|
| 729 |
+
kind="graph_nodes", key_col="node_cid",
|
| 730 |
+
)
|
| 731 |
+
write_parquet(indexes_dir / "graph_node_chunks.parquet", _index_df(node_idx))
|
| 732 |
+
edge_idx = write_sharded(
|
| 733 |
+
graph["edges"], out / "data" / "graph" / "edges", "data/graph/edges",
|
| 734 |
+
kind="graph_edges", key_col="edge_cid",
|
| 735 |
+
)
|
| 736 |
+
write_parquet(indexes_dir / "graph_edge_chunks.parquet", _index_df(edge_idx))
|
| 737 |
+
incoming = graph["incoming"]
|
| 738 |
+
outgoing = graph["outgoing"]
|
| 739 |
+
in_idx = write_sharded(
|
| 740 |
+
incoming if incoming is not None and not incoming.empty else pd.DataFrame(
|
| 741 |
+
columns=["node_cid", "page_index", "direction"]
|
| 742 |
+
),
|
| 743 |
+
out / "data" / "graph" / "adjacency" / "incoming",
|
| 744 |
+
"data/graph/adjacency/incoming",
|
| 745 |
+
kind="graph_incoming_adjacency",
|
| 746 |
+
key_col="node_cid",
|
| 747 |
+
)
|
| 748 |
+
out_idx = write_sharded(
|
| 749 |
+
outgoing if outgoing is not None and not outgoing.empty else pd.DataFrame(
|
| 750 |
+
columns=["node_cid", "page_index", "direction"]
|
| 751 |
+
),
|
| 752 |
+
out / "data" / "graph" / "adjacency" / "outgoing",
|
| 753 |
+
"data/graph/adjacency/outgoing",
|
| 754 |
+
kind="graph_outgoing_adjacency",
|
| 755 |
+
key_col="node_cid",
|
| 756 |
+
)
|
| 757 |
+
for rows, direction in ((in_idx, "incoming"), (out_idx, "outgoing")):
|
| 758 |
+
for r in rows:
|
| 759 |
+
r["direction"] = direction
|
| 760 |
+
r["adjacency_count"] = r.get("row_count", 0)
|
| 761 |
+
r["node_count"] = r.get("row_count", 0)
|
| 762 |
+
r["first_page_index"] = 0
|
| 763 |
+
r["last_page_index"] = 0
|
| 764 |
+
write_parquet(indexes_dir / "graph_incoming_adjacency.parquet", _index_df(in_idx))
|
| 765 |
+
write_parquet(indexes_dir / "graph_outgoing_adjacency.parquet", _index_df(out_idx))
|
| 766 |
+
gstats = graph["stats"]
|
| 767 |
+
n_graph_nodes = int(len(graph["nodes"]))
|
| 768 |
+
n_graph_edges = int(len(graph["edges"]))
|
| 769 |
+
n_in = int(len(incoming)) if incoming is not None else 0
|
| 770 |
+
n_out = int(len(outgoing)) if outgoing is not None else 0
|
| 771 |
+
edge_types = gstats.get("edge_types") or [
|
| 772 |
+
"HAS_JURISDICTION", "HAS_LANGUAGE", "BELONGS_TO_LAW", "HAS_ARTICLE", "BM25_NEIGHBOR_OF",
|
| 773 |
+
]
|
| 774 |
+
del graph, incoming, outgoing
|
| 775 |
+
gc.collect()
|
| 776 |
+
checkpoint("package_graph_done")
|
| 777 |
+
|
| 778 |
+
# --- vectors ---
|
| 779 |
+
vectors = _load_obj(vectors)
|
| 780 |
+
vectors_df = vectors["vectors"]
|
| 781 |
+
if "embedding" in vectors_df.columns and vectors_df["embedding"].isna().all():
|
| 782 |
+
vectors_write = vectors_df.drop(columns=["embedding"])
|
| 783 |
+
vectors_write["embedding_status"] = "stub_missing"
|
| 784 |
+
else:
|
| 785 |
+
vectors_write = vectors_df
|
| 786 |
+
vec_idx = write_sharded(
|
| 787 |
+
vectors_write, out / "data" / "vectors", "data/vectors",
|
| 788 |
+
kind="vectors", key_col="entry_cid", index_col="document_index",
|
| 789 |
+
)
|
| 790 |
+
meta_by_cluster = {m["cluster_id"]: m for m in vectors["chunk_meta"]}
|
| 791 |
+
for r in vec_idx:
|
| 792 |
+
m = meta_by_cluster.get(r["shard_id"], {})
|
| 793 |
+
r["centroid"] = m.get("centroid", [])
|
| 794 |
+
r["shard_centroid"] = m.get("shard_centroid", [])
|
| 795 |
+
r["centroid_min_score"] = m.get("centroid_min_score", 0.0)
|
| 796 |
+
r["centroid_shard_count"] = m.get("centroid_shard_count", 1)
|
| 797 |
+
r["chunk_in_cluster"] = m.get("chunk_in_cluster", 0)
|
| 798 |
+
r["cluster_id"] = m.get("cluster_id", r["shard_id"])
|
| 799 |
+
r["dimension"] = 384
|
| 800 |
+
r["model_name"] = "thenlper/gte-small"
|
| 801 |
+
if m.get("stub"):
|
| 802 |
+
r["stub"] = True
|
| 803 |
+
r["stub_reason"] = m.get("stub_reason", "")
|
| 804 |
+
write_parquet(indexes_dir / "vector_chunks.parquet", _index_df(vec_idx))
|
| 805 |
+
vstats = vectors["stats"]
|
| 806 |
+
n_vectors = int(len(vectors_df))
|
| 807 |
+
del vectors, vectors_df, vectors_write
|
| 808 |
+
gc.collect()
|
| 809 |
+
checkpoint("package_vectors_done")
|
| 810 |
+
|
| 811 |
+
# --- bundle code ---
|
| 812 |
+
pkg_src = Path(__file__).resolve().parent
|
| 813 |
+
dest_pkg = out / "country_laws_ir"
|
| 814 |
+
shutil.copytree(
|
| 815 |
+
pkg_src, dest_pkg, dirs_exist_ok=True,
|
| 816 |
+
ignore=shutil.ignore_patterns("__pycache__", "*.pyc", ".venv"),
|
| 817 |
+
)
|
| 818 |
+
scripts_dir = out / "scripts"
|
| 819 |
+
scripts_dir.mkdir(exist_ok=True)
|
| 820 |
+
for name in (
|
| 821 |
+
"build_country_laws_ir.py", "normalize_country_laws.py",
|
| 822 |
+
"query_country_laws_hf.py", "query_country_laws_ir.py", "generate_country_laws_ir.py",
|
| 823 |
+
):
|
| 824 |
+
src = code_root / "scripts" / name
|
| 825 |
+
if src.exists():
|
| 826 |
+
shutil.copy2(src, scripts_dir / name)
|
| 827 |
+
shutil.copy2(pkg_src / "normalize.py", out / "normalize.py")
|
| 828 |
+
shutil.copy2(pkg_src / "query.py", out / "query.py")
|
| 829 |
+
shutil.copy2(pkg_src / "build.py", out / "build.py")
|
| 830 |
+
hub_id = target_repo(country["slug"])
|
| 831 |
+
_write_skill(out, country, hub_id=hub_id)
|
| 832 |
+
|
| 833 |
+
reports_dir = out / "reports"
|
| 834 |
+
reports_dir.mkdir(exist_ok=True)
|
| 835 |
+
if normalization_report is not None:
|
| 836 |
+
payload = json.dumps(normalization_report, indent=2, ensure_ascii=False) + "\n"
|
| 837 |
+
(out / "normalization_report.json").write_text(payload, encoding="utf-8")
|
| 838 |
+
(reports_dir / "normalization.json").write_text(payload, encoding="utf-8")
|
| 839 |
+
|
| 840 |
+
counts = {
|
| 841 |
+
"bm25_document_chunks": len(bm25_doc_idx),
|
| 842 |
+
"bm25_documents": n_bm25_docs,
|
| 843 |
+
"bm25_keyword_shards": len(posting_idx),
|
| 844 |
+
"bm25_posting_rows": n_posting_rows,
|
| 845 |
+
"bm25_postings": int(bm25_stats["n_postings"]),
|
| 846 |
+
"bm25_terms": int(bm25_stats["n_terms"]),
|
| 847 |
+
"corpus_chunks": len(corpus_idx),
|
| 848 |
+
"corpus_rows": corpus_rows,
|
| 849 |
+
"graph_edge_chunks": len(edge_idx),
|
| 850 |
+
"graph_edges": n_graph_edges,
|
| 851 |
+
"graph_incoming_adjacency_edges": n_graph_edges,
|
| 852 |
+
"graph_incoming_adjacency_rows": n_in,
|
| 853 |
+
"graph_incoming_adjacency_shards": len(in_idx),
|
| 854 |
+
"graph_node_chunks": len(node_idx),
|
| 855 |
+
"graph_nodes": n_graph_nodes,
|
| 856 |
+
"graph_outgoing_adjacency_edges": n_graph_edges,
|
| 857 |
+
"graph_outgoing_adjacency_rows": n_out,
|
| 858 |
+
"graph_outgoing_adjacency_shards": len(out_idx),
|
| 859 |
+
"vector_chunks": len(vec_idx),
|
| 860 |
+
"vector_rows": n_vectors,
|
| 861 |
+
"n_laws": n_laws,
|
| 862 |
+
"n_articles": n_articles,
|
| 863 |
+
}
|
| 864 |
+
|
| 865 |
+
def idx_desc(name: str) -> dict[str, Any]:
|
| 866 |
+
path = indexes_dir / name
|
| 867 |
+
if not path.is_file():
|
| 868 |
+
return {"relative_path": f"indexes/{name}", "present": False}
|
| 869 |
+
return file_descriptor(path, f"indexes/{name}")
|
| 870 |
+
|
| 871 |
+
manifest = {
|
| 872 |
+
"schema_version": SCHEMA_VERSION,
|
| 873 |
+
"layout_family": LAYOUT_FAMILY,
|
| 874 |
+
"packager_version": __version__,
|
| 875 |
+
"primary_key": "entry_cid",
|
| 876 |
+
"dataset_id": source_meta["source_dataset"],
|
| 877 |
+
"dataset_repo_id": hub_id,
|
| 878 |
+
"dataset_revision": source_meta["source_revision"],
|
| 879 |
+
"country": country,
|
| 880 |
+
"disclaimer": "Research snapshot. Not legal advice. The official gazette / authentic source prevails.",
|
| 881 |
+
"bm25": {k: (bm25_stats or {}).get(k) for k in (
|
| 882 |
+
"k1", "b", "title_weight", "body_weight", "average_document_length",
|
| 883 |
+
"tokenizer", "max_query_terms", "posting_rows_per_record", "terms_per_shard",
|
| 884 |
+
) if k in bm25_stats},
|
| 885 |
+
"counts": counts,
|
| 886 |
+
"parquet": {
|
| 887 |
+
"compression": "zstd",
|
| 888 |
+
"compression_level": 6,
|
| 889 |
+
"max_rows_per_file": MAX_ROWS_PER_FILE,
|
| 890 |
+
"row_group_size": MAX_ROWS_PER_FILE,
|
| 891 |
+
},
|
| 892 |
+
"graph": {
|
| 893 |
+
"adjacency_pointers_per_row": ADJ_POINTERS_PER_ROW,
|
| 894 |
+
"adjacency_pointers_per_shard": ADJ_POINTERS_PER_SHARD,
|
| 895 |
+
"directions": ["incoming", "outgoing"],
|
| 896 |
+
"max_remote_walk_depth": 8,
|
| 897 |
+
"ordering": "score_desc_nulls_last",
|
| 898 |
+
"edge_types": edge_types,
|
| 899 |
+
},
|
| 900 |
+
"vector": vstats,
|
| 901 |
+
"canonical_fields": [
|
| 902 |
+
"entry_cid", "law_cid", "record_type", "jurisdiction", "language",
|
| 903 |
+
"instrument_id", "instrument_title", "article_number", "article_title",
|
| 904 |
+
"title", "body", "source_url", "snapshot_date", "coverage", "license",
|
| 905 |
+
"collector", "source_dataset", "source_revision",
|
| 906 |
+
],
|
| 907 |
+
"input_sha256": {
|
| 908 |
+
"laws.parquet": source_meta.get("laws_sha256"),
|
| 909 |
+
"articles.parquet": source_meta.get("articles_sha256"),
|
| 910 |
+
},
|
| 911 |
+
"model_id": (vstats or {}).get("model_name", "thenlper/gte-small"),
|
| 912 |
+
"cid": {
|
| 913 |
+
"codec": "raw",
|
| 914 |
+
"hash": "sha2-256",
|
| 915 |
+
"multibase": "base32",
|
| 916 |
+
"payload": "json.dumps(obj, sort_keys=True, ensure_ascii=False, separators=(',', ':')).encode('utf-8')",
|
| 917 |
+
},
|
| 918 |
+
"normalization": normalization_report or {},
|
| 919 |
+
"packaging_mode": "sequential_spill",
|
| 920 |
+
"schema_mapping": {
|
| 921 |
+
"laws": {
|
| 922 |
+
"id": "instrument_id", "title": "instrument_title", "text": "body",
|
| 923 |
+
"article_count_dtype_source": source_meta.get("article_count_dtype"),
|
| 924 |
+
},
|
| 925 |
+
"articles": {
|
| 926 |
+
"id": "source_id / article identity", "law_id": "instrument_id",
|
| 927 |
+
"title": "article_title", "text": "body",
|
| 928 |
+
},
|
| 929 |
+
"unit_policy": "prefer articles; fall back to law-level when articles empty",
|
| 930 |
+
"required_law_columns": ["id", "title", "text"],
|
| 931 |
+
"required_article_columns": ["id", "law_id", "title", "text"],
|
| 932 |
+
"fail_closed": True,
|
| 933 |
+
"notes": (
|
| 934 |
+
"Malta and Germany share the same column names. Drift: Malta article_count "
|
| 935 |
+
"is int64, Germany article_count is int32; Germany eli is often null. "
|
| 936 |
+
"Identifiers are never invented. Layout matches SkillCenter HF release / publicus-ir family."
|
| 937 |
+
),
|
| 938 |
+
},
|
| 939 |
+
"indexes": {
|
| 940 |
+
"bm25_document_chunks": idx_desc("bm25_document_chunks.parquet"),
|
| 941 |
+
"bm25_keyword_shards": idx_desc("bm25_keyword_shards.parquet"),
|
| 942 |
+
"corpus_chunks": idx_desc("corpus_chunks.parquet"),
|
| 943 |
+
"graph_edge_chunks": idx_desc("graph_edge_chunks.parquet"),
|
| 944 |
+
"graph_incoming_adjacency": idx_desc("graph_incoming_adjacency.parquet"),
|
| 945 |
+
"graph_node_chunks": idx_desc("graph_node_chunks.parquet"),
|
| 946 |
+
"graph_outgoing_adjacency": idx_desc("graph_outgoing_adjacency.parquet"),
|
| 947 |
+
"vector_chunks": idx_desc("vector_chunks.parquet"),
|
| 948 |
+
},
|
| 949 |
+
"source": source_meta,
|
| 950 |
+
}
|
| 951 |
+
if extra_manifest:
|
| 952 |
+
manifest.update(extra_manifest)
|
| 953 |
+
(out / "manifest.json").write_text(
|
| 954 |
+
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
|
| 955 |
+
)
|
| 956 |
+
_write_readme(
|
| 957 |
+
out,
|
| 958 |
+
country,
|
| 959 |
+
source_meta,
|
| 960 |
+
counts,
|
| 961 |
+
bm25_stats,
|
| 962 |
+
gstats,
|
| 963 |
+
vstats,
|
| 964 |
+
hub_id,
|
| 965 |
+
normalization_report=normalization_report,
|
| 966 |
+
)
|
| 967 |
+
_write_gitattributes(out)
|
| 968 |
+
_write_dataset_configs(out)
|
| 969 |
+
checkpoint("package_seq_done")
|
| 970 |
+
return manifest
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def package_from_spill(
|
| 974 |
+
out: Path,
|
| 975 |
+
spill: Path,
|
| 976 |
+
corpus_path: Path,
|
| 977 |
+
source_meta: dict[str, Any],
|
| 978 |
+
country: dict[str, Any],
|
| 979 |
+
code_root: Path,
|
| 980 |
+
normalization_report: dict[str, Any] | None = None,
|
| 981 |
+
expected_rows: int | None = None,
|
| 982 |
+
extra_manifest: dict[str, Any] | None = None,
|
| 983 |
+
) -> dict[str, Any]:
|
| 984 |
+
"""Package from spill dir artifacts: bm25_*.parquet, bm25_stats.json, graph.pkl, vectors.pkl."""
|
| 985 |
+
import json as _json
|
| 986 |
+
import pickle as _pickle
|
| 987 |
+
|
| 988 |
+
spill = Path(spill)
|
| 989 |
+
stats_json = spill / "bm25_stats.json"
|
| 990 |
+
stats_pkl = spill / "bm25_stats.pkl"
|
| 991 |
+
if stats_json.is_file():
|
| 992 |
+
bm25_stats = _json.loads(stats_json.read_text(encoding="utf-8"))
|
| 993 |
+
else:
|
| 994 |
+
with stats_pkl.open("rb") as f:
|
| 995 |
+
bm25_stats = _pickle.load(f)
|
| 996 |
+
return package_release_sequential(
|
| 997 |
+
out,
|
| 998 |
+
corpus_path=Path(corpus_path),
|
| 999 |
+
bm25_documents_path=spill / "bm25_documents.parquet",
|
| 1000 |
+
bm25_postings_path=spill / "bm25_postings.parquet",
|
| 1001 |
+
bm25_stats=bm25_stats,
|
| 1002 |
+
graph=spill / "graph.pkl",
|
| 1003 |
+
vectors=spill / "vectors.pkl",
|
| 1004 |
+
source_meta=source_meta,
|
| 1005 |
+
country=country,
|
| 1006 |
+
code_root=Path(code_root),
|
| 1007 |
+
normalization_report=normalization_report,
|
| 1008 |
+
expected_rows=expected_rows,
|
| 1009 |
+
extra_manifest=extra_manifest,
|
| 1010 |
+
)
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/parquet_io.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ZSTD parquet shard writer matching skillcenter-huggingface-release/v3."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Iterable
|
| 8 |
+
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import pyarrow as pa
|
| 11 |
+
import pyarrow.parquet as pq
|
| 12 |
+
|
| 13 |
+
from . import MAX_ROWS_PER_FILE, SCHEMA_VERSION
|
| 14 |
+
from .cidutil import file_descriptor
|
| 15 |
+
|
| 16 |
+
COMPRESSION = "zstd"
|
| 17 |
+
COMPRESSION_LEVEL = 6
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def write_parquet(path: Path, df: pd.DataFrame) -> None:
|
| 21 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 22 |
+
table = pa.Table.from_pandas(df, preserve_index=False)
|
| 23 |
+
pq.write_table(
|
| 24 |
+
table,
|
| 25 |
+
path,
|
| 26 |
+
compression=COMPRESSION,
|
| 27 |
+
compression_level=COMPRESSION_LEVEL,
|
| 28 |
+
row_group_size=min(MAX_ROWS_PER_FILE, max(len(df), 1)),
|
| 29 |
+
use_dictionary=True,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def shard_frames(df: pd.DataFrame, max_rows: int = MAX_ROWS_PER_FILE) -> list[pd.DataFrame]:
|
| 34 |
+
if df.empty:
|
| 35 |
+
return [df.copy()]
|
| 36 |
+
n = int(math.ceil(len(df) / max_rows))
|
| 37 |
+
return [df.iloc[i * max_rows : (i + 1) * max_rows].copy() for i in range(n)]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def write_sharded(
|
| 41 |
+
df: pd.DataFrame,
|
| 42 |
+
out_dir: Path,
|
| 43 |
+
relative_dir: str,
|
| 44 |
+
kind: str,
|
| 45 |
+
key_col: str | None = None,
|
| 46 |
+
index_col: str | None = None,
|
| 47 |
+
extra_index: dict | None = None,
|
| 48 |
+
) -> list[dict[str, Any]]:
|
| 49 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
shards = shard_frames(df)
|
| 51 |
+
rows: list[dict[str, Any]] = []
|
| 52 |
+
for i, part in enumerate(shards):
|
| 53 |
+
name = f"part-{i:06d}.parquet"
|
| 54 |
+
path = out_dir / name
|
| 55 |
+
write_parquet(path, part)
|
| 56 |
+
rel = f"{relative_dir}/{name}"
|
| 57 |
+
first_key = last_key = ""
|
| 58 |
+
if key_col and key_col in part.columns and not part.empty:
|
| 59 |
+
keys = part[key_col].astype(str)
|
| 60 |
+
first_key = keys.iloc[0]
|
| 61 |
+
last_key = keys.iloc[-1]
|
| 62 |
+
start_idx = end_idx = 0
|
| 63 |
+
if index_col and index_col in part.columns and not part.empty:
|
| 64 |
+
start_idx = int(part[index_col].iloc[0])
|
| 65 |
+
end_idx = int(part[index_col].iloc[-1])
|
| 66 |
+
desc = file_descriptor(
|
| 67 |
+
path,
|
| 68 |
+
rel,
|
| 69 |
+
extra={
|
| 70 |
+
"shard_id": i,
|
| 71 |
+
"kind": kind,
|
| 72 |
+
"row_count": int(len(part)),
|
| 73 |
+
"first_key": first_key,
|
| 74 |
+
"last_key": last_key,
|
| 75 |
+
"start_document_index": start_idx,
|
| 76 |
+
"end_document_index": end_idx,
|
| 77 |
+
"schema_version": SCHEMA_VERSION,
|
| 78 |
+
},
|
| 79 |
+
)
|
| 80 |
+
if extra_index:
|
| 81 |
+
desc.update(extra_index)
|
| 82 |
+
rows.append(desc)
|
| 83 |
+
return rows
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/profiles.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-language legal heading lexicons for country-law structure extraction.
|
| 2 |
+
|
| 3 |
+
Oregon (ORS) is English title/chapter/section. Other gazettes use their own
|
| 4 |
+
words (Artikel, Titre, Artículo, 条, مادة). This table is how we *score*
|
| 5 |
+
whether a split used the right language — not a claim that every country
|
| 6 |
+
has a dedicated parser.
|
| 7 |
+
|
| 8 |
+
Languages with no lexicon (ar, zh, ja, ko, …) must not be force-split on
|
| 9 |
+
Latin TITLE/ARTICLE markers; collectors may already have article rows.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from collections import Counter
|
| 15 |
+
import re
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
# keyword -> list of (kind, language); some words are shared (article).
|
| 19 |
+
HEADING_LEXICON: dict[str, list[tuple[str, str]]] = {}
|
| 20 |
+
|
| 21 |
+
def _add(lang: str, kind: str, *words: str) -> None:
|
| 22 |
+
for word in words:
|
| 23 |
+
HEADING_LEXICON.setdefault(word.casefold(), []).append((kind, lang))
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
_add("en", "title", "title")
|
| 27 |
+
_add("en", "chapter", "chapter")
|
| 28 |
+
# The period is part of the token so a bare "ch" is not a heading.
|
| 29 |
+
_add("en", "chapter", "ch.")
|
| 30 |
+
_add("en", "part", "part", "division")
|
| 31 |
+
_add("en", "article", "article")
|
| 32 |
+
_add("en", "section", "section", "sec.", "rule", "regulation", "schedule", "annex", "appendix")
|
| 33 |
+
# The period is part of the token so a bare "can" is not a heading.
|
| 34 |
+
_add("la", "article", "can.")
|
| 35 |
+
_add("fr", "section", "annexe")
|
| 36 |
+
_add("es", "section", "anexo")
|
| 37 |
+
_add("de", "section", "anlage")
|
| 38 |
+
_add("nl", "section", "bijlage")
|
| 39 |
+
_add("it", "section", "allegato")
|
| 40 |
+
_add("pl", "section", "załącznik")
|
| 41 |
+
_add("sv", "section", "bilaga")
|
| 42 |
+
_add("fi", "section", "liite")
|
| 43 |
+
_add("cs", "section", "příloha")
|
| 44 |
+
_add("pt", "section", "anexo")
|
| 45 |
+
|
| 46 |
+
_add("fr", "title", "titre")
|
| 47 |
+
_add("fr", "chapter", "chapitre")
|
| 48 |
+
_add("fr", "part", "partie")
|
| 49 |
+
_add("fr", "article", "article")
|
| 50 |
+
_add("fr", "section", "section", "paragraphe")
|
| 51 |
+
|
| 52 |
+
_add("de", "title", "titel")
|
| 53 |
+
_add("de", "chapter", "kapitel")
|
| 54 |
+
_add("de", "part", "teil")
|
| 55 |
+
_add("de", "article", "artikel")
|
| 56 |
+
_add("de", "section", "abschnitt", "unterabschnitt", "paragraf", "anhang")
|
| 57 |
+
|
| 58 |
+
_add("nl", "title", "titel")
|
| 59 |
+
_add("nl", "chapter", "hoofdstuk")
|
| 60 |
+
_add("nl", "part", "deel")
|
| 61 |
+
_add("nl", "article", "artikel")
|
| 62 |
+
_add("nl", "section", "paragraaf", "afdeling", "kerndoel")
|
| 63 |
+
|
| 64 |
+
_add("es", "title", "título", "titulo")
|
| 65 |
+
_add("es", "chapter", "capítulo", "capitulo", "subcapítulo", "subcapitulo")
|
| 66 |
+
_add("es", "part", "parte")
|
| 67 |
+
_add("es", "article", "artículo", "articulo")
|
| 68 |
+
# The period is part of the token so a bare "arto" is not a heading.
|
| 69 |
+
_add("es", "article", "arto.")
|
| 70 |
+
_add("es", "section", "sección", "seccion")
|
| 71 |
+
_add("es", "article", "disposición", "disposicion")
|
| 72 |
+
|
| 73 |
+
_add("pt", "title", "título", "titulo")
|
| 74 |
+
_add("pt", "chapter", "capítulo", "capitulo")
|
| 75 |
+
_add("pt", "part", "parte")
|
| 76 |
+
_add("pt", "article", "artigo")
|
| 77 |
+
_add("pt", "section", "secção", "secao")
|
| 78 |
+
# Brazil SUBSEÇÃO folds to subsecao. Portugal SUBSECÇÃO folds to subseccao.
|
| 79 |
+
_add("pt", "section", "subseção", "subsecção")
|
| 80 |
+
|
| 81 |
+
_add("it", "title", "titolo")
|
| 82 |
+
_add("it", "chapter", "capitolo")
|
| 83 |
+
_add("it", "part", "parte")
|
| 84 |
+
_add("it", "article", "articolo")
|
| 85 |
+
_add("it", "section", "sezione")
|
| 86 |
+
|
| 87 |
+
_add("el", "article", "άρθρο", "αρθρο")
|
| 88 |
+
_add("el", "chapter", "κεφάλαιο")
|
| 89 |
+
_add("el", "section", "τμήμα", "ενότητα")
|
| 90 |
+
_add("hu", "article", "szakasz", "cikk")
|
| 91 |
+
_add("cs", "article", "článek")
|
| 92 |
+
# The period is part of the token so a bare "cl" is not a heading.
|
| 93 |
+
_add("cs", "article", "čl.")
|
| 94 |
+
_add("cs", "chapter", "kapitola")
|
| 95 |
+
_add("cs", "section", "odstavec", "odst.")
|
| 96 |
+
_add("sk", "article", "článok")
|
| 97 |
+
_add("sl", "article", "člen")
|
| 98 |
+
_add("nb", "article", "artikkel")
|
| 99 |
+
_add("sv", "article", "paragraf")
|
| 100 |
+
_add("fi", "article", "pykälä")
|
| 101 |
+
_add("fi", "chapter", "luku")
|
| 102 |
+
_add("is", "article", "grein")
|
| 103 |
+
_add("lv", "article", "pants")
|
| 104 |
+
_add("lv", "chapter", "nodaļa")
|
| 105 |
+
_add("et", "article", "paragrahv")
|
| 106 |
+
_add("et", "chapter", "peatükk")
|
| 107 |
+
_add("pl", "article", "artykuł", "artykul")
|
| 108 |
+
_add("ro", "article", "articolul", "articol")
|
| 109 |
+
_add("mt", "article", "artikolu")
|
| 110 |
+
_add("zh", "article", "条", "條")
|
| 111 |
+
_add("ar", "article", "مادة", "المادة", "الماده", "املادة", "املاده")
|
| 112 |
+
_add("ar", "chapter", "الباب")
|
| 113 |
+
_add("ar", "part", "الكتاب")
|
| 114 |
+
_add("ar", "section", "الفصل", "ملحق", "الفرع", "القسم")
|
| 115 |
+
_add("fa", "article", "ماده")
|
| 116 |
+
_add("fa", "section", "تبصره", "بند")
|
| 117 |
+
_add("ja", "article", "条")
|
| 118 |
+
_add("ko", "article", "조")
|
| 119 |
+
_add("he", "article", "סעיף")
|
| 120 |
+
_add("he", "chapter", "פרק")
|
| 121 |
+
_add("he", "part", "חלק")
|
| 122 |
+
_add("he", "section", "סימן", "תוספת", "תקנה")
|
| 123 |
+
_add("th", "article", "มาตรา")
|
| 124 |
+
_add("th", "chapter", "หมวด")
|
| 125 |
+
_add("th", "section", "ข้อ", "วรรค")
|
| 126 |
+
_add("hi", "article", "धारा")
|
| 127 |
+
_add("bn", "article", "ধারা")
|
| 128 |
+
_add("ru", "article", "статья")
|
| 129 |
+
_add("ru", "chapter", "глава")
|
| 130 |
+
_add("ru", "title", "раздел")
|
| 131 |
+
_add("uk", "article", "стаття")
|
| 132 |
+
_add("bg", "article", "член", "чл")
|
| 133 |
+
_add("mk", "article", "член")
|
| 134 |
+
_add("sr", "article", "чла��")
|
| 135 |
+
_add("hr", "article", "članak")
|
| 136 |
+
_add("hr", "chapter", "poglavlje")
|
| 137 |
+
_add("bs", "article", "članak")
|
| 138 |
+
_add("sq", "article", "neni")
|
| 139 |
+
_add("tr", "article", "madde")
|
| 140 |
+
_add("az", "article", "maddə")
|
| 141 |
+
_add("uz", "article", "модда")
|
| 142 |
+
_add("mn", "article", "зүйл")
|
| 143 |
+
_add("lo", "article", "ມາດຕາ")
|
| 144 |
+
_add("id", "article", "pasal")
|
| 145 |
+
_add("id", "chapter", "bab")
|
| 146 |
+
_add("ms", "article", "seksyen")
|
| 147 |
+
_add("ms", "part", "bahagian")
|
| 148 |
+
_add("lt", "article", "straipsnis")
|
| 149 |
+
_add("ta", "article", "பிரிவு")
|
| 150 |
+
_add("el", "part", "μέρος")
|
| 151 |
+
_add("el", "section", "παράγραφος")
|
| 152 |
+
_add("uk", "title", "розділ")
|
| 153 |
+
_add("zh", "chapter", "章")
|
| 154 |
+
_add("ja", "chapter", "章")
|
| 155 |
+
_add("ko", "chapter", "장")
|
| 156 |
+
_add("vi", "article", "điều")
|
| 157 |
+
_add("vi", "chapter", "chương")
|
| 158 |
+
_add("ka", "article", "მუხლი")
|
| 159 |
+
_add("hy", "article", "հոդված")
|
| 160 |
+
_add("am", "article", "አንቀጽ")
|
| 161 |
+
_add("km", "article", "មាត្រា")
|
| 162 |
+
_add("my", "article", "ပုဒ်မ")
|
| 163 |
+
_add("ne", "article", "दफा")
|
| 164 |
+
_add("si", "article", "වගන්තිය")
|
| 165 |
+
_add("kk", "article", "бап")
|
| 166 |
+
_add("uz", "article", "modda")
|
| 167 |
+
_add("be", "article", "артыкул")
|
| 168 |
+
_add("ky", "article", "берене")
|
| 169 |
+
_add("ur", "article", "دفعہ")
|
| 170 |
+
_add("so", "article", "qodob", "qodobka")
|
| 171 |
+
_add("ga", "article", "airteagal")
|
| 172 |
+
_add("cy", "article", "erthygl")
|
| 173 |
+
_add("fil", "article", "artikulo")
|
| 174 |
+
_add("fil", "section", "seksyon")
|
| 175 |
+
_add("fil", "chapter", "kabanata")
|
| 176 |
+
_add("id", "part", "bagian")
|
| 177 |
+
_add("vi", "part", "mục")
|
| 178 |
+
_add("sw", "part", "sehemu")
|
| 179 |
+
_add("ht", "article", "atik")
|
| 180 |
+
_add("eu", "article", "artikulua")
|
| 181 |
+
_add("da", "section", "stk")
|
| 182 |
+
_add("nb", "section", "ledd")
|
| 183 |
+
_add("de", "section", "absatz")
|
| 184 |
+
_add("es", "section", "apartado")
|
| 185 |
+
_add("it", "section", "comma")
|
| 186 |
+
_add("tr", "section", "fıkra")
|
| 187 |
+
_add("hr", "section", "stavak")
|
| 188 |
+
_add("bg", "section", "ал")
|
| 189 |
+
_add("te", "article", "ప్రకరణము", "ప్రకరణ")
|
| 190 |
+
_add("kn", "article", "ಪ್ರಕರಣ")
|
| 191 |
+
_add("gu", "article", "કલમ")
|
| 192 |
+
_add("pa", "article", "ਧਾਰਾ")
|
| 193 |
+
_add("ml", "article", "വകുപ്പ്")
|
| 194 |
+
_add("th", "title", "ลักษณะ")
|
| 195 |
+
_add("zh", "part", "编")
|
| 196 |
+
_add("ja", "part", "編")
|
| 197 |
+
_add("ko", "part", "편")
|
| 198 |
+
_add("tg", "article", "модда")
|
| 199 |
+
_add("sw", "article", "kifungu")
|
| 200 |
+
_add("ca", "article", "article")
|
| 201 |
+
_add("ca", "chapter", "capítol", "capitol")
|
| 202 |
+
_add("ca", "title", "títol", "titol")
|
| 203 |
+
_add("ca", "section", "secció", "seccio")
|
| 204 |
+
_add("pl", "chapter", "rozdział")
|
| 205 |
+
_add("pl", "title", "dział")
|
| 206 |
+
_add("ro", "chapter", "capitolul")
|
| 207 |
+
_add("ro", "title", "titlul")
|
| 208 |
+
_add("it", "chapter", "capo")
|
| 209 |
+
_add("cs", "chapter", "hlava")
|
| 210 |
+
_add("sk", "chapter", "hlava")
|
| 211 |
+
_add("es", "part", "libro")
|
| 212 |
+
_add("sv", "chapter", "kap")
|
| 213 |
+
_add("km", "chapter", "ជំពូក")
|
| 214 |
+
_add("lo", "part", "ພາກ")
|
| 215 |
+
_add("my", "chapter", "အခန်း")
|
| 216 |
+
_add("ka", "chapter", "თავი")
|
| 217 |
+
_add("hy", "chapter", "գլուխ")
|
| 218 |
+
_add("am", "chapter", "ምዕራፍ")
|
| 219 |
+
_add("sq", "chapter", "kreu")
|
| 220 |
+
_add("hu", "chapter", "fejezet")
|
| 221 |
+
_add("tr", "chapter", "bölüm")
|
| 222 |
+
_add("az", "chapter", "fəsil")
|
| 223 |
+
_add("lt", "chapter", "skyrius")
|
| 224 |
+
_add("is", "chapter", "kafli")
|
| 225 |
+
_add("ga", "chapter", "caibidil")
|
| 226 |
+
_add("cy", "chapter", "pennod")
|
| 227 |
+
_add("mt", "chapter", "kapitolu")
|
| 228 |
+
_add("ht", "chapter", "chapit")
|
| 229 |
+
_add("sw", "chapter", "sura")
|
| 230 |
+
_add("nb", "chapter", "kapittel")
|
| 231 |
+
_add("ha", "chapter", "sashe")
|
| 232 |
+
_add("mg", "chapter", "andiany")
|
| 233 |
+
_add("mi", "part", "wāhanga", "wahanga")
|
| 234 |
+
_add("sm", "part", "vaega")
|
| 235 |
+
_add("to", "article", "kupu")
|
| 236 |
+
_add("fj", "chapter", "wase")
|
| 237 |
+
_add("tpi", "part", "hap")
|
| 238 |
+
_add("fo", "chapter", "kapittul")
|
| 239 |
+
_add("bi", "article", "atikol")
|
| 240 |
+
_add("rw", "article", "ingingo")
|
| 241 |
+
_add("zu", "chapter", "isigaba")
|
| 242 |
+
_add("xh", "chapter", "icandelo")
|
| 243 |
+
_add("st", "part", "karolo")
|
| 244 |
+
_add("tn", "chapter", "kgaolo")
|
| 245 |
+
_add("sn", "part", "chikamu")
|
| 246 |
+
_add("ny", "article", "ndime")
|
| 247 |
+
_add("ku", "part", "beş")
|
| 248 |
+
_add("ky", "chapter", "бөлүм")
|
| 249 |
+
_add("tg", "chapter", "боби")
|
| 250 |
+
_add("yo", "article", "abala")
|
| 251 |
+
_add("yo", "chapter", "ori")
|
| 252 |
+
_add("ig", "article", "nkeji")
|
| 253 |
+
_add("lg", "part", "ekitundu")
|
| 254 |
+
_add("om", "chapter", "kutaa")
|
| 255 |
+
_add("ln", "part", "eténi", "eteni")
|
| 256 |
+
_add("ti", "article", "ዓንቀጽ")
|
| 257 |
+
_add("bm", "article", "sariya")
|
| 258 |
+
_add("wo", "article", "tere")
|
| 259 |
+
_add("ak", "article", "ahyɛde", "ahyede")
|
| 260 |
+
_add("ee", "part", "akpa")
|
| 261 |
+
_add("ff", "part", "faanda")
|
| 262 |
+
_add("br", "article", "pennad")
|
| 263 |
+
_add("kri", "section", "sekshon")
|
| 264 |
+
_add("bo", "article", "དོན་ཚན")
|
| 265 |
+
_add("ug", "article", "ماددا")
|
| 266 |
+
_add("kw", "article", "erthygel")
|
| 267 |
+
_add("tw", "article", "hyɛdeɛ", "hyedee")
|
| 268 |
+
_add("tet", "article", "artigu")
|
| 269 |
+
_add("haw", "article", "paukū", "pauku")
|
| 270 |
+
_add("ty", "article", "irava")
|
| 271 |
+
_add("ch", "part", "påtte", "patte")
|
| 272 |
+
_add("es", "section", "numeral")
|
| 273 |
+
_add("it", "section", "capoverso")
|
| 274 |
+
_add("de", "section", "nummer")
|
| 275 |
+
_add("so", "part", "qaybta")
|
| 276 |
+
_add("vi", "part", "phần")
|
| 277 |
+
_add("sk", "chapter", "oddiel")
|
| 278 |
+
_add("el", "title", "τίτλος")
|
| 279 |
+
_add("bg", "title", "дял")
|
| 280 |
+
_add("uz", "chapter", "bob")
|
| 281 |
+
_add("kk", "chapter", "тарау")
|
| 282 |
+
_add("hi", "chapter", "अध्याय")
|
| 283 |
+
_add("bn", "chapter", "অধ্যায়")
|
| 284 |
+
_add("ur", "chapter", "باب")
|
| 285 |
+
_add("fa", "chapter", "فصل")
|
| 286 |
+
_add("ne", "chapter", "परिच्छेद")
|
| 287 |
+
_add("zh", "section", "节")
|
| 288 |
+
_add("ja", "section", "節")
|
| 289 |
+
_add("ko", "section", "절")
|
| 290 |
+
_add("th", "section", "ตอน")
|
| 291 |
+
_add("sr", "part", "одељак")
|
| 292 |
+
_add("be", "title", "раздзел")
|
| 293 |
+
|
| 294 |
+
# Shared abbreviation; language left unknown.
|
| 295 |
+
_add("und", "article", "art.", "član")
|
| 296 |
+
_add("und", "section", "§")
|
| 297 |
+
|
| 298 |
+
# Scripts we do not Latin-split:
|
| 299 |
+
NO_LATIN_SPLIT_LANGS = frozenset(
|
| 300 |
+
{
|
| 301 |
+
"ar", "zh", "zh-cn", "zh-tw", "ja", "ko", "fa", "he", "th", "hi", "bn",
|
| 302 |
+
"am", "ru", "uk", "be", "ka", "hy", "km", "lo", "my", "si",
|
| 303 |
+
}
|
| 304 |
+
)
|
| 305 |
+
|
| 306 |
+
_TOKEN_RE = re.compile(r"[^\W\d_]+|art\.|sec\.|чл\.|§", re.UNICODE)
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def classify_heading_token(token: str) -> list[tuple[str, str]]:
|
| 310 |
+
return list(HEADING_LEXICON.get(token.casefold()) or ())
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def score_heading_languages(text: str) -> Counter[str]:
|
| 314 |
+
"""Count distinctive lexicon hits. Shared words like 'article' do not vote."""
|
| 315 |
+
counts: Counter[str] = Counter()
|
| 316 |
+
if not text:
|
| 317 |
+
return counts
|
| 318 |
+
for token in _TOKEN_RE.findall(text):
|
| 319 |
+
hits = classify_heading_token(token)
|
| 320 |
+
langs = {lang for _kind, lang in hits if lang != "und"}
|
| 321 |
+
if len(langs) == 1:
|
| 322 |
+
counts[next(iter(langs))] += 1
|
| 323 |
+
return counts
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
def majority_language(counts: Counter[str], *, exclude: tuple[str, ...] = ("und",)) -> str | None:
|
| 327 |
+
filtered = Counter({k: v for k, v in counts.items() if k not in exclude})
|
| 328 |
+
if not filtered:
|
| 329 |
+
return None
|
| 330 |
+
lang, _n = filtered.most_common(1)[0]
|
| 331 |
+
return lang
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def iso_lang(value: Any) -> str:
|
| 335 |
+
text = str(value or "").strip().lower().replace("_", "-")
|
| 336 |
+
if not text:
|
| 337 |
+
return ""
|
| 338 |
+
return text.split("-")[0]
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def latin_split_allowed(language: str) -> bool:
|
| 342 |
+
return iso_lang(language) not in NO_LATIN_SPLIT_LANGS
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/query.py
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Thin-client query for country-laws IR releases (local dir)."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
K1 = 1.2
|
| 15 |
+
B = 0.75
|
| 16 |
+
TITLE_WEIGHT = 5.0
|
| 17 |
+
BODY_WEIGHT = 1.0
|
| 18 |
+
MAX_QUERY_TERMS = 64
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def tokenize(text: str) -> list[str]:
|
| 22 |
+
import re
|
| 23 |
+
import unicodedata
|
| 24 |
+
|
| 25 |
+
if not text:
|
| 26 |
+
return []
|
| 27 |
+
nfkd = unicodedata.normalize("NFKD", text)
|
| 28 |
+
folded = "".join(ch for ch in nfkd if not unicodedata.combining(ch)).lower()
|
| 29 |
+
return re.findall(r"[0-9A-Za-z]+", folded)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class Release:
|
| 33 |
+
def __init__(self, root: Path):
|
| 34 |
+
self.root = Path(root)
|
| 35 |
+
self.manifest = json.loads((self.root / "manifest.json").read_text(encoding="utf-8"))
|
| 36 |
+
|
| 37 |
+
def _read(self, rel: str) -> pd.DataFrame:
|
| 38 |
+
path = self.root / rel
|
| 39 |
+
if path.is_dir():
|
| 40 |
+
files = sorted(path.glob("*.parquet"))
|
| 41 |
+
return pd.concat([pd.read_parquet(f) for f in files], ignore_index=True) if files else pd.DataFrame()
|
| 42 |
+
return pd.read_parquet(path)
|
| 43 |
+
|
| 44 |
+
def bm25(self, query: str, top_k: int = 10) -> list[dict]:
|
| 45 |
+
try:
|
| 46 |
+
from .duckdb_store import bm25_search
|
| 47 |
+
|
| 48 |
+
return bm25_search(self.root, query, top_k=top_k)
|
| 49 |
+
except Exception:
|
| 50 |
+
pass
|
| 51 |
+
q_terms = tokenize(query)[:MAX_QUERY_TERMS]
|
| 52 |
+
if not q_terms:
|
| 53 |
+
return []
|
| 54 |
+
shards = pd.read_parquet(self.root / "indexes" / "bm25_keyword_shards.parquet")
|
| 55 |
+
needed = set()
|
| 56 |
+
for term in q_terms:
|
| 57 |
+
hit = shards[(shards["first_key"] <= term) & (shards["last_key"] >= term)]
|
| 58 |
+
if hit.empty:
|
| 59 |
+
hit = shards
|
| 60 |
+
for rel in hit["relative_path"].tolist():
|
| 61 |
+
needed.add(rel)
|
| 62 |
+
postings = pd.concat(
|
| 63 |
+
[pd.read_parquet(self.root / rel) for rel in sorted(needed)],
|
| 64 |
+
ignore_index=True,
|
| 65 |
+
)
|
| 66 |
+
postings = postings[postings["term"].isin(q_terms)]
|
| 67 |
+
docs = self._read("data/bm25/documents")
|
| 68 |
+
avgdl = float(self.manifest["bm25"]["average_document_length"]) or 1.0
|
| 69 |
+
scores: dict[int, float] = defaultdict(float)
|
| 70 |
+
for rec in postings.itertuples(index=False):
|
| 71 |
+
idf = float(rec.idf)
|
| 72 |
+
for di, ttf, btf, dl in zip(
|
| 73 |
+
rec.document_indices, rec.title_frequencies, rec.body_frequencies, rec.document_lengths
|
| 74 |
+
):
|
| 75 |
+
tf = TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf)
|
| 76 |
+
denom = tf + K1 * (1.0 - B + B * (int(dl) / avgdl))
|
| 77 |
+
if denom:
|
| 78 |
+
scores[int(di)] += idf * (tf * (K1 + 1.0)) / denom
|
| 79 |
+
ranked = sorted(scores.items(), key=lambda kv: kv[1], reverse=True)[:top_k]
|
| 80 |
+
by_idx = docs.set_index("document_index")
|
| 81 |
+
out = []
|
| 82 |
+
for di, score in ranked:
|
| 83 |
+
row = by_idx.loc[di]
|
| 84 |
+
out.append(
|
| 85 |
+
{
|
| 86 |
+
"document_index": int(di),
|
| 87 |
+
"entry_cid": row["entry_cid"],
|
| 88 |
+
"title": row["title"],
|
| 89 |
+
"record_type": row["record_type"],
|
| 90 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 91 |
+
"law_cid": row.get("law_cid", ""),
|
| 92 |
+
"score": float(score),
|
| 93 |
+
}
|
| 94 |
+
)
|
| 95 |
+
return out
|
| 96 |
+
|
| 97 |
+
def vector(self, query: str, top_k: int = 10, candidate_centroids: int = 4, device: str = "cpu") -> list[dict]:
|
| 98 |
+
status = (self.manifest.get("vector") or {}).get("status")
|
| 99 |
+
if status == "stub":
|
| 100 |
+
return [{"error": "vectors are stubbed", "reason": self.manifest["vector"].get("stub_reason")}]
|
| 101 |
+
from sentence_transformers import SentenceTransformer
|
| 102 |
+
|
| 103 |
+
model = SentenceTransformer(self.manifest["vector"]["model_name"], device=device)
|
| 104 |
+
q = model.encode([query], normalize_embeddings=True, convert_to_numpy=True)[0].astype(np.float32)
|
| 105 |
+
meta = pd.read_parquet(self.root / "indexes" / "vector_chunks.parquet")
|
| 106 |
+
cents = np.stack(meta["centroid"].map(lambda c: np.asarray(c, dtype=np.float32)).to_numpy())
|
| 107 |
+
sims = cents @ q
|
| 108 |
+
order = np.argsort(-sims)[: max(1, candidate_centroids)]
|
| 109 |
+
shards = meta.iloc[order]
|
| 110 |
+
frames = [pd.read_parquet(self.root / rel) for rel in shards["relative_path"].tolist()]
|
| 111 |
+
vecs = pd.concat(frames, ignore_index=True)
|
| 112 |
+
if "embedding" not in vecs.columns or vecs["embedding"].isna().all():
|
| 113 |
+
return [{"error": "vector shard missing embeddings"}]
|
| 114 |
+
emb = np.stack(vecs["embedding"].map(lambda e: np.asarray(e, dtype=np.float32)).to_numpy())
|
| 115 |
+
scores = emb @ q
|
| 116 |
+
top = np.argsort(-scores)[:top_k]
|
| 117 |
+
out = []
|
| 118 |
+
for i in top:
|
| 119 |
+
row = vecs.iloc[int(i)]
|
| 120 |
+
out.append(
|
| 121 |
+
{
|
| 122 |
+
"document_index": int(row["document_index"]),
|
| 123 |
+
"entry_cid": row["entry_cid"],
|
| 124 |
+
"title": row["title"],
|
| 125 |
+
"record_type": row["record_type"],
|
| 126 |
+
"instrument_id": row.get("instrument_id", row.get("law_id", "")),
|
| 127 |
+
"score": float(scores[int(i)]),
|
| 128 |
+
}
|
| 129 |
+
)
|
| 130 |
+
return out
|
| 131 |
+
|
| 132 |
+
def neighbors(self, node_cid: str, direction: str = "both", limit: int = 25) -> list[dict]:
|
| 133 |
+
try:
|
| 134 |
+
from .duckdb_store import graph_neighbors
|
| 135 |
+
|
| 136 |
+
return graph_neighbors(self.root, node_cid, direction=direction, limit=limit)
|
| 137 |
+
except Exception:
|
| 138 |
+
pass
|
| 139 |
+
dirs = ["incoming", "outgoing"] if direction == "both" else [direction]
|
| 140 |
+
hits = []
|
| 141 |
+
for d in dirs:
|
| 142 |
+
path = self.root / "data" / "graph" / "adjacency" / d
|
| 143 |
+
files = sorted(path.glob("*.parquet"))
|
| 144 |
+
for f in files:
|
| 145 |
+
df = pd.read_parquet(f)
|
| 146 |
+
sub = df[df["node_cid"] == node_cid]
|
| 147 |
+
for rec in sub.itertuples(index=False):
|
| 148 |
+
for i, neigh in enumerate(rec.neighbor_cids):
|
| 149 |
+
hits.append(
|
| 150 |
+
{
|
| 151 |
+
"direction": d,
|
| 152 |
+
"node_cid": node_cid,
|
| 153 |
+
"neighbor_cid": neigh,
|
| 154 |
+
"edge_type": rec.edge_types[i] if i < len(rec.edge_types) else "",
|
| 155 |
+
"score": rec.scores[i] if rec.scores is not None and i < len(rec.scores) else None,
|
| 156 |
+
}
|
| 157 |
+
)
|
| 158 |
+
hits.sort(key=lambda r: (-(r["score"] or 0), r["neighbor_cid"]))
|
| 159 |
+
return hits[:limit]
|
| 160 |
+
|
| 161 |
+
def cite(self, citation: str, cite_format: str = "any", limit: int = 25) -> list[dict]:
|
| 162 |
+
from .duckdb_store import cite_search
|
| 163 |
+
|
| 164 |
+
return cite_search(self.root, citation, cite_format=cite_format, limit=limit)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def _print(rows: list[dict]) -> None:
|
| 168 |
+
print(json.dumps(rows, indent=2, ensure_ascii=False))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def main(argv: list[str] | None = None) -> int:
|
| 172 |
+
ap = argparse.ArgumentParser(description="Query a country-laws IR release")
|
| 173 |
+
ap.add_argument("--local-dir", required=True, help="Path to local release root")
|
| 174 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 175 |
+
|
| 176 |
+
p_bm = sub.add_parser("bm25")
|
| 177 |
+
p_bm.add_argument("query")
|
| 178 |
+
p_bm.add_argument("--top-k", type=int, default=10)
|
| 179 |
+
|
| 180 |
+
p_vec = sub.add_parser("vector")
|
| 181 |
+
p_vec.add_argument("query")
|
| 182 |
+
p_vec.add_argument("--top-k", type=int, default=10)
|
| 183 |
+
p_vec.add_argument("--candidate-centroids", type=int, default=4)
|
| 184 |
+
p_vec.add_argument("--device", default="cuda")
|
| 185 |
+
|
| 186 |
+
p_g = sub.add_parser("graph")
|
| 187 |
+
g_sub = p_g.add_subparsers(dest="graph_cmd", required=True)
|
| 188 |
+
p_n = g_sub.add_parser("neighbors")
|
| 189 |
+
p_n.add_argument("node_cid")
|
| 190 |
+
p_n.add_argument(
|
| 191 |
+
"--direction",
|
| 192 |
+
default="both",
|
| 193 |
+
choices=["both", "in", "out", "incoming", "outgoing"],
|
| 194 |
+
)
|
| 195 |
+
p_n.add_argument("--limit", type=int, default=25)
|
| 196 |
+
|
| 197 |
+
p_cite = sub.add_parser("cite")
|
| 198 |
+
p_cite.add_argument("citation")
|
| 199 |
+
p_cite.add_argument(
|
| 200 |
+
"--format",
|
| 201 |
+
dest="cite_format",
|
| 202 |
+
default="any",
|
| 203 |
+
choices=["any", "bluebook", "official"],
|
| 204 |
+
)
|
| 205 |
+
p_cite.add_argument("--limit", type=int, default=25)
|
| 206 |
+
|
| 207 |
+
args = ap.parse_args(argv)
|
| 208 |
+
rel = Release(Path(args.local_dir))
|
| 209 |
+
if args.cmd == "bm25":
|
| 210 |
+
_print(rel.bm25(args.query, top_k=args.top_k))
|
| 211 |
+
elif args.cmd == "vector":
|
| 212 |
+
_print(rel.vector(args.query, top_k=args.top_k, candidate_centroids=args.candidate_centroids, device=args.device))
|
| 213 |
+
elif args.cmd == "graph" and args.graph_cmd == "neighbors":
|
| 214 |
+
_print(rel.neighbors(args.node_cid, direction=args.direction, limit=args.limit))
|
| 215 |
+
elif args.cmd == "cite":
|
| 216 |
+
_print(rel.cite(args.citation, cite_format=args.cite_format, limit=args.limit))
|
| 217 |
+
return 0
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
if __name__ == "__main__":
|
| 221 |
+
raise SystemExit(main())
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/raw_package.py
ADDED
|
@@ -0,0 +1,324 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Incrementally package raw collector instruments into laws/articles parquet.
|
| 2 |
+
|
| 3 |
+
Collectors write one JSON instrument per official page under
|
| 4 |
+
``$LEGAL_CORPORA_ROOT/<iso>/instruments/*.json``. Those files grow as new
|
| 5 |
+
pages are scraped. This module merges them into the ``endomorphosis/ipfs_*_laws``
|
| 6 |
+
parquet schema without rewriting unchanged rows, so the GraphRAG builder can
|
| 7 |
+
delta-rebuild from the resulting pack.
|
| 8 |
+
|
| 9 |
+
Never invents legal text or identifiers. Empty/short bodies are dropped, not
|
| 10 |
+
filled.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
from typing import Any
|
| 20 |
+
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
from .cidutil import sha256_file
|
| 24 |
+
from .schema import LAW_FIELD_MAP, REQUIRED_ARTICLE_COLUMNS, REQUIRED_LAW_COLUMNS
|
| 25 |
+
|
| 26 |
+
LAW_COLS = [
|
| 27 |
+
"id",
|
| 28 |
+
"title",
|
| 29 |
+
"text",
|
| 30 |
+
"source_url",
|
| 31 |
+
"source_type",
|
| 32 |
+
"jurisdiction",
|
| 33 |
+
"country",
|
| 34 |
+
"language",
|
| 35 |
+
"eli",
|
| 36 |
+
"date",
|
| 37 |
+
"date_issued",
|
| 38 |
+
"retrieved_at",
|
| 39 |
+
"license",
|
| 40 |
+
"law_status",
|
| 41 |
+
"identifier",
|
| 42 |
+
"official_identifier",
|
| 43 |
+
"article_count",
|
| 44 |
+
"json_path",
|
| 45 |
+
"metadata_json",
|
| 46 |
+
]
|
| 47 |
+
ART_COLS = [
|
| 48 |
+
"law_id",
|
| 49 |
+
"id",
|
| 50 |
+
"title",
|
| 51 |
+
"text",
|
| 52 |
+
"source_url",
|
| 53 |
+
"document_number",
|
| 54 |
+
"article_number",
|
| 55 |
+
"record_type",
|
| 56 |
+
"metadata_json",
|
| 57 |
+
]
|
| 58 |
+
|
| 59 |
+
MIN_BODY_CHARS = 80
|
| 60 |
+
DEFAULT_CORPORA_ROOT = Path(
|
| 61 |
+
os.environ.get(
|
| 62 |
+
"LEGAL_CORPORA_ROOT",
|
| 63 |
+
str(Path.home() / ".ipfs_datasets" / "legal-corpora"),
|
| 64 |
+
)
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _s(value: Any) -> str:
|
| 69 |
+
if value is None:
|
| 70 |
+
return ""
|
| 71 |
+
return str(value).strip()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _meta_json(value: Any) -> str:
|
| 75 |
+
if isinstance(value, str):
|
| 76 |
+
return value
|
| 77 |
+
try:
|
| 78 |
+
return json.dumps(value or {}, ensure_ascii=False)
|
| 79 |
+
except Exception:
|
| 80 |
+
return "{}"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def instruments_to_frames(
|
| 84 |
+
instruments_dir: Path,
|
| 85 |
+
*,
|
| 86 |
+
min_body_chars: int = MIN_BODY_CHARS,
|
| 87 |
+
) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
| 88 |
+
"""Read collector JSON instruments into laws/articles dataframes."""
|
| 89 |
+
laws: list[dict[str, Any]] = []
|
| 90 |
+
arts: list[dict[str, Any]] = []
|
| 91 |
+
skipped_short = 0
|
| 92 |
+
skipped_bad = 0
|
| 93 |
+
root = Path(instruments_dir)
|
| 94 |
+
files = sorted(root.glob("*.json")) if root.is_dir() else []
|
| 95 |
+
for path in files:
|
| 96 |
+
try:
|
| 97 |
+
rec = json.loads(path.read_text(encoding="utf-8"))
|
| 98 |
+
except Exception:
|
| 99 |
+
skipped_bad += 1
|
| 100 |
+
continue
|
| 101 |
+
if not isinstance(rec, dict):
|
| 102 |
+
skipped_bad += 1
|
| 103 |
+
continue
|
| 104 |
+
text = _s(rec.get("text"))
|
| 105 |
+
ident = _s(rec.get("id"))
|
| 106 |
+
title = _s(rec.get("title"))
|
| 107 |
+
if not ident or not title or len(text) < min_body_chars:
|
| 108 |
+
skipped_short += 1
|
| 109 |
+
continue
|
| 110 |
+
meta = rec.get("metadata") or {}
|
| 111 |
+
laws.append(
|
| 112 |
+
{
|
| 113 |
+
"id": ident,
|
| 114 |
+
"title": title,
|
| 115 |
+
"text": text,
|
| 116 |
+
"source_url": _s(rec.get("source_url")),
|
| 117 |
+
"source_type": _s(rec.get("source_type")),
|
| 118 |
+
"jurisdiction": _s(rec.get("jurisdiction")),
|
| 119 |
+
"country": _s(rec.get("country")),
|
| 120 |
+
"language": _s(rec.get("language")),
|
| 121 |
+
"eli": _s(rec.get("eli")) or None,
|
| 122 |
+
"date": _s(rec.get("date")) or None,
|
| 123 |
+
"date_issued": _s(rec.get("date_issued") or rec.get("date")) or None,
|
| 124 |
+
"retrieved_at": _s(rec.get("retrieved_at")) or None,
|
| 125 |
+
"license": _s(rec.get("license")),
|
| 126 |
+
"law_status": _s(rec.get("law_status")),
|
| 127 |
+
"identifier": _s(rec.get("identifier")) or ident,
|
| 128 |
+
"official_identifier": _s(rec.get("official_identifier")),
|
| 129 |
+
"article_count": rec.get("article_count") or len(rec.get("documents") or []),
|
| 130 |
+
"json_path": f"instruments/{path.name}",
|
| 131 |
+
"metadata_json": _meta_json(meta),
|
| 132 |
+
}
|
| 133 |
+
)
|
| 134 |
+
for doc in rec.get("documents") or []:
|
| 135 |
+
if not isinstance(doc, dict):
|
| 136 |
+
continue
|
| 137 |
+
art_id = _s(doc.get("id"))
|
| 138 |
+
art_title = _s(doc.get("title"))
|
| 139 |
+
art_text = _s(doc.get("text"))
|
| 140 |
+
if not art_id or not art_title or not art_text:
|
| 141 |
+
continue
|
| 142 |
+
arts.append(
|
| 143 |
+
{
|
| 144 |
+
"law_id": ident,
|
| 145 |
+
"id": art_id,
|
| 146 |
+
"title": art_title,
|
| 147 |
+
"text": art_text,
|
| 148 |
+
"source_url": _s(doc.get("source_url")) or _s(rec.get("source_url")),
|
| 149 |
+
"document_number": _s(doc.get("document_number")),
|
| 150 |
+
"article_number": _s(doc.get("article_number")),
|
| 151 |
+
"record_type": _s(doc.get("record_type")) or "article",
|
| 152 |
+
"metadata_json": _meta_json(doc.get("metadata") or {}),
|
| 153 |
+
}
|
| 154 |
+
)
|
| 155 |
+
report = {
|
| 156 |
+
"n_instrument_files": len(files),
|
| 157 |
+
"n_laws": len(laws),
|
| 158 |
+
"n_articles": len(arts),
|
| 159 |
+
"skipped_short_or_empty": skipped_short,
|
| 160 |
+
"skipped_unreadable": skipped_bad,
|
| 161 |
+
"min_body_chars": min_body_chars,
|
| 162 |
+
"never_invented_legal_text": True,
|
| 163 |
+
"required_law_columns": list(REQUIRED_LAW_COLUMNS),
|
| 164 |
+
"required_article_columns": list(REQUIRED_ARTICLE_COLUMNS),
|
| 165 |
+
"law_field_map": dict(LAW_FIELD_MAP),
|
| 166 |
+
}
|
| 167 |
+
return (
|
| 168 |
+
pd.DataFrame(laws, columns=LAW_COLS),
|
| 169 |
+
pd.DataFrame(arts, columns=ART_COLS),
|
| 170 |
+
report,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def _retrieved_key(value: Any) -> str:
|
| 175 |
+
return _s(value)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def merge_laws(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame:
|
| 179 |
+
"""Upsert laws by ``id``. Newer ``retrieved_at`` wins; otherwise incoming wins."""
|
| 180 |
+
if prior is None or prior.empty:
|
| 181 |
+
return incoming.copy() if incoming is not None else pd.DataFrame(columns=LAW_COLS)
|
| 182 |
+
if incoming is None or incoming.empty:
|
| 183 |
+
return prior.copy()
|
| 184 |
+
by_id: dict[str, dict[str, Any]] = {}
|
| 185 |
+
for frame, incoming_flag in ((prior, False), (incoming, True)):
|
| 186 |
+
for rec in frame.to_dict(orient="records"):
|
| 187 |
+
ident = _s(rec.get("id"))
|
| 188 |
+
if not ident:
|
| 189 |
+
continue
|
| 190 |
+
existing = by_id.get(ident)
|
| 191 |
+
if existing is None:
|
| 192 |
+
by_id[ident] = rec
|
| 193 |
+
continue
|
| 194 |
+
if incoming_flag:
|
| 195 |
+
new_ts = _retrieved_key(rec.get("retrieved_at"))
|
| 196 |
+
old_ts = _retrieved_key(existing.get("retrieved_at"))
|
| 197 |
+
if not old_ts or new_ts >= old_ts:
|
| 198 |
+
by_id[ident] = rec
|
| 199 |
+
rows = [by_id[k] for k in sorted(by_id)]
|
| 200 |
+
return pd.DataFrame(rows, columns=LAW_COLS)
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def merge_articles(prior: pd.DataFrame | None, incoming: pd.DataFrame) -> pd.DataFrame:
|
| 204 |
+
"""Upsert articles by ``id``. Incoming replaces the same article id."""
|
| 205 |
+
if prior is None or prior.empty:
|
| 206 |
+
return incoming.copy() if incoming is not None else pd.DataFrame(columns=ART_COLS)
|
| 207 |
+
if incoming is None or incoming.empty:
|
| 208 |
+
return prior.copy()
|
| 209 |
+
by_id: dict[str, dict[str, Any]] = {}
|
| 210 |
+
for frame in (prior, incoming):
|
| 211 |
+
for rec in frame.to_dict(orient="records"):
|
| 212 |
+
ident = _s(rec.get("id"))
|
| 213 |
+
if not ident:
|
| 214 |
+
continue
|
| 215 |
+
by_id[ident] = rec
|
| 216 |
+
rows = [by_id[k] for k in sorted(by_id)]
|
| 217 |
+
return pd.DataFrame(rows, columns=ART_COLS)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def load_existing_parquet(pack_dir: Path) -> tuple[pd.DataFrame | None, pd.DataFrame | None]:
|
| 221 |
+
pack_dir = Path(pack_dir)
|
| 222 |
+
laws_path = None
|
| 223 |
+
arts_path = None
|
| 224 |
+
for cand in (pack_dir / "data" / "laws.parquet", pack_dir / "laws.parquet"):
|
| 225 |
+
if cand.is_file():
|
| 226 |
+
laws_path = cand
|
| 227 |
+
break
|
| 228 |
+
for cand in (pack_dir / "data" / "articles.parquet", pack_dir / "articles.parquet"):
|
| 229 |
+
if cand.is_file():
|
| 230 |
+
arts_path = cand
|
| 231 |
+
break
|
| 232 |
+
laws = pd.read_parquet(laws_path) if laws_path else None
|
| 233 |
+
arts = pd.read_parquet(arts_path) if arts_path else None
|
| 234 |
+
return laws, arts
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def write_pack(
|
| 238 |
+
out: Path,
|
| 239 |
+
laws: pd.DataFrame,
|
| 240 |
+
articles: pd.DataFrame,
|
| 241 |
+
*,
|
| 242 |
+
slug: str,
|
| 243 |
+
source_dataset: str,
|
| 244 |
+
name: str | None = None,
|
| 245 |
+
extra_meta: dict[str, Any] | None = None,
|
| 246 |
+
) -> dict[str, Any]:
|
| 247 |
+
"""Write a local pack that ``load_source`` / ``get_country`` can consume."""
|
| 248 |
+
out = Path(out)
|
| 249 |
+
data_dir = out / "data"
|
| 250 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 251 |
+
laws_path = data_dir / "laws.parquet"
|
| 252 |
+
arts_path = data_dir / "articles.parquet"
|
| 253 |
+
laws.to_parquet(laws_path, index=False)
|
| 254 |
+
articles.to_parquet(arts_path, index=False)
|
| 255 |
+
now = datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z")
|
| 256 |
+
meta = {
|
| 257 |
+
"slug": slug,
|
| 258 |
+
"repo": source_dataset,
|
| 259 |
+
"source_dataset": source_dataset,
|
| 260 |
+
"name": name or slug.replace("_", " ").title(),
|
| 261 |
+
"indexable": True,
|
| 262 |
+
"source_revision": f"local:{now}",
|
| 263 |
+
"n_laws": int(len(laws)),
|
| 264 |
+
"n_articles": int(len(articles)),
|
| 265 |
+
"laws_sha256": sha256_file(laws_path),
|
| 266 |
+
"articles_sha256": sha256_file(arts_path),
|
| 267 |
+
"generated_at": now,
|
| 268 |
+
"incremental": True,
|
| 269 |
+
}
|
| 270 |
+
if extra_meta:
|
| 271 |
+
meta.update(extra_meta)
|
| 272 |
+
(out / "pack_meta.json").write_text(
|
| 273 |
+
json.dumps(meta, indent=2, ensure_ascii=False) + "\n",
|
| 274 |
+
encoding="utf-8",
|
| 275 |
+
)
|
| 276 |
+
return meta
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def package_instruments(
|
| 280 |
+
*,
|
| 281 |
+
instruments_dir: Path,
|
| 282 |
+
out: Path,
|
| 283 |
+
slug: str,
|
| 284 |
+
source_dataset: str | None = None,
|
| 285 |
+
prior_pack: Path | None = None,
|
| 286 |
+
name: str | None = None,
|
| 287 |
+
min_body_chars: int = MIN_BODY_CHARS,
|
| 288 |
+
) -> dict[str, Any]:
|
| 289 |
+
"""Merge collector JSON (+ optional prior parquet) into a local IR source pack."""
|
| 290 |
+
incoming_laws, incoming_arts, extract_report = instruments_to_frames(
|
| 291 |
+
instruments_dir, min_body_chars=min_body_chars
|
| 292 |
+
)
|
| 293 |
+
prior_laws = prior_arts = None
|
| 294 |
+
prior_dir = Path(prior_pack) if prior_pack else (out if out.exists() else None)
|
| 295 |
+
if prior_dir is not None:
|
| 296 |
+
prior_laws, prior_arts = load_existing_parquet(prior_dir)
|
| 297 |
+
laws = merge_laws(prior_laws, incoming_laws)
|
| 298 |
+
articles = merge_articles(prior_arts, incoming_arts)
|
| 299 |
+
if laws.empty:
|
| 300 |
+
raise RuntimeError(
|
| 301 |
+
f"no laws with text>={min_body_chars} under {instruments_dir}"
|
| 302 |
+
)
|
| 303 |
+
repo = source_dataset or f"endomorphosis/ipfs_{slug}_laws"
|
| 304 |
+
meta = write_pack(
|
| 305 |
+
out,
|
| 306 |
+
laws,
|
| 307 |
+
articles,
|
| 308 |
+
slug=slug,
|
| 309 |
+
source_dataset=repo,
|
| 310 |
+
name=name,
|
| 311 |
+
extra_meta={"extract": extract_report},
|
| 312 |
+
)
|
| 313 |
+
meta["extract"] = extract_report
|
| 314 |
+
meta["n_laws_prior"] = int(len(prior_laws)) if prior_laws is not None else 0
|
| 315 |
+
meta["n_articles_prior"] = int(len(prior_arts)) if prior_arts is not None else 0
|
| 316 |
+
meta["n_laws_incoming"] = int(len(incoming_laws))
|
| 317 |
+
meta["n_articles_incoming"] = int(len(incoming_arts))
|
| 318 |
+
meta["out"] = str(out)
|
| 319 |
+
return meta
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def default_instruments_dir(iso_or_slug: str, root: Path | None = None) -> Path:
|
| 323 |
+
base = Path(root) if root is not None else DEFAULT_CORPORA_ROOT
|
| 324 |
+
return base / iso_or_slug / "instruments"
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/reconstruct.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reconstruct empty parent law bodies from article children.
|
| 2 |
+
|
| 3 |
+
Never invents legal text. Glue uses the same normalized strings as child
|
| 4 |
+
corpus fields. Eligible empty parents always get a law row (full glue,
|
| 5 |
+
streamed prefix, or title/number stub) — they are not dropped.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from dataclasses import dataclass, field
|
| 11 |
+
import os
|
| 12 |
+
import re
|
| 13 |
+
import unicodedata
|
| 14 |
+
from typing import Any, Iterable
|
| 15 |
+
|
| 16 |
+
from .structure import normalize_legal_text
|
| 17 |
+
|
| 18 |
+
RECONSTRUCT_MAX_PARENT_CHARS = 2_000_000
|
| 19 |
+
RECONSTRUCT_STUB_MAX_CHARS = 8_192
|
| 20 |
+
RECONSTRUCT_PROCESS_BUDGET_BYTES = 512 * 1024 * 1024
|
| 21 |
+
RSS_ABORT_SKIP_FULL_CONCAT = frozenset({"france", "eu", "denmark"})
|
| 22 |
+
PARENT_TRUNCATED_MAX_CHARS = 40
|
| 23 |
+
|
| 24 |
+
_DIGIT_FOLD = str.maketrans(
|
| 25 |
+
{
|
| 26 |
+
"٠": "0",
|
| 27 |
+
"١": "1",
|
| 28 |
+
"٢": "2",
|
| 29 |
+
"٣": "3",
|
| 30 |
+
"٤": "4",
|
| 31 |
+
"٥": "5",
|
| 32 |
+
"٦": "6",
|
| 33 |
+
"٧": "7",
|
| 34 |
+
"٨": "8",
|
| 35 |
+
"٩": "9",
|
| 36 |
+
"۰": "0",
|
| 37 |
+
"۱": "1",
|
| 38 |
+
"۲": "2",
|
| 39 |
+
"۳": "3",
|
| 40 |
+
"۴": "4",
|
| 41 |
+
"۵": "5",
|
| 42 |
+
"۶": "6",
|
| 43 |
+
"۷": "7",
|
| 44 |
+
"۸": "8",
|
| 45 |
+
"۹": "9",
|
| 46 |
+
"〇": "0",
|
| 47 |
+
"零": "0",
|
| 48 |
+
}
|
| 49 |
+
)
|
| 50 |
+
_NUM_RUN = re.compile(r"\d+|\D+")
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def fold_digits(value: str) -> str:
|
| 54 |
+
return unicodedata.normalize("NFKC", value or "").translate(_DIGIT_FOLD)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def article_sort_key(article_number: str, source_id: str) -> tuple:
|
| 58 |
+
folded = fold_digits(article_number or "")
|
| 59 |
+
nums: list[int] = []
|
| 60 |
+
rest: list[str] = []
|
| 61 |
+
for run in _NUM_RUN.findall(folded) if folded else []:
|
| 62 |
+
if run.isdigit():
|
| 63 |
+
nums.append(int(run))
|
| 64 |
+
else:
|
| 65 |
+
rest.append(run)
|
| 66 |
+
if not folded:
|
| 67 |
+
return (0, (), "", source_id or "")
|
| 68 |
+
if nums:
|
| 69 |
+
return (1, tuple(nums), "".join(rest), source_id or "")
|
| 70 |
+
return (2, (), folded, source_id or "")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def glue_piece(title: str, article_number: str, body: str) -> str:
|
| 74 |
+
"""One child's contribution to a reconstructed parent (normalized strings)."""
|
| 75 |
+
title = title or ""
|
| 76 |
+
article_number = article_number or ""
|
| 77 |
+
body = body or ""
|
| 78 |
+
chunk = title if title else article_number
|
| 79 |
+
if chunk and not body.lstrip().startswith(chunk):
|
| 80 |
+
return f"{chunk}\n{body}" if body else chunk
|
| 81 |
+
return body
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def glue_parent(pieces: Iterable[str]) -> str:
|
| 85 |
+
return "\n\n".join(p for p in pieces if p)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
@dataclass
|
| 89 |
+
class ReconstructResult:
|
| 90 |
+
body: str
|
| 91 |
+
reconstructed_from_articles: bool
|
| 92 |
+
reconstruction_truncated: bool
|
| 93 |
+
reconstruction_gap_note: str
|
| 94 |
+
reconstruction_article_count: int
|
| 95 |
+
reconstruction_article_ids: list[str] = field(default_factory=list)
|
| 96 |
+
reconstruction_article_sha256: list[str] = field(default_factory=list)
|
| 97 |
+
extra_bytes: int = 0
|
| 98 |
+
is_stub: bool = False
|
| 99 |
+
|
| 100 |
+
def extra_fields(self) -> dict[str, Any]:
|
| 101 |
+
return {
|
| 102 |
+
"reconstructed_from_articles": self.reconstructed_from_articles,
|
| 103 |
+
"reconstruction_truncated": self.reconstruction_truncated,
|
| 104 |
+
"reconstruction_gap_note": self.reconstruction_gap_note,
|
| 105 |
+
"reconstruction_article_count": self.reconstruction_article_count,
|
| 106 |
+
"reconstruction_article_ids": list(self.reconstruction_article_ids),
|
| 107 |
+
"reconstruction_article_sha256": list(self.reconstruction_article_sha256),
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def parent_needs_reconstruct(parent_body: str, n_articles: int) -> bool:
|
| 112 |
+
if n_articles < 1:
|
| 113 |
+
return False
|
| 114 |
+
body = parent_body or ""
|
| 115 |
+
return (not body) or len(body) < PARENT_TRUNCATED_MAX_CHARS
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def reconstruct_on() -> bool:
|
| 119 |
+
return os.environ.get("COUNTRY_LAWS_RECONSTRUCT", "1").strip() not in {"0", "false", "off"}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def force_full_concat() -> bool:
|
| 123 |
+
return os.environ.get("COUNTRY_LAWS_RECONSTRUCT_FULL", "").strip() in {"1", "true", "on"}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def process_budget_bytes() -> int:
|
| 127 |
+
raw = os.environ.get("RECONSTRUCT_PROCESS_BUDGET_BYTES")
|
| 128 |
+
if raw and raw.isdigit():
|
| 129 |
+
return int(raw)
|
| 130 |
+
return RECONSTRUCT_PROCESS_BUDGET_BYTES
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def reconstruct_parent(
|
| 134 |
+
*,
|
| 135 |
+
slug: str,
|
| 136 |
+
parent_body: str,
|
| 137 |
+
parent_title: str,
|
| 138 |
+
children: list[dict[str, str]],
|
| 139 |
+
running_extra_bytes: int,
|
| 140 |
+
sha256_hex,
|
| 141 |
+
) -> ReconstructResult:
|
| 142 |
+
"""Apply the five-way outcome table. ``children`` already normalized."""
|
| 143 |
+
# Empty bodies are dropped from the corpus. A title-only piece would make
|
| 144 |
+
# the parent disagree with the glue of the children that remain.
|
| 145 |
+
kept = [c for c in children if str(c.get("body") or "").strip()]
|
| 146 |
+
ordered = sorted(
|
| 147 |
+
kept,
|
| 148 |
+
key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""),
|
| 149 |
+
)
|
| 150 |
+
ids = [c.get("id") or "" for c in ordered]
|
| 151 |
+
shas = [sha256_hex((c.get("body") or "").encode("utf-8")) for c in ordered]
|
| 152 |
+
n = len(ordered)
|
| 153 |
+
if n < 1 or not parent_needs_reconstruct(parent_body, n):
|
| 154 |
+
return ReconstructResult(
|
| 155 |
+
body=parent_body,
|
| 156 |
+
reconstructed_from_articles=False,
|
| 157 |
+
reconstruction_truncated=False,
|
| 158 |
+
reconstruction_gap_note="",
|
| 159 |
+
reconstruction_article_count=0,
|
| 160 |
+
)
|
| 161 |
+
|
| 162 |
+
stub_note = ""
|
| 163 |
+
if slug in RSS_ABORT_SKIP_FULL_CONCAT and not force_full_concat():
|
| 164 |
+
stub_note = "rss_abort_slug"
|
| 165 |
+
elif running_extra_bytes >= process_budget_bytes():
|
| 166 |
+
stub_note = "reconstruct_budget"
|
| 167 |
+
|
| 168 |
+
if stub_note:
|
| 169 |
+
parts: list[str] = []
|
| 170 |
+
if parent_title:
|
| 171 |
+
parts.append(parent_title)
|
| 172 |
+
for child in ordered:
|
| 173 |
+
label = child.get("title") or child.get("article_number") or ""
|
| 174 |
+
if label:
|
| 175 |
+
parts.append(label)
|
| 176 |
+
stub = "\n".join(parts)[:RECONSTRUCT_STUB_MAX_CHARS]
|
| 177 |
+
return ReconstructResult(
|
| 178 |
+
body=stub,
|
| 179 |
+
reconstructed_from_articles=True,
|
| 180 |
+
reconstruction_truncated=False,
|
| 181 |
+
reconstruction_gap_note=stub_note,
|
| 182 |
+
reconstruction_article_count=n,
|
| 183 |
+
reconstruction_article_ids=ids,
|
| 184 |
+
reconstruction_article_sha256=shas,
|
| 185 |
+
extra_bytes=0,
|
| 186 |
+
is_stub=True,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
acc: list[str] = []
|
| 190 |
+
size = 0
|
| 191 |
+
truncated = False
|
| 192 |
+
for child in ordered:
|
| 193 |
+
piece = glue_piece(
|
| 194 |
+
child.get("title") or "",
|
| 195 |
+
child.get("article_number") or "",
|
| 196 |
+
child.get("body") or "",
|
| 197 |
+
)
|
| 198 |
+
if not piece:
|
| 199 |
+
continue
|
| 200 |
+
extra = (2 if acc else 0) + len(piece)
|
| 201 |
+
if size + extra > RECONSTRUCT_MAX_PARENT_CHARS:
|
| 202 |
+
room = RECONSTRUCT_MAX_PARENT_CHARS - size - (2 if acc else 0)
|
| 203 |
+
if room > 0:
|
| 204 |
+
acc.append(piece[:room])
|
| 205 |
+
size = RECONSTRUCT_MAX_PARENT_CHARS
|
| 206 |
+
truncated = True
|
| 207 |
+
break
|
| 208 |
+
acc.append(piece)
|
| 209 |
+
size += extra
|
| 210 |
+
body = glue_parent(acc)
|
| 211 |
+
return ReconstructResult(
|
| 212 |
+
body=body,
|
| 213 |
+
reconstructed_from_articles=True,
|
| 214 |
+
reconstruction_truncated=truncated,
|
| 215 |
+
reconstruction_gap_note="",
|
| 216 |
+
reconstruction_article_count=n,
|
| 217 |
+
reconstruction_article_ids=ids,
|
| 218 |
+
reconstruction_article_sha256=shas,
|
| 219 |
+
extra_bytes=len(body.encode("utf-8")),
|
| 220 |
+
is_stub=False,
|
| 221 |
+
)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def expected_glue_from_children(children: list[dict[str, str]]) -> str:
|
| 225 |
+
ordered = sorted(
|
| 226 |
+
children,
|
| 227 |
+
key=lambda c: article_sort_key(c.get("article_number") or "", c.get("id") or ""),
|
| 228 |
+
)
|
| 229 |
+
return glue_parent(
|
| 230 |
+
glue_piece(c.get("title") or "", c.get("article_number") or "", c.get("body") or "")
|
| 231 |
+
for c in ordered
|
| 232 |
+
)
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/resources.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Admit country-IR workers from live memory, disk, and GPU headroom.
|
| 2 |
+
|
| 3 |
+
The caller keeps at most ``Admission.workers`` builds in flight. Zero workers
|
| 4 |
+
means pause and sleep ``backoff_seconds`` instead of starting another country.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import shutil
|
| 10 |
+
import subprocess
|
| 11 |
+
from dataclasses import dataclass
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
@dataclass(frozen=True)
|
| 16 |
+
class GpuSnapshot:
|
| 17 |
+
index: int
|
| 18 |
+
memory_free_mib: int
|
| 19 |
+
memory_total_mib: int
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@dataclass(frozen=True)
|
| 23 |
+
class HostSnapshot:
|
| 24 |
+
"""One host reading for admission.
|
| 25 |
+
|
| 26 |
+
``mem_available_gib`` is raw Linux MemAvailable. ``schedulable_gib`` adds
|
| 27 |
+
ZFS ARC above arc_c_min. A negative schedulable value means the caller
|
| 28 |
+
did not measure the ARC, and admission then uses the raw figure. The
|
| 29 |
+
under-6 GiB pause keeps using the raw figure.
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
mem_available_gib: float
|
| 33 |
+
disk_free_gib: float
|
| 34 |
+
gpus: tuple[GpuSnapshot, ...]
|
| 35 |
+
schedulable_gib: float = -1.0
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclass(frozen=True)
|
| 39 |
+
class Admission:
|
| 40 |
+
workers: int
|
| 41 |
+
devices: tuple[str, ...]
|
| 42 |
+
backoff_s: float
|
| 43 |
+
reason: str
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def job_slots(corpus_rows: int) -> int:
|
| 47 |
+
"""How many admission slots one country consumes.
|
| 48 |
+
|
| 49 |
+
Unknown size costs one slot. A corpus of at least 150_000 rows costs two.
|
| 50 |
+
A million-row corpus costs four, so it can share a wide pool instead of
|
| 51 |
+
waiting until every other country has finished.
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
rows = int(corpus_rows or 0)
|
| 55 |
+
if rows >= 1_000_000:
|
| 56 |
+
return 4
|
| 57 |
+
if rows >= 150_000:
|
| 58 |
+
return 2
|
| 59 |
+
return 1
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def can_admit(used_slots: int, limit: int, cost: int) -> bool:
|
| 63 |
+
if limit <= 0 or cost <= 0:
|
| 64 |
+
return False
|
| 65 |
+
return used_slots + cost <= limit
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def backoff_seconds(base: float, pressure: int) -> float:
|
| 69 |
+
"""Double the pause on each refused admission, and cap it at two minutes."""
|
| 70 |
+
|
| 71 |
+
if base <= 0:
|
| 72 |
+
return 0.0
|
| 73 |
+
steps = min(max(int(pressure), 0), 4)
|
| 74 |
+
return min(120.0, float(base) * (2**steps))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def assign_device(devices: tuple[str, ...], inflight: tuple[str, ...]) -> str:
|
| 78 |
+
if not devices:
|
| 79 |
+
return "cpu"
|
| 80 |
+
counts = {device: inflight.count(device) for device in devices}
|
| 81 |
+
return min(devices, key=lambda device: (counts[device], devices.index(device)))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def admission_budget_gib(snap: HostSnapshot) -> float:
|
| 85 |
+
"""RAM the slot formula may use.
|
| 86 |
+
|
| 87 |
+
Probe sets ``schedulable_gib`` to MemAvailable plus evictable ZFS ARC.
|
| 88 |
+
Callers that only fill ``mem_available_gib`` leave the ARC unmeasured.
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
if snap.schedulable_gib >= 0:
|
| 92 |
+
return snap.schedulable_gib
|
| 93 |
+
return snap.mem_available_gib
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def admit_parallelism(
|
| 97 |
+
snap: HostSnapshot,
|
| 98 |
+
*,
|
| 99 |
+
ceiling: int,
|
| 100 |
+
per_worker_gib: float = 6.0,
|
| 101 |
+
reserve_gib: float = 8.0,
|
| 102 |
+
gpu_free_mib: int = 3072,
|
| 103 |
+
disk_pause_gib: float = 20.0,
|
| 104 |
+
disk_slow_gib: float = 40.0,
|
| 105 |
+
) -> Admission:
|
| 106 |
+
"""Return how many country builds may start, and which devices they may use.
|
| 107 |
+
|
| 108 |
+
The slot count uses schedulable RAM, so evictable ZFS ARC counts as room.
|
| 109 |
+
The pause under 6 GiB uses raw MemAvailable. ARC shrink is not instant,
|
| 110 |
+
and MemAbort keeps that same raw floor.
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
ceiling = max(0, int(ceiling))
|
| 114 |
+
budget = admission_budget_gib(snap)
|
| 115 |
+
if snap.disk_free_gib >= 0 and snap.disk_free_gib < disk_pause_gib:
|
| 116 |
+
return Admission(0, (), 15.0, "disk")
|
| 117 |
+
if snap.mem_available_gib >= 0 and snap.mem_available_gib < 6.0:
|
| 118 |
+
return Admission(0, (), 15.0, "memory")
|
| 119 |
+
|
| 120 |
+
if budget < 0:
|
| 121 |
+
ram_slots = 1
|
| 122 |
+
else:
|
| 123 |
+
ram_slots = int((budget - reserve_gib) // per_worker_gib)
|
| 124 |
+
if budget < 12.0:
|
| 125 |
+
ram_slots = min(ram_slots, 1)
|
| 126 |
+
ram_slots = max(0, ram_slots)
|
| 127 |
+
|
| 128 |
+
usable = tuple(
|
| 129 |
+
f"cuda:{gpu.index}"
|
| 130 |
+
for gpu in snap.gpus
|
| 131 |
+
if gpu.memory_free_mib >= gpu_free_mib
|
| 132 |
+
)
|
| 133 |
+
if snap.gpus and not usable:
|
| 134 |
+
return Admission(0, (), 10.0, "gpu")
|
| 135 |
+
if not snap.gpus:
|
| 136 |
+
devices: tuple[str, ...] = ("cpu",)
|
| 137 |
+
device_slots = 4
|
| 138 |
+
else:
|
| 139 |
+
devices = usable
|
| 140 |
+
# Encode stays one-at-a-time per GPU. The extra slots overlap
|
| 141 |
+
# download, normalize, and search-graph builds while RAM is free.
|
| 142 |
+
device_slots = len(usable) * 4
|
| 143 |
+
|
| 144 |
+
if snap.disk_free_gib >= 0 and snap.disk_free_gib < disk_slow_gib:
|
| 145 |
+
device_slots = min(device_slots, 1)
|
| 146 |
+
ram_slots = min(ram_slots, 1)
|
| 147 |
+
|
| 148 |
+
workers = min(ceiling, ram_slots, device_slots)
|
| 149 |
+
if workers <= 0:
|
| 150 |
+
return Admission(0, (), 15.0, "budget")
|
| 151 |
+
return Admission(workers, devices, 0.0, "ok")
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def probe_host(anchor: Path | None = None) -> HostSnapshot:
|
| 155 |
+
"""Read RAM, free space on ``anchor``, and ``nvidia-smi`` memory.
|
| 156 |
+
|
| 157 |
+
The snapshot keeps raw MemAvailable and a schedulable budget. The budget
|
| 158 |
+
adds ZFS ARC above arc_c_min. MemAbort does not read that budget.
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
from .mem import mem_available_gib, schedulable_gib
|
| 162 |
+
|
| 163 |
+
root = anchor or Path.home()
|
| 164 |
+
try:
|
| 165 |
+
disk = shutil.disk_usage(root).free / (1024**3)
|
| 166 |
+
except OSError:
|
| 167 |
+
disk = -1.0
|
| 168 |
+
available = mem_available_gib()
|
| 169 |
+
return HostSnapshot(
|
| 170 |
+
mem_available_gib=available,
|
| 171 |
+
disk_free_gib=disk,
|
| 172 |
+
gpus=tuple(_gpu_snapshots()),
|
| 173 |
+
schedulable_gib=schedulable_gib(available),
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _gpu_snapshots() -> list[GpuSnapshot]:
|
| 178 |
+
try:
|
| 179 |
+
raw = subprocess.check_output(
|
| 180 |
+
[
|
| 181 |
+
"nvidia-smi",
|
| 182 |
+
"--query-gpu=index,memory.free,memory.total",
|
| 183 |
+
"--format=csv,noheader,nounits",
|
| 184 |
+
],
|
| 185 |
+
text=True,
|
| 186 |
+
timeout=5,
|
| 187 |
+
stderr=subprocess.DEVNULL,
|
| 188 |
+
)
|
| 189 |
+
except (OSError, subprocess.SubprocessError, ValueError):
|
| 190 |
+
return []
|
| 191 |
+
found: list[GpuSnapshot] = []
|
| 192 |
+
for line in raw.splitlines():
|
| 193 |
+
parts = [part.strip() for part in line.split(",")]
|
| 194 |
+
if len(parts) != 3:
|
| 195 |
+
continue
|
| 196 |
+
try:
|
| 197 |
+
found.append(GpuSnapshot(int(parts[0]), int(parts[1]), int(parts[2])))
|
| 198 |
+
except ValueError:
|
| 199 |
+
continue
|
| 200 |
+
return found
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/schema.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail-closed schema mapping for endomorphosis/ipfs_*_laws parquet tables.
|
| 2 |
+
|
| 3 |
+
Verified 2026-09-03 against Malta (pilot) and Germany (column-drift check):
|
| 4 |
+
|
| 5 |
+
Laws columns (both countries):
|
| 6 |
+
id, title, text, source_url, source_type, jurisdiction, country, language,
|
| 7 |
+
eli, date, date_issued, retrieved_at, license, law_status, identifier,
|
| 8 |
+
official_identifier, article_count, json_path, metadata_json
|
| 9 |
+
|
| 10 |
+
Drift: Malta article_count is int64; Germany article_count is int32.
|
| 11 |
+
Germany eli is frequently null. Neither is a missing identifier.
|
| 12 |
+
|
| 13 |
+
Articles columns (both countries; Malta snapshot has 0 rows):
|
| 14 |
+
law_id, id, title, text, source_url, document_number, article_number,
|
| 15 |
+
record_type, metadata_json
|
| 16 |
+
|
| 17 |
+
Required identity columns are NOT invented. Missing required identifiers
|
| 18 |
+
fail the build.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
REQUIRED_LAW_COLUMNS = ("id", "title", "text")
|
| 24 |
+
REQUIRED_ARTICLE_COLUMNS = ("id", "law_id", "title", "text")
|
| 25 |
+
|
| 26 |
+
OPTIONAL_LAW_COLUMNS = (
|
| 27 |
+
"source_url",
|
| 28 |
+
"source_type",
|
| 29 |
+
"jurisdiction",
|
| 30 |
+
"country",
|
| 31 |
+
"language",
|
| 32 |
+
"eli",
|
| 33 |
+
"date",
|
| 34 |
+
"date_issued",
|
| 35 |
+
"retrieved_at",
|
| 36 |
+
"license",
|
| 37 |
+
"law_status",
|
| 38 |
+
"identifier",
|
| 39 |
+
"official_identifier",
|
| 40 |
+
"article_count",
|
| 41 |
+
"json_path",
|
| 42 |
+
"metadata_json",
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
OPTIONAL_ARTICLE_COLUMNS = (
|
| 46 |
+
"source_url",
|
| 47 |
+
"document_number",
|
| 48 |
+
"article_number",
|
| 49 |
+
"record_type",
|
| 50 |
+
"metadata_json",
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Canonical field mapping used in the CID-keyed corpus.
|
| 54 |
+
LAW_FIELD_MAP = {
|
| 55 |
+
"source_id": "id",
|
| 56 |
+
"title": "title",
|
| 57 |
+
"body": "text",
|
| 58 |
+
"source_url": "source_url",
|
| 59 |
+
"source_type": "source_type",
|
| 60 |
+
"jurisdiction": "jurisdiction",
|
| 61 |
+
"country": "country",
|
| 62 |
+
"language": "language",
|
| 63 |
+
"eli": "eli",
|
| 64 |
+
"date": "date",
|
| 65 |
+
"date_issued": "date_issued",
|
| 66 |
+
"retrieved_at": "retrieved_at",
|
| 67 |
+
"license_expression": "license",
|
| 68 |
+
"law_status": "law_status",
|
| 69 |
+
"identifier": "identifier",
|
| 70 |
+
"official_identifier": "official_identifier",
|
| 71 |
+
"article_count": "article_count",
|
| 72 |
+
"metadata_json": "metadata_json",
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
ARTICLE_FIELD_MAP = {
|
| 76 |
+
"source_id": "id",
|
| 77 |
+
"law_id": "law_id",
|
| 78 |
+
"title": "title",
|
| 79 |
+
"body": "text",
|
| 80 |
+
"source_url": "source_url",
|
| 81 |
+
"document_number": "document_number",
|
| 82 |
+
"article_number": "article_number",
|
| 83 |
+
"record_type_src": "record_type",
|
| 84 |
+
"metadata_json": "metadata_json",
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class SchemaError(ValueError):
|
| 89 |
+
pass
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def _cols(df) -> set[str]:
|
| 93 |
+
return set(map(str, df.columns))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def validate_laws(df) -> None:
|
| 97 |
+
missing = [c for c in REQUIRED_LAW_COLUMNS if c not in _cols(df)]
|
| 98 |
+
if missing:
|
| 99 |
+
raise SchemaError(
|
| 100 |
+
f"laws.parquet missing required identifier/content columns {missing}; "
|
| 101 |
+
f"present={sorted(_cols(df))}. Fail closed — will not invent ids."
|
| 102 |
+
)
|
| 103 |
+
null_ids = int(df["id"].isna().sum()) if "id" in df.columns else len(df)
|
| 104 |
+
empty_ids = int((df["id"].astype(str).str.strip() == "").sum()) if "id" in df.columns else 0
|
| 105 |
+
if null_ids or empty_ids:
|
| 106 |
+
raise SchemaError(
|
| 107 |
+
f"laws.parquet has {null_ids} null and {empty_ids} empty id values. Fail closed."
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def validate_articles(df) -> None:
|
| 112 |
+
if df is None or df.empty:
|
| 113 |
+
return
|
| 114 |
+
missing = [c for c in REQUIRED_ARTICLE_COLUMNS if c not in _cols(df)]
|
| 115 |
+
if missing:
|
| 116 |
+
raise SchemaError(
|
| 117 |
+
f"articles.parquet missing required identifier/content columns {missing}; "
|
| 118 |
+
f"present={sorted(_cols(df))}. Fail closed — will not invent ids."
|
| 119 |
+
)
|
| 120 |
+
null_ids = int(df["id"].isna().sum())
|
| 121 |
+
null_law = int(df["law_id"].isna().sum())
|
| 122 |
+
empty_ids = int((df["id"].astype(str).str.strip() == "").sum())
|
| 123 |
+
empty_law = int((df["law_id"].astype(str).str.strip() == "").sum())
|
| 124 |
+
if null_ids or empty_ids or null_law or empty_law:
|
| 125 |
+
raise SchemaError(
|
| 126 |
+
f"articles.parquet has null/empty identifiers "
|
| 127 |
+
f"(id null={null_ids} empty={empty_ids}; law_id null={null_law} empty={empty_law}). Fail closed."
|
| 128 |
+
)
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/sparse.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Country-law sparse GraphRAG export through the shared HF GraphRAG builders.
|
| 2 |
+
|
| 3 |
+
This is the same parquet layout used by US Code, state laws, Federal Register,
|
| 4 |
+
and SkillCenter:
|
| 5 |
+
|
| 6 |
+
* ``ipfs_datasets_py.retrieval.hf_graphrag.bm25.build_bm25_layout``
|
| 7 |
+
* ``ipfs_datasets_py.retrieval.hf_graphrag.graph.write_graph_layout``
|
| 8 |
+
|
| 9 |
+
No SQLite. Indexes are ZSTD parquet shards under ``data/bm25`` and
|
| 10 |
+
``data/graph``. DuckDB queries those shards at read time.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import pandas as pd
|
| 19 |
+
|
| 20 |
+
from . import EDGE_IDENTITY_SCHEMA, SCHEMA_VERSION
|
| 21 |
+
from .cidutil import cid_of_json
|
| 22 |
+
from .graph import build_graph
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def corpus_to_bm25_rows(corpus: pd.DataFrame) -> list[dict[str, Any]]:
|
| 26 |
+
"""Project a normalized country-law corpus onto the shared BM25 row schema.
|
| 27 |
+
|
| 28 |
+
Rows with no searchable tokens are omitted. The shared
|
| 29 |
+
``build_bm25_layout`` builder fail-closes on empty documents (same
|
| 30 |
+
admission rule as US Code / Federal Register).
|
| 31 |
+
"""
|
| 32 |
+
from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import tokenize_bm25_text
|
| 33 |
+
|
| 34 |
+
_MAX_TITLE = 4_096
|
| 35 |
+
_MAX_BODY = 200_000
|
| 36 |
+
_CTRL = dict.fromkeys(range(32))
|
| 37 |
+
rows: list[dict[str, Any]] = []
|
| 38 |
+
for rec in corpus.itertuples(index=False):
|
| 39 |
+
cid = str(getattr(rec, "entry_cid", "") or "")
|
| 40 |
+
record_type = str(getattr(rec, "record_type", "") or "law")
|
| 41 |
+
title = str(getattr(rec, "title", "") or "").replace("\x00", "")
|
| 42 |
+
body = str(getattr(rec, "body", "") or "").replace("\x00", "")
|
| 43 |
+
title = title.translate(_CTRL).strip()
|
| 44 |
+
body = body.strip()
|
| 45 |
+
if len(title) > _MAX_TITLE:
|
| 46 |
+
title = title[:_MAX_TITLE].rstrip()
|
| 47 |
+
if len(body) > _MAX_BODY:
|
| 48 |
+
body = body[:_MAX_BODY].rstrip()
|
| 49 |
+
if not title:
|
| 50 |
+
title = f"{record_type} {cid}"[:_MAX_TITLE].strip()
|
| 51 |
+
if not title and not body:
|
| 52 |
+
continue
|
| 53 |
+
if not tokenize_bm25_text(title) and not tokenize_bm25_text(body):
|
| 54 |
+
continue
|
| 55 |
+
rows.append(
|
| 56 |
+
{
|
| 57 |
+
"entry_cid": cid,
|
| 58 |
+
"title": title,
|
| 59 |
+
"body": body,
|
| 60 |
+
"record_type": record_type,
|
| 61 |
+
"document_index": int(rec.document_index),
|
| 62 |
+
}
|
| 63 |
+
)
|
| 64 |
+
if not rows:
|
| 65 |
+
raise RuntimeError("no corpus rows had searchable BM25 tokens")
|
| 66 |
+
for i, row in enumerate(rows):
|
| 67 |
+
row["document_index"] = i
|
| 68 |
+
return rows
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _graph_nodes_and_edges(corpus: pd.DataFrame) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
|
| 72 |
+
"""Structural graph only (no precomputed BM25 neighbor matrix)."""
|
| 73 |
+
built = build_graph(corpus, [[] for _ in range(len(corpus))])
|
| 74 |
+
nodes = [
|
| 75 |
+
{
|
| 76 |
+
"node_cid": str(row["node_cid"]),
|
| 77 |
+
"node_type": str(row["node_type"]),
|
| 78 |
+
"label": row.get("label"),
|
| 79 |
+
"entry_cid": row.get("entry_cid") or None,
|
| 80 |
+
}
|
| 81 |
+
for row in built["nodes"].to_dict("records")
|
| 82 |
+
]
|
| 83 |
+
edges = []
|
| 84 |
+
for row in built["edges"].to_dict("records"):
|
| 85 |
+
source = str(row.get("source_cid") or row.get("source_node_cid") or "")
|
| 86 |
+
target = str(row.get("target_cid") or row.get("target_node_cid") or "")
|
| 87 |
+
edge_type = str(row.get("edge_type") or "")
|
| 88 |
+
if not source or not target or not edge_type:
|
| 89 |
+
continue
|
| 90 |
+
edge_cid = str(row.get("edge_cid") or "") or cid_of_json(
|
| 91 |
+
{
|
| 92 |
+
"edge_type": edge_type,
|
| 93 |
+
"schema": EDGE_IDENTITY_SCHEMA,
|
| 94 |
+
"source": source,
|
| 95 |
+
"target": target,
|
| 96 |
+
}
|
| 97 |
+
)
|
| 98 |
+
edges.append(
|
| 99 |
+
{
|
| 100 |
+
"edge_cid": edge_cid,
|
| 101 |
+
"edge_type": edge_type,
|
| 102 |
+
"source_node_cid": source,
|
| 103 |
+
"target_node_cid": target,
|
| 104 |
+
"retrieval_method": str(row.get("retrieval_method") or "structural"),
|
| 105 |
+
"score": row.get("score"),
|
| 106 |
+
}
|
| 107 |
+
)
|
| 108 |
+
return nodes, edges
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def export_sparse_graphrag(
|
| 112 |
+
corpus: pd.DataFrame,
|
| 113 |
+
output_dir: Path,
|
| 114 |
+
) -> dict[str, Any]:
|
| 115 |
+
"""Write BM25 + graph parquet shards using the shared HF GraphRAG builders."""
|
| 116 |
+
from ipfs_datasets_py.retrieval.hf_graphrag.bm25 import (
|
| 117 |
+
BM25LayoutConfig,
|
| 118 |
+
build_bm25_layout,
|
| 119 |
+
)
|
| 120 |
+
from ipfs_datasets_py.retrieval.hf_graphrag.graph import write_graph_layout
|
| 121 |
+
|
| 122 |
+
output_dir = Path(output_dir)
|
| 123 |
+
output_dir.mkdir(parents=True, exist_ok=True)
|
| 124 |
+
rows = corpus_to_bm25_rows(corpus)
|
| 125 |
+
bm25 = build_bm25_layout(
|
| 126 |
+
rows,
|
| 127 |
+
output_dir,
|
| 128 |
+
config=BM25LayoutConfig(max_documents=max(len(rows), 1)),
|
| 129 |
+
)
|
| 130 |
+
nodes, edges = _graph_nodes_and_edges(corpus)
|
| 131 |
+
written = write_graph_layout(nodes, edges, output_dir)
|
| 132 |
+
layout = written.layout
|
| 133 |
+
return {
|
| 134 |
+
"engine": "hf_graphrag",
|
| 135 |
+
"schema_version": SCHEMA_VERSION,
|
| 136 |
+
"bm25": bm25.to_manifest_fragment(),
|
| 137 |
+
"graph": {
|
| 138 |
+
"node_count": int(layout.node_count),
|
| 139 |
+
"edge_count": int(layout.edge_count),
|
| 140 |
+
"adjacency": "data/graph/adjacency/{out,in}/*.parquet",
|
| 141 |
+
},
|
| 142 |
+
"sqlite": False,
|
| 143 |
+
"query_engine": "duckdb",
|
| 144 |
+
}
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/spill.py
ADDED
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Disk-spill helpers for large country IR builds (DuckDB + parquet).
|
| 2 |
+
|
| 3 |
+
Design (CoS / DO OOM lesson):
|
| 4 |
+
- Embeddings: checkpointed .npy via vectors.encode_corpus (unchanged).
|
| 5 |
+
- Neighbors for n >= DUCKDB_THRESHOLD (40k): DuckDB FTS over corpus parquet,
|
| 6 |
+
streamed into neighbor_*.parquet shards — never hold the full neighbor
|
| 7 |
+
matrix in RAM.
|
| 8 |
+
- BM25 TF: stream tokenize → DuckDB → posting parquet parts.
|
| 9 |
+
- Package: sequential parquet write so corpus, bm25, graph, vectors are never
|
| 10 |
+
all resident together.
|
| 11 |
+
|
| 12 |
+
No SQLite. Intermediate and published artifacts are parquet / DuckDB.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import json
|
| 18 |
+
import math
|
| 19 |
+
import pickle
|
| 20 |
+
from collections import defaultdict
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
from typing import Any, Callable, Iterable, Iterator
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import pandas as pd
|
| 26 |
+
import pyarrow.parquet as pq
|
| 27 |
+
|
| 28 |
+
from . import SCHEMA_VERSION
|
| 29 |
+
from .bm25 import (
|
| 30 |
+
B,
|
| 31 |
+
BODY_WEIGHT,
|
| 32 |
+
K1,
|
| 33 |
+
POSTING_ROWS_PER_RECORD,
|
| 34 |
+
TERMS_PER_SHARD,
|
| 35 |
+
TITLE_WEIGHT,
|
| 36 |
+
)
|
| 37 |
+
from .graph import _adjacency, _edge, build_graph
|
| 38 |
+
from .mem import MemAbort, checkpoint, log_mem
|
| 39 |
+
from .tokenize import tokenize
|
| 40 |
+
|
| 41 |
+
DUCKDB_THRESHOLD = 40_000
|
| 42 |
+
SQLITE_THRESHOLD = DUCKDB_THRESHOLD # backward-compatible alias; not SQLite
|
| 43 |
+
BATCH = 256
|
| 44 |
+
NEIGHBOR_SHARD = 5_000
|
| 45 |
+
NEIGHBOR_K = 8
|
| 46 |
+
DF_CAP = 1500
|
| 47 |
+
MAX_QTERMS = 8
|
| 48 |
+
TITLE_W = TITLE_WEIGHT
|
| 49 |
+
BODY_W = BODY_WEIGHT
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def spill_dir_for(slug: str, cache: Path) -> Path:
|
| 53 |
+
return Path(cache) / f"{slug}_bm25_spill"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def spill_pickle(path: Path, obj: Any) -> None:
|
| 57 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 58 |
+
tmp = path.with_suffix(path.suffix + ".tmp")
|
| 59 |
+
with tmp.open("wb") as f:
|
| 60 |
+
pickle.dump(obj, f, protocol=pickle.HIGHEST_PROTOCOL)
|
| 61 |
+
tmp.replace(path)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def load_pickle(path: Path) -> Any:
|
| 65 |
+
with path.open("rb") as f:
|
| 66 |
+
return pickle.load(f)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _idf(n_docs: int, df: int) -> float:
|
| 70 |
+
return math.log((n_docs - df + 0.5) / (df + 0.5) + 1.0)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _require_duckdb():
|
| 74 |
+
try:
|
| 75 |
+
import duckdb # type: ignore
|
| 76 |
+
except ImportError as exc:
|
| 77 |
+
raise RuntimeError("duckdb is required for sparse GraphRAG spill (no sqlite)") from exc
|
| 78 |
+
return duckdb
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def duckdb_ready(db_path: Path, expected: int) -> bool:
|
| 82 |
+
if not db_path.is_file():
|
| 83 |
+
return False
|
| 84 |
+
duckdb = _require_duckdb()
|
| 85 |
+
try:
|
| 86 |
+
conn = duckdb.connect(str(db_path), read_only=True)
|
| 87 |
+
n = int(conn.execute("SELECT COUNT(*) FROM documents").fetchone()[0])
|
| 88 |
+
conn.close()
|
| 89 |
+
return n == expected
|
| 90 |
+
except Exception:
|
| 91 |
+
return False
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def build_sqlite_fts(*args, **kwargs): # pragma: no cover - removed
|
| 95 |
+
raise RuntimeError("SQLite FTS is removed; use DuckDB parquet neighbors")
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def neighbors_via_duckdb(
|
| 99 |
+
corpus_path: Path,
|
| 100 |
+
spill: Path,
|
| 101 |
+
n_docs: int,
|
| 102 |
+
*,
|
| 103 |
+
k: int = NEIGHBOR_K,
|
| 104 |
+
resume: bool = True,
|
| 105 |
+
log: Callable[[str], None] | None = None,
|
| 106 |
+
) -> list[Path]:
|
| 107 |
+
"""DuckDB FTS over corpus parquet → neighbor_*.parquet shards. No SQLite."""
|
| 108 |
+
from .duckdb_store import build_fts_index, stream_neighbors_to_parquet
|
| 109 |
+
|
| 110 |
+
spill = Path(spill)
|
| 111 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
db_path = spill / "neighbors.duckdb"
|
| 113 |
+
if not duckdb_ready(db_path, n_docs):
|
| 114 |
+
if db_path.exists():
|
| 115 |
+
db_path.unlink()
|
| 116 |
+
if log:
|
| 117 |
+
log(f"building duckdb fts n={n_docs} -> {db_path}")
|
| 118 |
+
build_fts_index(corpus_path, db_path, n_docs, log=log)
|
| 119 |
+
else:
|
| 120 |
+
if log:
|
| 121 |
+
log(f"reusing duckdb fts n={n_docs} path={db_path}")
|
| 122 |
+
return stream_neighbors_to_parquet(
|
| 123 |
+
db_path, spill, n_docs, k=k, resume=resume, log=log
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def iter_neighbor_shards(spill: Path) -> Iterator[tuple[int, list]]:
|
| 128 |
+
"""Yield (start_index, shard_list) from parquet neighbor shards."""
|
| 129 |
+
from .duckdb_store import iter_neighbor_parquet_shards
|
| 130 |
+
|
| 131 |
+
parquet = list(Path(spill).glob("neighbors_*.parquet"))
|
| 132 |
+
if parquet:
|
| 133 |
+
yield from iter_neighbor_parquet_shards(spill)
|
| 134 |
+
return
|
| 135 |
+
# Legacy pickle shards (pre-DuckDB). Do not create new ones.
|
| 136 |
+
paths = sorted(Path(spill).glob("neighbors_*.pkl"))
|
| 137 |
+
for sp in paths:
|
| 138 |
+
parts = sp.stem.split("_")
|
| 139 |
+
start_i = int(parts[1])
|
| 140 |
+
yield start_i, load_pickle(sp)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def assemble_neighbors_streaming(spill: Path, n_docs: int) -> list:
|
| 144 |
+
"""Assemble only when unavoidable; prefer build_graph_from_neighbor_shards."""
|
| 145 |
+
neighbors: list = []
|
| 146 |
+
for start_i, part in iter_neighbor_shards(spill):
|
| 147 |
+
while len(neighbors) < start_i:
|
| 148 |
+
neighbors.append([])
|
| 149 |
+
neighbors.extend(part)
|
| 150 |
+
del part
|
| 151 |
+
gc.collect()
|
| 152 |
+
while len(neighbors) < n_docs:
|
| 153 |
+
neighbors.append([])
|
| 154 |
+
if len(neighbors) > n_docs:
|
| 155 |
+
neighbors = neighbors[:n_docs]
|
| 156 |
+
return neighbors
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def neighbors_via_sqlite(*args, **kwargs):
|
| 160 |
+
"""Removed. Sparse GraphRAG neighbors are DuckDB/parquet only."""
|
| 161 |
+
return neighbors_via_duckdb(*args, **kwargs)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def build_graph_from_neighbor_shards(
|
| 165 |
+
corpus: pd.DataFrame,
|
| 166 |
+
spill: Path,
|
| 167 |
+
*,
|
| 168 |
+
log: Callable[[str], None] | None = None,
|
| 169 |
+
) -> dict[str, Any]:
|
| 170 |
+
"""Build graph without holding the full neighbor list.
|
| 171 |
+
|
| 172 |
+
Structural edges first (neighbors=[]), then stream BM25_NEIGHBOR_OF from shards
|
| 173 |
+
and recompute adjacency once.
|
| 174 |
+
"""
|
| 175 |
+
n = len(corpus)
|
| 176 |
+
# Structural + facets only
|
| 177 |
+
graph = build_graph(corpus, [[] for _ in range(n)])
|
| 178 |
+
cid_by_idx = corpus["entry_cid"].tolist()
|
| 179 |
+
extra_edges: list[dict[str, Any]] = []
|
| 180 |
+
seen = 0
|
| 181 |
+
for start_i, part in iter_neighbor_shards(spill):
|
| 182 |
+
for offset, neigh in enumerate(part):
|
| 183 |
+
i = start_i + offset
|
| 184 |
+
if i >= n:
|
| 185 |
+
break
|
| 186 |
+
src = cid_by_idx[i]
|
| 187 |
+
for item in neigh:
|
| 188 |
+
if len(item) == 3:
|
| 189 |
+
j, score, terms = item
|
| 190 |
+
else:
|
| 191 |
+
j, score = item[0], item[1]
|
| 192 |
+
terms = []
|
| 193 |
+
tgt = cid_by_idx[int(j)]
|
| 194 |
+
extra_edges.append(
|
| 195 |
+
_edge(
|
| 196 |
+
src,
|
| 197 |
+
"BM25_NEIGHBOR_OF",
|
| 198 |
+
tgt,
|
| 199 |
+
"bm25-okapi",
|
| 200 |
+
float(score),
|
| 201 |
+
{"k": 8, "neighbor_index": int(j)},
|
| 202 |
+
matched_terms=list(terms),
|
| 203 |
+
)
|
| 204 |
+
)
|
| 205 |
+
seen += len(part)
|
| 206 |
+
del part
|
| 207 |
+
if len(extra_edges) >= 50_000:
|
| 208 |
+
# Flush into edges df incrementally
|
| 209 |
+
add = pd.DataFrame(extra_edges)
|
| 210 |
+
graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True)
|
| 211 |
+
extra_edges.clear()
|
| 212 |
+
del add
|
| 213 |
+
gc.collect()
|
| 214 |
+
checkpoint(f"graph_neighbor_edges@{seen}", row=seen, every_n=50_000, log=log)
|
| 215 |
+
if extra_edges:
|
| 216 |
+
add = pd.DataFrame(extra_edges)
|
| 217 |
+
graph["edges"] = pd.concat([graph["edges"], add], ignore_index=True)
|
| 218 |
+
del add, extra_edges
|
| 219 |
+
gc.collect()
|
| 220 |
+
|
| 221 |
+
edges_df = graph["edges"]
|
| 222 |
+
if not edges_df.empty:
|
| 223 |
+
edges_df = edges_df.drop_duplicates("edge_cid").reset_index(drop=True)
|
| 224 |
+
edges_df = edges_df.sort_values(
|
| 225 |
+
["edge_type", "source_cid", "target_cid"]
|
| 226 |
+
).reset_index(drop=True)
|
| 227 |
+
graph["edges"] = edges_df
|
| 228 |
+
node_type = {r["node_cid"]: r["node_type"] for r in graph["nodes"].to_dict("records")}
|
| 229 |
+
incoming, outgoing = _adjacency(edges_df, node_type)
|
| 230 |
+
graph["incoming"] = incoming
|
| 231 |
+
graph["outgoing"] = outgoing
|
| 232 |
+
graph["stats"] = {
|
| 233 |
+
"n_nodes": int(len(graph["nodes"])),
|
| 234 |
+
"n_edges": int(len(edges_df)),
|
| 235 |
+
"n_doc_nodes": int(
|
| 236 |
+
graph["nodes"]["node_type"].isin(["law_entry", "article", "law"]).sum()
|
| 237 |
+
),
|
| 238 |
+
"n_facet_nodes": int(
|
| 239 |
+
graph["nodes"]["node_type"].astype(str).str.startswith("facet_").sum()
|
| 240 |
+
),
|
| 241 |
+
"edge_types": sorted(edges_df["edge_type"].unique().tolist())
|
| 242 |
+
if not edges_df.empty
|
| 243 |
+
else [],
|
| 244 |
+
}
|
| 245 |
+
if log:
|
| 246 |
+
log(
|
| 247 |
+
f"graph from shards nodes={graph['stats']['n_nodes']} "
|
| 248 |
+
f"edges={graph['stats']['n_edges']}"
|
| 249 |
+
)
|
| 250 |
+
return graph
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def build_bm25_tf_spill(
|
| 254 |
+
corpus_path: Path,
|
| 255 |
+
spill: Path,
|
| 256 |
+
n_docs: int,
|
| 257 |
+
*,
|
| 258 |
+
batch: int = 512,
|
| 259 |
+
log: Callable[[str], None] | None = None,
|
| 260 |
+
) -> dict[str, Any]:
|
| 261 |
+
"""Stream tokenize corpus → DuckDB TF → bm25_documents/postings parquet + stats.
|
| 262 |
+
|
| 263 |
+
Resume: if bm25_documents.parquet + bm25_postings.parquet + bm25_stats.json exist
|
| 264 |
+
with matching n_docs, reuse.
|
| 265 |
+
"""
|
| 266 |
+
spill.mkdir(parents=True, exist_ok=True)
|
| 267 |
+
docs_path = spill / "bm25_documents.parquet"
|
| 268 |
+
post_path = spill / "bm25_postings.parquet"
|
| 269 |
+
stats_json = spill / "bm25_stats.json"
|
| 270 |
+
stats_path = spill / "bm25_stats.pkl"
|
| 271 |
+
if docs_path.is_file() and post_path.is_file():
|
| 272 |
+
stats = None
|
| 273 |
+
if stats_json.is_file():
|
| 274 |
+
stats = json.loads(stats_json.read_text(encoding="utf-8"))
|
| 275 |
+
elif stats_path.is_file():
|
| 276 |
+
stats = load_pickle(stats_path)
|
| 277 |
+
if stats is not None and int(stats.get("n_docs", -1)) == n_docs:
|
| 278 |
+
if log:
|
| 279 |
+
log(f"reusing bm25 spill n_docs={n_docs}")
|
| 280 |
+
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 281 |
+
|
| 282 |
+
duckdb = _require_duckdb()
|
| 283 |
+
bm25_db = spill / "bm25_tf.duckdb"
|
| 284 |
+
if bm25_db.exists():
|
| 285 |
+
bm25_db.unlink()
|
| 286 |
+
conn = duckdb.connect(str(bm25_db))
|
| 287 |
+
conn.execute(
|
| 288 |
+
"CREATE TABLE tf (term VARCHAR NOT NULL, doc INTEGER NOT NULL, "
|
| 289 |
+
"ttf INTEGER NOT NULL, btf INTEGER NOT NULL)"
|
| 290 |
+
)
|
| 291 |
+
title_len = np.zeros(n_docs, dtype=np.int32)
|
| 292 |
+
body_len = np.zeros(n_docs, dtype=np.int32)
|
| 293 |
+
meta_path = spill / "doc_meta_rows.parquet"
|
| 294 |
+
meta_path.unlink(missing_ok=True)
|
| 295 |
+
meta_buf: list[dict] = []
|
| 296 |
+
pf = pq.ParquetFile(corpus_path)
|
| 297 |
+
schema_names = set(pf.schema_arrow.names)
|
| 298 |
+
cols = [
|
| 299 |
+
c
|
| 300 |
+
for c in [
|
| 301 |
+
"document_index",
|
| 302 |
+
"entry_cid",
|
| 303 |
+
"law_cid",
|
| 304 |
+
"instrument_id",
|
| 305 |
+
"law_id",
|
| 306 |
+
"source_id",
|
| 307 |
+
"title",
|
| 308 |
+
"instrument_title",
|
| 309 |
+
"article_number",
|
| 310 |
+
"article_title",
|
| 311 |
+
"record_type",
|
| 312 |
+
"language",
|
| 313 |
+
"jurisdiction",
|
| 314 |
+
"body",
|
| 315 |
+
]
|
| 316 |
+
if c in schema_names
|
| 317 |
+
]
|
| 318 |
+
processed = 0
|
| 319 |
+
batch_rows: list[tuple] = []
|
| 320 |
+
for batch_tbl in pf.iter_batches(batch_size=batch, columns=cols):
|
| 321 |
+
d = batch_tbl.to_pydict()
|
| 322 |
+
m = len(d["document_index"])
|
| 323 |
+
for i in range(m):
|
| 324 |
+
di = int(d["document_index"][i])
|
| 325 |
+
title = str((d.get("title") or [""])[i] or "")
|
| 326 |
+
body = str((d.get("body") or [""])[i] or "")
|
| 327 |
+
tt = tokenize(title)
|
| 328 |
+
bt = tokenize(body)
|
| 329 |
+
title_len[di] = len(tt)
|
| 330 |
+
body_len[di] = len(bt)
|
| 331 |
+
tf_t: dict[str, int] = defaultdict(int)
|
| 332 |
+
tf_b: dict[str, int] = defaultdict(int)
|
| 333 |
+
for tok in tt:
|
| 334 |
+
tf_t[tok] += 1
|
| 335 |
+
for tok in bt:
|
| 336 |
+
tf_b[tok] += 1
|
| 337 |
+
for tok in set(tf_t) | set(tf_b):
|
| 338 |
+
batch_rows.append((tok, di, int(tf_t.get(tok, 0)), int(tf_b.get(tok, 0))))
|
| 339 |
+
law_id = str((d.get("law_id") or d.get("instrument_id") or [""])[i] or "")
|
| 340 |
+
instrument_id = str(
|
| 341 |
+
(d.get("instrument_id") or d.get("law_id") or [""])[i] or ""
|
| 342 |
+
)
|
| 343 |
+
meta_buf.append(
|
| 344 |
+
{
|
| 345 |
+
"entry_cid": str(d["entry_cid"][i]),
|
| 346 |
+
"document_index": di,
|
| 347 |
+
"law_cid": str((d.get("law_cid") or [""])[i] or ""),
|
| 348 |
+
"instrument_id": instrument_id,
|
| 349 |
+
"law_id": law_id,
|
| 350 |
+
"source_id": str(d["source_id"][i]),
|
| 351 |
+
"title": title,
|
| 352 |
+
"instrument_title": str(
|
| 353 |
+
(d.get("instrument_title") or [""])[i] or ""
|
| 354 |
+
),
|
| 355 |
+
"article_number": str((d.get("article_number") or [""])[i] or ""),
|
| 356 |
+
"article_title": str((d.get("article_title") or [""])[i] or ""),
|
| 357 |
+
"record_type": str(d["record_type"][i]),
|
| 358 |
+
"language": str((d.get("language") or [""])[i] or ""),
|
| 359 |
+
"jurisdiction": str((d.get("jurisdiction") or [""])[i] or ""),
|
| 360 |
+
}
|
| 361 |
+
)
|
| 362 |
+
if len(batch_rows) >= 20_000:
|
| 363 |
+
conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows)
|
| 364 |
+
batch_rows.clear()
|
| 365 |
+
processed += m
|
| 366 |
+
if len(meta_buf) >= 20_000:
|
| 367 |
+
dfm = pd.DataFrame(meta_buf)
|
| 368 |
+
if meta_path.exists():
|
| 369 |
+
old = pd.read_parquet(meta_path)
|
| 370 |
+
dfm = pd.concat([old, dfm], ignore_index=True)
|
| 371 |
+
del old
|
| 372 |
+
dfm.to_parquet(meta_path, index=False)
|
| 373 |
+
del dfm
|
| 374 |
+
meta_buf.clear()
|
| 375 |
+
gc.collect()
|
| 376 |
+
if processed % 20_000 == 0:
|
| 377 |
+
checkpoint(f"bm25_tf_tokenize", row=processed, every_n=20_000, log=log)
|
| 378 |
+
gc.collect()
|
| 379 |
+
if batch_rows:
|
| 380 |
+
conn.executemany("INSERT INTO tf VALUES (?, ?, ?, ?)", batch_rows)
|
| 381 |
+
batch_rows.clear()
|
| 382 |
+
if meta_buf:
|
| 383 |
+
dfm = pd.DataFrame(meta_buf)
|
| 384 |
+
if meta_path.exists():
|
| 385 |
+
old = pd.read_parquet(meta_path)
|
| 386 |
+
dfm = pd.concat([old, dfm], ignore_index=True)
|
| 387 |
+
del old
|
| 388 |
+
dfm.to_parquet(meta_path, index=False)
|
| 389 |
+
del dfm
|
| 390 |
+
meta_buf.clear()
|
| 391 |
+
if log:
|
| 392 |
+
log("bm25 tf spilled to duckdb; writing documents")
|
| 393 |
+
|
| 394 |
+
doc_len = (title_len * TITLE_WEIGHT + body_len * BODY_WEIGHT).astype(np.float64)
|
| 395 |
+
avgdl = float(doc_len.mean()) if n_docs else 0.0
|
| 396 |
+
meta_df = pd.read_parquet(meta_path).sort_values("document_index").reset_index(drop=True)
|
| 397 |
+
assert len(meta_df) == n_docs
|
| 398 |
+
meta_df["title_length"] = title_len[meta_df["document_index"].to_numpy()]
|
| 399 |
+
meta_df["body_length"] = body_len[meta_df["document_index"].to_numpy()]
|
| 400 |
+
meta_df["document_length"] = np.round(
|
| 401 |
+
doc_len[meta_df["document_index"].to_numpy()]
|
| 402 |
+
).astype(int)
|
| 403 |
+
meta_df["schema_version"] = SCHEMA_VERSION
|
| 404 |
+
meta_df.to_parquet(docs_path, index=False)
|
| 405 |
+
del meta_df
|
| 406 |
+
gc.collect()
|
| 407 |
+
meta_path.unlink(missing_ok=True)
|
| 408 |
+
|
| 409 |
+
posting_rows: list[dict] = []
|
| 410 |
+
n_postings = 0
|
| 411 |
+
n_terms = 0
|
| 412 |
+
part_i = 0
|
| 413 |
+
cur_term = None
|
| 414 |
+
cur_items: list = []
|
| 415 |
+
|
| 416 |
+
def flush_term(term: str, items: list) -> None:
|
| 417 |
+
nonlocal n_postings, n_terms, part_i, posting_rows
|
| 418 |
+
if not items:
|
| 419 |
+
return
|
| 420 |
+
n_terms += 1
|
| 421 |
+
dfreq = len(items)
|
| 422 |
+
cfreq = sum(int(ttf) + int(btf) for _, ttf, btf in items)
|
| 423 |
+
idf = _idf(n_docs, dfreq)
|
| 424 |
+
chunks = [
|
| 425 |
+
items[i : i + POSTING_ROWS_PER_RECORD]
|
| 426 |
+
for i in range(0, max(len(items), 1), POSTING_ROWS_PER_RECORD)
|
| 427 |
+
]
|
| 428 |
+
n_chunks = len(chunks)
|
| 429 |
+
for cidx, chunk in enumerate(chunks):
|
| 430 |
+
posting_rows.append(
|
| 431 |
+
{
|
| 432 |
+
"term": term,
|
| 433 |
+
"document_indices": [int(d) for d, _, _ in chunk],
|
| 434 |
+
"title_frequencies": [int(ttf) for _, ttf, _ in chunk],
|
| 435 |
+
"body_frequencies": [int(btf) for _, _, btf in chunk],
|
| 436 |
+
"tfs": [
|
| 437 |
+
TITLE_WEIGHT * int(ttf) + BODY_WEIGHT * int(btf)
|
| 438 |
+
for _, ttf, btf in chunk
|
| 439 |
+
],
|
| 440 |
+
"lengths": [int(round(doc_len[int(d)])) for d, _, _ in chunk],
|
| 441 |
+
"document_lengths": [
|
| 442 |
+
int(round(doc_len[int(d)])) for d, _, _ in chunk
|
| 443 |
+
],
|
| 444 |
+
"document_frequency": int(dfreq),
|
| 445 |
+
"corpus_frequency": int(cfreq),
|
| 446 |
+
"idf": float(idf),
|
| 447 |
+
"posting_chunk_index": int(cidx),
|
| 448 |
+
"posting_chunk_count": int(n_chunks),
|
| 449 |
+
"schema_version": SCHEMA_VERSION,
|
| 450 |
+
}
|
| 451 |
+
)
|
| 452 |
+
n_postings += dfreq
|
| 453 |
+
if len(posting_rows) >= 8_000:
|
| 454 |
+
pd.DataFrame(posting_rows).to_parquet(
|
| 455 |
+
spill / f"postings_part_{part_i:08d}.parquet", index=False
|
| 456 |
+
)
|
| 457 |
+
posting_rows.clear()
|
| 458 |
+
part_i += 1
|
| 459 |
+
gc.collect()
|
| 460 |
+
|
| 461 |
+
for term, doc, ttf, btf in conn.execute(
|
| 462 |
+
"SELECT term, doc, ttf, btf FROM tf ORDER BY term, doc"
|
| 463 |
+
).fetchall():
|
| 464 |
+
term = str(term)
|
| 465 |
+
if cur_term is None:
|
| 466 |
+
cur_term = term
|
| 467 |
+
if term != cur_term:
|
| 468 |
+
flush_term(cur_term, cur_items)
|
| 469 |
+
cur_items = []
|
| 470 |
+
cur_term = term
|
| 471 |
+
if n_terms and n_terms % 50_000 == 0:
|
| 472 |
+
checkpoint(f"bm25_postings_terms", row=n_terms, every_n=50_000, log=log)
|
| 473 |
+
cur_items.append((int(doc), int(ttf), int(btf)))
|
| 474 |
+
if cur_term is not None:
|
| 475 |
+
flush_term(cur_term, cur_items)
|
| 476 |
+
if posting_rows:
|
| 477 |
+
pd.DataFrame(posting_rows).to_parquet(
|
| 478 |
+
spill / f"postings_part_{part_i:08d}.parquet", index=False
|
| 479 |
+
)
|
| 480 |
+
posting_rows.clear()
|
| 481 |
+
conn.close()
|
| 482 |
+
gc.collect()
|
| 483 |
+
|
| 484 |
+
parts = sorted(spill.glob("postings_part_*.parquet"))
|
| 485 |
+
frames: list[pd.DataFrame] = []
|
| 486 |
+
for i, part in enumerate(parts):
|
| 487 |
+
frames.append(pd.read_parquet(part))
|
| 488 |
+
if len(frames) >= 8:
|
| 489 |
+
frames = [pd.concat(frames, ignore_index=True)]
|
| 490 |
+
gc.collect()
|
| 491 |
+
if i and i % 20 == 0:
|
| 492 |
+
checkpoint(f"concat_postings", row=i, every_n=20, log=log)
|
| 493 |
+
postings = pd.concat(frames, ignore_index=True) if frames else pd.DataFrame()
|
| 494 |
+
del frames
|
| 495 |
+
for part in parts:
|
| 496 |
+
part.unlink()
|
| 497 |
+
postings.to_parquet(post_path, index=False)
|
| 498 |
+
out_rows = len(postings)
|
| 499 |
+
del postings
|
| 500 |
+
gc.collect()
|
| 501 |
+
stats = {
|
| 502 |
+
"k1": K1,
|
| 503 |
+
"b": B,
|
| 504 |
+
"title_weight": TITLE_WEIGHT,
|
| 505 |
+
"body_weight": BODY_WEIGHT,
|
| 506 |
+
"average_document_length": avgdl,
|
| 507 |
+
"tokenizer": "fts5-unicode61-remove-diacritics-2-python/v1",
|
| 508 |
+
"max_query_terms": 64,
|
| 509 |
+
"posting_rows_per_record": POSTING_ROWS_PER_RECORD,
|
| 510 |
+
"terms_per_shard": TERMS_PER_SHARD,
|
| 511 |
+
"n_docs": n_docs,
|
| 512 |
+
"n_terms": int(n_terms),
|
| 513 |
+
"n_posting_rows": int(out_rows),
|
| 514 |
+
"n_postings": int(n_postings),
|
| 515 |
+
}
|
| 516 |
+
stats_json.write_text(json.dumps(stats, indent=2) + "\n", encoding="utf-8")
|
| 517 |
+
try:
|
| 518 |
+
bm25_db.unlink()
|
| 519 |
+
except Exception:
|
| 520 |
+
pass
|
| 521 |
+
if log:
|
| 522 |
+
log(f"bm25 spill done terms={n_terms} posting_rows={out_rows}")
|
| 523 |
+
return {"stats": stats, "documents": docs_path, "postings": post_path}
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def should_use_spill(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool:
|
| 527 |
+
return n_docs >= threshold
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def should_use_sqlite(n_docs: int, threshold: int = DUCKDB_THRESHOLD) -> bool:
|
| 531 |
+
"""Alias: large-corpus path is DuckDB/parquet, not SQLite."""
|
| 532 |
+
return should_use_spill(n_docs, threshold)
|
scrapers_and_normalizers/ipfs_datasets_py/processors/legal_scrapers/country_laws_ir/structure.py
ADDED
|
@@ -0,0 +1,2203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Extract legal hierarchy from country-law text (Oregon-style, multilingual).
|
| 2 |
+
|
| 3 |
+
Oregon Revised Statutes are stored as title / chapter / section / subsection
|
| 4 |
+
trees. National gazettes are not that uniform: some use Article/Artikel,
|
| 5 |
+
some §, some only a single instrument body.
|
| 6 |
+
|
| 7 |
+
This module:
|
| 8 |
+
|
| 9 |
+
* strips leftover HTML chrome so GraphRAG sees legal text, not tags;
|
| 10 |
+
* detects multilingual heading markers (title/chapter/part/article/section);
|
| 11 |
+
* splits an instrument into those units when at least two headings exist;
|
| 12 |
+
* otherwise keeps the whole instrument (never invents a hierarchy).
|
| 13 |
+
|
| 14 |
+
Subsection markers such as ``(a)`` / ``(1)`` are recorded on the parent
|
| 15 |
+
unit; they are not forced into their own retrieval rows.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
from dataclasses import dataclass, field
|
| 21 |
+
from html.parser import HTMLParser
|
| 22 |
+
import html as html_lib
|
| 23 |
+
import json
|
| 24 |
+
import os
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
import re
|
| 27 |
+
import unicodedata
|
| 28 |
+
from typing import Any
|
| 29 |
+
|
| 30 |
+
_WS_RE = re.compile(r"\s+", re.UNICODE)
|
| 31 |
+
_HAS_TAG_RE = re.compile(r"</?[a-zA-Z][^>]*>")
|
| 32 |
+
|
| 33 |
+
# 1:1 map so match offsets stay aligned with the stored body. re.I does not
|
| 34 |
+
# treat É as E; gazettes use Décision, Ordonnance, Điều, Člen, etc.
|
| 35 |
+
_LATIN_FOLD = str.maketrans({
|
| 36 |
+
**dict.fromkeys("áàâäãåăąāấầẩẫậắằẳẵặảạ", "a"),
|
| 37 |
+
**dict.fromkeys("ÁÀÂÄÃÅĂĄĀẢẠ", "A"),
|
| 38 |
+
**dict.fromkeys("éèêëěęēếềểễệẻẹə", "e"),
|
| 39 |
+
**dict.fromkeys("ÉÈÊËĚĘĒẺẸƏ", "E"),
|
| 40 |
+
**dict.fromkeys("íìîïĩįīıịỉ", "i"),
|
| 41 |
+
**dict.fromkeys("ÍÌÎÏĨĮĪİỈỊ", "I"),
|
| 42 |
+
**dict.fromkeys("óòôöõőøōốồổỗộớờởỡợỏọ", "o"),
|
| 43 |
+
**dict.fromkeys("ÓÒÔÖÕŐØŌỎỌ", "O"),
|
| 44 |
+
**dict.fromkeys("úùûüűũūůứừửữựủụ", "u"),
|
| 45 |
+
**dict.fromkeys("ÚÙÛÜŰŨŪŮỦỤ", "U"),
|
| 46 |
+
**dict.fromkeys("ýÿỳỹỷỵ", "y"),
|
| 47 |
+
**dict.fromkeys("ÝŸỶỴ", "Y"),
|
| 48 |
+
**dict.fromkeys("çćčĉċ", "c"),
|
| 49 |
+
**dict.fromkeys("ÇĆČĈĊ", "C"),
|
| 50 |
+
**dict.fromkeys("ďđ", "d"),
|
| 51 |
+
**dict.fromkeys("ĎĐ", "D"),
|
| 52 |
+
**dict.fromkeys("ğĝģġ", "g"),
|
| 53 |
+
**dict.fromkeys("ĞĜĢĠ", "G"),
|
| 54 |
+
**dict.fromkeys("ñńņň", "n"),
|
| 55 |
+
**dict.fromkeys("ÑŃŅŇ", "N"),
|
| 56 |
+
**dict.fromkeys("ŕŗř", "r"),
|
| 57 |
+
**dict.fromkeys("ŔŖŘ", "R"),
|
| 58 |
+
**dict.fromkeys("śŝşšș", "s"),
|
| 59 |
+
**dict.fromkeys("ŚŜŞŠȘ", "S"),
|
| 60 |
+
**dict.fromkeys("ţťț", "t"),
|
| 61 |
+
**dict.fromkeys("ŢŤȚ", "T"),
|
| 62 |
+
**dict.fromkeys("źżž", "z"),
|
| 63 |
+
**dict.fromkeys("ŹŻŽ", "Z"),
|
| 64 |
+
**dict.fromkeys("ĺļľł", "l"),
|
| 65 |
+
**dict.fromkeys("ĹĻĽŁ", "L"),
|
| 66 |
+
"æ": "a", "Æ": "A", "œ": "o", "Œ": "O", "ß": "s",
|
| 67 |
+
"ɛ": "e", "Ɛ": "E", "ɔ": "o", "Ɔ": "O", "ŋ": "n", "Ŋ": "N",
|
| 68 |
+
**dict.fromkeys("ơớờởỡợ", "o"),
|
| 69 |
+
**dict.fromkeys("ƠỚỜỞỠỢ", "O"),
|
| 70 |
+
**dict.fromkeys("ưứừửữự", "u"),
|
| 71 |
+
**dict.fromkeys("ƯỨỪỬỮỰ", "U"),
|
| 72 |
+
**dict(zip("άέήίόύώϊϋΐΰ", "αεηιουωιυιυ")),
|
| 73 |
+
**dict(zip("ΆΈΉΊΌΎΏ", "ΑΕΗΙΟΥΩ")),
|
| 74 |
+
"ς": "σ",
|
| 75 |
+
"ё": "е", "Ё": "Е", "ї": "и", "Ї": "И", "є": "е", "Є": "Е", "ґ": "г", "Ґ": "Г",
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _latin_fold(text: str) -> str:
|
| 80 |
+
return text.translate(_LATIN_FOLD)
|
| 81 |
+
|
| 82 |
+
# Headings at line start *or* after . ; : so compacted "Art. 1. … Art. 2." still splits.
|
| 83 |
+
# Separator allows "Art. 1", "Art.1", "Član 12.", "ARTICULO 10.-", "Madde 1 –",
|
| 84 |
+
# "Article (1)", French "Art. L. 111-1", Roman "ARTICLE I".
|
| 85 |
+
_HEADING_NUM = (
|
| 86 |
+
r"(?:[0-9٠-٩۰-۹]+(?:er|ère|bis|ter|quater|o)?"
|
| 87 |
+
r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])"
|
| 88 |
+
r"|premier(?:e)?|première|primero|primeira"
|
| 89 |
+
r"|unique|unico|unica|único|única)"
|
| 90 |
+
)
|
| 91 |
+
_ARTICLE_N = (
|
| 92 |
+
r"(?:"
|
| 93 |
+
r"(?:[LRD]\.?\s*)?"
|
| 94 |
+
r"(?:"
|
| 95 |
+
r"[0-9٠-٩۰-۹]+(?:\.[0-9]+)?"
|
| 96 |
+
r"(?:er|ère|bis|ter|quater|aad|[A-Za-z]|o)?"
|
| 97 |
+
r"(?:/[0-9A-Za-z]+)?"
|
| 98 |
+
r"(?:\s+(?:bis|ter|quater))?"
|
| 99 |
+
r"|(?-i:[IVXLCDM]{1,8})(?:er|ère)?(?![A-Za-z])"
|
| 100 |
+
r"|[Α-Ω]{1,6}(?![Α-Ωα-ω])"
|
| 101 |
+
r")"
|
| 102 |
+
r"(?:[-–](?:[0-9]+|aad|bis|ter|quater|[A-Za-z](?![A-Za-z])))?"
|
| 103 |
+
r"(?:\([0-9A-Za-z]+\))?"
|
| 104 |
+
r"|premier(?:e)?"
|
| 105 |
+
r"|première"
|
| 106 |
+
r"|unique|unico|unica|único|única"
|
| 107 |
+
r"|primero|primera|primeiro|primeira"
|
| 108 |
+
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])"
|
| 109 |
+
r"|eerste|första|første"
|
| 110 |
+
r"|annexe"
|
| 111 |
+
r"|primera|segunda|tercera|cuarta|quinta"
|
| 112 |
+
r"|sexta|séptima|octava|novena|décima"
|
| 113 |
+
r")"
|
| 114 |
+
)
|
| 115 |
+
_HEADING_START = r"(?:^|(?<=[.;:])|(?<=\d[ \t]))[ \t\[\(\u00ab\u00bb\"“”‘’«»‹›\u2039\u203a]*"
|
| 116 |
+
_HEADING_RE = re.compile(
|
| 117 |
+
_latin_fold(
|
| 118 |
+
r"(?im)" + _HEADING_START + r"(?:"
|
| 119 |
+
r"(?P<title>TITLE|TITRE|TITEL|T[IÍ]TULO|TITOLO|TITLUL|T[IÍ]TUL|LUKU|PEAT[UÜ]KK|"
|
| 120 |
+
r"РАЗДЕЛ|РОЗДІЛ|DZIA[ŁL]|ΤΙΤΛΟΣ|ДЯЛ)\s+"
|
| 121 |
+
r"(?P<title_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)"
|
| 122 |
+
r"|(?P<chapter>CHAPTER|CHAPITRE|KAPITEL|CAP[IÍ]TULO|CAPITOLO|HOOFDSTUK|"
|
| 123 |
+
r"ROZDZIA[ŁL]|CAPITOLUL|NODA[ĻL]A|GLAVA|ГЛАВА|POGLAVLJE|KAPITOLA|"
|
| 124 |
+
r"ΚΕΦΑΛΑΙ[ΟO]|CH[UƯ][OƠ]NG|BAB|KABANATA|CAPO|HLAVA|KREU|FEJEZET|"
|
| 125 |
+
r"B[ÖO]L[ÜU]M|FESIL|CAIBIDIL|PENNOD|KAPITOLU|CHAPIT|ODDIEL|"
|
| 126 |
+
r"SURA(?:\s+YA)?|KAPITTEL|KAPITTUL|ANDIANY|SASHE(?:\s+NA)?|WASE|"
|
| 127 |
+
r"ISIGABA|ICANDELO|KGAOLO|BOBI|KUTAA|ORI|CAP\.)\s+"
|
| 128 |
+
r"(?P<chapter_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)"
|
| 129 |
+
r"|(?P<part>PART|PARTIE|TEIL|PARTE|DEEL|LIVRE|BOOK|BUCH|TOMO|KNIHA|"
|
| 130 |
+
r"KODEKS|CODE|ZAKONIK|BAHAGIAN|BAGIAN|SEHEMU|MỤC|MUC|LIBRO|PH[AẦ]N|"
|
| 131 |
+
r"QAYBTA|WAHANGA|VAEGA|HAP|KAROLO|CHIKAMU|BES|EKITUNDU|ETENI|"
|
| 132 |
+
r"AKPA|FAANDA|PATTE|ΜΕΡΟΣ)\s+"
|
| 133 |
+
r"(?P<part_n>" + _HEADING_NUM + r"(?:\.[0-9]+|-(?:[0-9]+|[A-Za-z](?![A-Za-z])))?)"
|
| 134 |
+
r"|(?P<article>(?:l['’])?(?:(?:EK|GEÇICI|GECICI|GEÇİCİ)\s+)?"
|
| 135 |
+
r"(?:ART(?:ICLE|IKEL|ÍCULO|ICULO|IGO|ICOLO|IKKEL|YKU[ŁL]|ICOLUL|ICOL|IKOLU|IKULA)?\.?"
|
| 136 |
+
r"|ART\.|NENI|PASAL|MADDE|MADDƏ|ĐIỀU|ĐIÊU|DIEU|CLANAK|ČLANAK|ČLÁNEK|ČLÁNOK|ČLEN|ČLAN|CLAN"
|
| 137 |
+
r"|ЧЛАНАК|ЧЛАН|ЧЛЕН|ЧЛ\.|СТАТЬЯ|СТАТТЯ|SZAKASZ|CIKK|ΆΡΘΡΟ|ΑΡΘΡΟ"
|
| 138 |
+
r"|PYKÄLÄ|GREIN|PANTS|SEKSYEN|CIKK|KIFUNGU|MODDA|ATIK|KUPU|ATIKOL|"
|
| 139 |
+
r"INGINGO(?:\s+YA)?|NDIME|ABALA|NKEJI|SARIYA|TERE|AHYEDE|PENNAD|ERTHYGEL|HYEDEE|"
|
| 140 |
+
r"ARTIGU|PAUKU|IRAVA"
|
| 141 |
+
r"|მუხლი|ՀՈԴՎԱԾ|Հոդված))(?![A-Za-z])"
|
| 142 |
+
r"(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*"
|
| 143 |
+
r"(?P<article_n>" + _ARTICLE_N + r")\)?"
|
| 144 |
+
r"|(?P<section>SUB(?:-)?SECTION|SECTION|SECCI[OÓ]N|SEZIONE|ABSCHNITT|PARAGRAHV|PARAGRAPHE|PARAGRAAF|PARAGRAPH|"
|
| 145 |
+
r"RECITAL|CONSIDERANDO|"
|
| 146 |
+
r"ALIN[EÉ]A|ALINEATUL|INCISO|P[AÁ]RRAFO|PUNKT(?![A-Za-z])|SATZ(?![A-Za-z])|LID|"
|
| 147 |
+
r"ΠΑΡΑΓΡΑΦΟΣ|ABSATZ|APARTADO|COMMA(?![A-Za-z])|FIKRA|STAVAK|STK\.?|АЛ\.|SEKSHON|"
|
| 148 |
+
r"NUMERAL|CAPOVERSO|NUMMER|"
|
| 149 |
+
r"AYAT|KHOẢN|KHOAN|"
|
| 150 |
+
r"RULE(?![A-Za-z])|REGULATION(?![A-Za-z])|SCHEDULE(?![A-Za-z])|FORM(?![A-Za-z])|"
|
| 151 |
+
r"ORDINANCE|ORDONNANCE|ORDONAN[TŢȚ][AĂÁ]?|ORDIN(?![A-Za-z])|BY-?LAW|DIRECTIVE(?![A-Za-z])|"
|
| 152 |
+
r"D[EÉ]CISION(?![A-Za-z])|DECISION(?![A-Za-z])|DECIZIE|"
|
| 153 |
+
r"BESLUIT(?![A-Za-z])|REGELING(?![A-Za-z])|BESCHIKKING(?![A-Za-z])|"
|
| 154 |
+
r"ODLUKA|PRAVILNIK|HOT[ĂA]R[ÂAÎI]RE|"
|
| 155 |
+
r"RESOLUCI[OÓ]N(?![A-Za-z])|RESOLU[CÇ][AÃ]O(?![A-Za-z])|PORTARIA(?![A-Za-z])|ACUERDO(?![A-Za-z])|"
|
| 156 |
+
r"MEDIDA\s+PROVIS[OÓ]RIA|"
|
| 157 |
+
r"PROCLAMATION(?![A-Za-z])|PROKLAMATION|CIRCULAR(?![A-Za-z])|INSTRUCTION(?![A-Za-z])|"
|
| 158 |
+
r"GUIDELINE(?![A-Za-z])|MEMORANDUM(?![A-Za-z])|"
|
| 159 |
+
r"AVISO(?![A-Za-z])|AVIS(?![A-Za-z])|BEKANNTMACHUNG|MEDDELANDE|"
|
| 160 |
+
r"NORMA(?![A-Za-z])|"
|
| 161 |
+
r"PRESIDENTIAL\s+DECREE|DECRETO-LEI|DECRETO(?![A-Za-z])|DECREE(?![A-Za-z])|"
|
| 162 |
+
r"D[EÉ]CRET-LOI|D[EÉ]CRET(?![A-Za-z])|ARR[EÊ]T[EÉ]|"
|
| 163 |
+
r"DELIBERA[CÇ][AÃ]O|D[EÉ]LIB[EÉ]RATION|COMUNICADO|"
|
| 164 |
+
r"R[EÈ]GLEMENT(?![A-Za-z])|CIRCULAIRE(?![A-Za-z])|VERORDNUNG(?![A-Za-z])|ERLASS(?![A-Za-z])|"
|
| 165 |
+
r"PUNTO(?![A-Za-z])|SUB(?:-)?PARAGRAPH|"
|
| 166 |
+
r"ANNEX(?:E)?(?![A-Za-z])|ANEXO|ANLAGE|BIJLAGE|APPENDIX|ALLEGATO|"
|
| 167 |
+
r"ZA[ŁL][AĄ]CZNIK|BILAGA|LIITE|P[ŘR][IÍ]LOHA|"
|
| 168 |
+
r"UST\.|ODST\.|ODS\.|BEK\.|"
|
| 169 |
+
r"SEC(?:\.|(?=\s+[0-9])))(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?[.\s:]*\(?\s*"
|
| 170 |
+
r"(?P<section_n>(?:[0-9][0-9A-Za-z.\-]*(?:\([0-9A-Za-z]+\))?|"
|
| 171 |
+
r"(?-i:[IVXLCDM]{1,8})(?![A-Za-z])|[A-Za-z](?![A-Za-z])))\)?"
|
| 172 |
+
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]+\))?)"
|
| 173 |
+
r"|(?P<section_pre_n>[0-9]+(?:\s*[a-z])?)\s*\.?\s*(?P<section_pre>§)"
|
| 174 |
+
r"|(?P<grein_n>[0-9]+[a-z]?)\s*\.\s*(?P<grein>gr|pants)(?![A-Za-z])\.?"
|
| 175 |
+
r"|(?P<straipsnis_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<straipsnis>straipsnis)"
|
| 176 |
+
r"|(?P<artikulua_n>[0-9]+[a-z]?)\s*[.]?\s*(?P<artikulua>artikulua)"
|
| 177 |
+
r"|(?P<ledd_n>[0-9]+)\s*[.]?\s*(?P<ledd>ledd)"
|
| 178 |
+
r"|(?P<kap_n>[0-9]+)\s*(?P<kap>kap)\.?"
|
| 179 |
+
r"|(?P<luku_n>[0-9]+)\s*(?P<luku>luku)"
|
| 180 |
+
r"|(?P<fejezet_n>[IVXLCDM0-9]+)\s*\.\s*(?P<fejezet>fejezet)"
|
| 181 |
+
r"|(?P<peatukk_n>[0-9]+)\s*[.]?\s*(?P<peatukk>peat[uü]kk)"
|
| 182 |
+
r"|(?P<skyrius_n>[IVXLCDM0-9]+)\s*(?P<skyrius>skyrius)"
|
| 183 |
+
r"|(?P<nodala_n>[IVXLCDM0-9]+)\s*(?P<nodala>noda[ļl]a)"
|
| 184 |
+
r"|(?P<kafli_n>[IVXLCDM0-9]+)\s*[.]?\s*(?P<kafli>kafli)"
|
| 185 |
+
r"|(?P<bob_n>[0-9]+)\s*-\s*(?P<bob>bob)"
|
| 186 |
+
r"|(?P<tarau_n>[0-9]+)\s*-\s*(?P<tarau>тарау)"
|
| 187 |
+
r"|(?P<bolum_n>[0-9]+)\s*-\s*(?P<bolum>бөлүм)"
|
| 188 |
+
r"|(?P<modda_n>[0-9]+)\s*-\s*(?P<modda>модда|modda)"
|
| 189 |
+
r"|(?P<mn_n>[0-9]+)\s*(?P<mn>(?:дүгээр|дугаар)\s*зүйл)"
|
| 190 |
+
r"|(?P<kk_n>[0-9]+)\s*-?\s*(?P<kk>бап)"
|
| 191 |
+
r"|(?P<mom_n>[0-9]+)\s*(?P<mom>momentti)"
|
| 192 |
+
r"|(?P<order>(?:EXECUTIVE\s+)?ORDER)\s+(?P<order_n>[0-9]+)"
|
| 193 |
+
r"|(?P<kidogo>KIFUNGU\s+KIDOG[OU])\s*\(?\s*(?P<kidogo_n>[0-9]+)"
|
| 194 |
+
r"|(?P<disp>DISPOSICI[OÓ]N)(?:\s+(?:adicional(?:es)?|transitoria(?:s)?|derogatoria(?:s)?|final(?:es)?))?\s+"
|
| 195 |
+
r"(?P<disp_n>" + _ARTICLE_N + r")"
|
| 196 |
+
r"|(?P<esresol>primero|segundo|tercero|cuarto|quinto|sexto|septimo|octavo|noveno|decimo|"
|
| 197 |
+
r"erstens|zweitens|drittens|viertens|funftens|"
|
| 198 |
+
r"premierement|deuxiemement|troisiemement|quatriemement|cinquiemement)\s*:"
|
| 199 |
+
r")"
|
| 200 |
+
)
|
| 201 |
+
)
|
| 202 |
+
# Commonwealth "1. Short title" — used only when keyword headings are scarce.
|
| 203 |
+
_PAREN_SUBSECTION_RE = re.compile(r"^\(\s*[0-9A-Za-z]{1,6}\s*\)")
|
| 204 |
+
_CW_NUM_RE = re.compile(
|
| 205 |
+
r"(?m)^[ \t]*(?P<cw_n>[0-9]+[A-Za-z]?)\.?\s*[-–—]?\s*"
|
| 206 |
+
r"(?:\(\s*[0-9A-Za-z]+\s*\)\s+)?"
|
| 207 |
+
r"(?=[A-Z][a-z]+|[A-Z]{3,}\b|A\s)"
|
| 208 |
+
)
|
| 209 |
+
_MONTH_START_RE = re.compile(
|
| 210 |
+
r"(?i)^(january|february|march|april|may|june|july|august|september|october|november|december|"
|
| 211 |
+
r"janvier|f[eé]vrier|marzo|abril|enero|junio|julio)\b"
|
| 212 |
+
)
|
| 213 |
+
# Malta bye-laws and Zambia Acts put the marginal note before the section number:
|
| 214 |
+
# "Citation. 1." and "Prohibited 33." A dotted number such as "Penalty. 5.1" needs no
|
| 215 |
+
# extra period. Months, chapter citations, and schedule labels are not section notes.
|
| 216 |
+
_MARGINAL_NOTE_RE = re.compile(
|
| 217 |
+
r"(?m)^(?P<marginal>[A-Z][A-Za-z]{2,40}\.?)\s+"
|
| 218 |
+
r"(?P<marginal_n>(?:[0-9]+(?:\.[0-9]+){1,3}|[0-9]{1,4}(?=\.(?!\d))))"
|
| 219 |
+
)
|
| 220 |
+
_MARGINAL_STOP = frozenset({
|
| 221 |
+
"january", "february", "march", "april", "may", "june", "july", "august",
|
| 222 |
+
"september", "october", "november", "december",
|
| 223 |
+
"janvier", "fevrier", "mars", "avril", "mai", "juin", "juillet", "aout",
|
| 224 |
+
"septembre", "octobre", "novembre", "decembre",
|
| 225 |
+
"enero", "febrero", "marzo", "abril", "mayo", "junio", "julio", "agosto",
|
| 226 |
+
"septiembre", "octubre", "noviembre", "diciembre",
|
| 227 |
+
"cap", "from", "open", "table", "figure", "box", "plate", "page", "item",
|
| 228 |
+
"act", "ley", "total", "column", "nr", "no", "nos", "pag", "pagina", "data",
|
| 229 |
+
"saldo", "and", "the", "for",
|
| 230 |
+
})
|
| 231 |
+
_CW_NUM_LANGS = frozenset({"", "en", "hi", "bn", "ne", "ur", "ms", "fil", "sw", "si"})
|
| 232 |
+
_LEXICON_HEADING_RE: re.Pattern[str] | None = None
|
| 233 |
+
_LEXICON_KIND: dict[str, str] = {}
|
| 234 |
+
|
| 235 |
+
_SUBSECTION_RE = re.compile(r"\(([0-9A-Za-z]{1,6})\)")
|
| 236 |
+
|
| 237 |
+
_KIND_RANK = {
|
| 238 |
+
"title": 1,
|
| 239 |
+
"chapter": 2,
|
| 240 |
+
"part": 3,
|
| 241 |
+
"article": 4,
|
| 242 |
+
"section": 5,
|
| 243 |
+
"subsection": 6,
|
| 244 |
+
}
|
| 245 |
+
|
| 246 |
+
MIN_SPLIT_HEADINGS = 2
|
| 247 |
+
MIN_UNIT_CHARS = 40
|
| 248 |
+
|
| 249 |
+
# Markers on the *stored* body (no rewritten newline copy).
|
| 250 |
+
_ZH_ART_RE = re.compile(
|
| 251 |
+
r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:之[一二三四五六七八九十百0-9]+)?"
|
| 252 |
+
)
|
| 253 |
+
_AR_ORD = (
|
| 254 |
+
r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*والعشرون|"
|
| 255 |
+
r"(?:الحادية|الثانية|الثالثة|الرابعة|الخامسة|السادسة|السابعة|الثامنة|التاسعة)[\s\u0640]*عشرة|"
|
| 256 |
+
r"العشرون|"
|
| 257 |
+
r"الأولى|الأولي|األولى|الاولى|الثانية|الثالثة|الرابعة|الخامسة|"
|
| 258 |
+
r"السادسة|السابعة|الثامنة|التاسعة|العاشرة"
|
| 259 |
+
)
|
| 260 |
+
_AR_ORD_M = (
|
| 261 |
+
r"الأول|الاول|الثاني|الثالث|الرابع|الخامس|"
|
| 262 |
+
r"السادس|السابع|الثامن|التاسع|العاشر"
|
| 263 |
+
)
|
| 264 |
+
_AR_ART_RE = re.compile(
|
| 265 |
+
r"\(?(?:الماد[ةه]|املاد[ةه]|مادة)\s*[-–]?\s*[()]*\s*(?:[0-9٠-٩۰-۹]+|" + _AR_ORD + r")"
|
| 266 |
+
r"(?:\s*[-–])?(?:\s*[()]*)?(?:\s*مكرر(?:اً|ا)?)?"
|
| 267 |
+
)
|
| 268 |
+
_CITE_TAIL_RE = re.compile(
|
| 269 |
+
_latin_fold(
|
| 270 |
+
r"(?i)\s+(?:"
|
| 271 |
+
r"of\s+(?:this\s+|the\s+)?(?:act|law|agreement|code|constitution|article|section|"
|
| 272 |
+
r"principal\s+act|ordinance|regulation|decree|chapter|part|title|ruling|order)"
|
| 273 |
+
r"|thereof\b"
|
| 274 |
+
r"|hereof\b"
|
| 275 |
+
r"|hereunder\b"
|
| 276 |
+
r"|de\s+la\s+(?:loi|ley|presente|présente)"
|
| 277 |
+
r"|du\s+(?:code|présent|present)"
|
| 278 |
+
r"|des\s+gesetzes"
|
| 279 |
+
r"|van\s+(?:deze\s+)?(?:wet|artikel)"
|
| 280 |
+
r"|i\s+lov\b"
|
| 281 |
+
r"|cua\s+luat(?:\s+nay)?"
|
| 282 |
+
r")\b"
|
| 283 |
+
)
|
| 284 |
+
)
|
| 285 |
+
_NUMERO_FOLD_RE = re.compile(
|
| 286 |
+
r"(?i)(?:№|n\.\s*o\b|n\.?[°º]|nÂ[oº°]|\bno\.?\s+(?=\d))\.?\s*"
|
| 287 |
+
)
|
| 288 |
+
_CJK_RANGE_RE = re.compile(
|
| 289 |
+
r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條]\s*(?:至|到|から)\s*"
|
| 290 |
+
r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[条條](?:まで)?"
|
| 291 |
+
)
|
| 292 |
+
_FA_ORD = (
|
| 293 |
+
r"یازدهم|دوازدهم|سیزدهم|چهاردهم|پانزدهم|شانزدهم|هفدهم|هجدهم|نوزدهم|بیستم|"
|
| 294 |
+
r"اولی?|نخست|دوم|سوم|چهارم|چارم|جارم|پنجم|ششم|هفتم|هشتم|نهم|دهم"
|
| 295 |
+
)
|
| 296 |
+
_FA_ART_RE = re.compile(r"(?:ماده|مادة)\s*(?:[0-9۰-۹]+|" + _FA_ORD + r")")
|
| 297 |
+
_DA_ART_RE = re.compile(r"(?:Artikel|§)\s*[0-9]+", re.IGNORECASE)
|
| 298 |
+
_CHROME_LINE_RE = re.compile(
|
| 299 |
+
r"(?i)^(?:"
|
| 300 |
+
r"početna stranica\b.*|"
|
| 301 |
+
r"upute za korištenje\b.*|"
|
| 302 |
+
r"elektronička pošta\b.*|"
|
| 303 |
+
r"vsebina uradnega lista\b.*|"
|
| 304 |
+
r"the incident id is\b.*|"
|
| 305 |
+
r"ωράριο λειτουργίας\b.*|"
|
| 306 |
+
r"τηλέφωνο επικοινωνίας\b.*|"
|
| 307 |
+
r"skip to (?:main )?content\b.*|"
|
| 308 |
+
r"javascript is (?:required|disabled)\b.*|"
|
| 309 |
+
r"privacy policy\s*$|"
|
| 310 |
+
r"traduction française pour information\s*$|"
|
| 311 |
+
r"pdf\s*$|"
|
| 312 |
+
r"https?://\S+\s*$|"
|
| 313 |
+
r"légimonaco\b.*|"
|
| 314 |
+
r"statutory instruments\s*$|"
|
| 315 |
+
r"official gazette\s*$|"
|
| 316 |
+
r"government gazette\s*$|"
|
| 317 |
+
r"(?:the )?london gazette\s*$|"
|
| 318 |
+
r"journal officiel(?: de la république(?: [^\n]{0,40})?)?\.?\s*$|"
|
| 319 |
+
r"bulletin officiel\s*$|"
|
| 320 |
+
r"gazette du canada\s*$|"
|
| 321 |
+
r"(?:the )?[\w .'-]{0,50}gazette\s*$|"
|
| 322 |
+
r"الوقائع المصرية\s*$|"
|
| 323 |
+
r"الوقائع العراقية\b.*|"
|
| 324 |
+
r"العدد\s*$|"
|
| 325 |
+
r"العدد\s+\S.{0,80}الوقائع\b.*|"
|
| 326 |
+
r".*شعبة الجريدة الرسمية\s*$|"
|
| 327 |
+
r"(?:the )?(?:republic of sudan gazette|gazette published by authority|official gazette of the republic of sudan)\b.*|"
|
| 328 |
+
r"الصفحة(?:\s*[0-9٠-٩]+)?\s*$|"
|
| 329 |
+
r"(?:الجريدة|اجلريدة|جريدة)(?:\s+الر\s*سمية)?(?:\s+العدد(?:\s*\(\s*\)?\s*[0-9٠-٩]+)?)?\s*$|"
|
| 330 |
+
r"république du s[ée]n[ée]gal\s*$|"
|
| 331 |
+
r"jamhuuriyadda\b.*|"
|
| 332 |
+
r"warta kerajaan\s*$|"
|
| 333 |
+
r"lembaran negara\s*$|"
|
| 334 |
+
r"berita negara\s*$|"
|
| 335 |
+
r"công báo\s*$|"
|
| 336 |
+
r"la gaceta\s*$|"
|
| 337 |
+
r"no\.?\s*\d+\s+government gazette\b.*|"
|
| 338 |
+
r"supplement to (?:the |official ).{0,60}gazette\b.*|"
|
| 339 |
+
r"[a-z0-9 ,.'()-]*supplement to official gazette[a-z0-9 ,.'()-]*$|"
|
| 340 |
+
r"printed by\b.*|"
|
| 341 |
+
r"https?://\S+(?:\s+\d+(?:\.\d+)*)?\s*$|"
|
| 342 |
+
r"©+\s*.*congress\b.*|"
|
| 343 |
+
r"(?:s|sm)\s+congress\b.*|"
|
| 344 |
+
r"palikir,\s*pohnpei\b.*|"
|
| 345 |
+
r"www\.\S+(?:\s+\d+)?\s*$|"
|
| 346 |
+
r"at\s+www\.\S+\s*$|"
|
| 347 |
+
r".*research bulletin.*|"
|
| 348 |
+
r"acts supplement\s*$|"
|
| 349 |
+
r"supplement\s+(?:nr\.\s*|no\.?\s*)\d+(?:\s+\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\.?)?\s*$|"
|
| 350 |
+
r"no\.\s+of\s+\d{4}\.?\s*$|"
|
| 351 |
+
r"act no\.\s+of\s+\d{4}\.?\s*$|"
|
| 352 |
+
r"bill for the\s*$|"
|
| 353 |
+
r"(?:the )?republic of [a-z]+(?:\s+[a-z]+)?\s*$|"
|
| 354 |
+
r"federal republic of [a-z]+(?:\s+[a-z]+)?\s*$|"
|
| 355 |
+
r"democratic people's republic of korea\s*$|"
|
| 356 |
+
r".{0,10}republic of palau\s*$|"
|
| 357 |
+
r"saint vincent and the grenadines\s*$|"
|
| 358 |
+
r"\[?\s*član\s+\.\.\.\s*\]?\s*$|"
|
| 359 |
+
r".*аудиони тинглаш.*|"
|
| 360 |
+
r"reprint\s*$|"
|
| 361 |
+
r"reprint authorised by\b.*|"
|
| 362 |
+
r"parliament building\s*$|"
|
| 363 |
+
r"oau drive, tower hill\s*$|"
|
| 364 |
+
r"office of the clerk of parliament\s*$|"
|
| 365 |
+
r"(?:(?:first|second|third|fourth|fifth)\s+parliament(?:\s+of\s+the\s+(?:first|second|third|fourth|fifth)\s+republic)?\s*){1,2}$|"
|
| 366 |
+
r"(?:(?:first|second|third|fourth|fifth)\s+meeting of parliament\s*){1,2}$|"
|
| 367 |
+
r"تفاصيل\s+(?:النظام|اللائحة)\s*$|"
|
| 368 |
+
r"مجموعة الأنظمة السعودية\s*$|"
|
| 369 |
+
r"المجلد\s+\S+\s*$|"
|
| 370 |
+
r"أنظمة\s+\S.{0,60}$|"
|
| 371 |
+
r"(?:first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth)\s+folder\s*$|"
|
| 372 |
+
r"this law includes:\s*$|"
|
| 373 |
+
r"-\s*اختر\s*-\s*$|"
|
| 374 |
+
r"تاريخ الإصدار\s*$|"
|
| 375 |
+
r"تاريخ النشر\s*$|"
|
| 376 |
+
r"الحالة\s*$|"
|
| 377 |
+
r"ساري\s*$|"
|
| 378 |
+
r"العربية\s*$|"
|
| 379 |
+
r"الإسم\s*$|"
|
| 380 |
+
r"البريد الإلكتروني\s*$|"
|
| 381 |
+
r"رقم الجوال\s*$|"
|
| 382 |
+
r"نوع البلاغ\s*$|"
|
| 383 |
+
r"\d{4}/\d{2}/\d{2}\s+ه\s+الموافق\s*:?\s*\d{2}/\d{2}/\d{4}\s+م\s*$|"
|
| 384 |
+
r"\d{3,4}\s+ه\s*$|"
|
| 385 |
+
r"خطأ لغوي\s*$|"
|
| 386 |
+
r"خطأ في مادة\s*$|"
|
| 387 |
+
r"يتضمن (?:النظام|التنظيم) ما يلي\s*:?\s*$|"
|
| 388 |
+
r"عدد مرات التصفح\s*\d*\s*$|"
|
| 389 |
+
r"نبذة عن النظام\s*$|"
|
| 390 |
+
r"اسم النظام/اللائحة\b.*|"
|
| 391 |
+
r"تاريخ (?:إصدار|نشر) النظام/اللائحة\s*$|"
|
| 392 |
+
r"حالة النظام/اللائحة\b.*|"
|
| 393 |
+
r"أدوات إصدار النظام\s*$|"
|
| 394 |
+
r"نص النظام\s*$|"
|
| 395 |
+
r"مادة معدلة\s*$|"
|
| 396 |
+
r"مادة ملغية\s*$|"
|
| 397 |
+
r"اصل الوثيقة\s*$|"
|
| 398 |
+
r"طباعة\s*$|"
|
| 399 |
+
r"إبلاغ\s*$|"
|
| 400 |
+
r"الإصدارات\s*$|"
|
| 401 |
+
r"اللغات\s*$|"
|
| 402 |
+
r"الإنجليزية\s*\(English\)\s*$|"
|
| 403 |
+
r"(?:\d{4}\s+)?revised edition(?:\s+as at\b.*|\s+page\s+\d+)?\s*$|"
|
| 404 |
+
r"page\s+\d+\s+\d{4}\s+revised edition\s*$|"
|
| 405 |
+
r"\[note: this version\b.*|"
|
| 406 |
+
r"\[this is the version of this document\b.*|"
|
| 407 |
+
r"el peruano\s*$|"
|
| 408 |
+
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*$|"
|
| 409 |
+
r"[a-z]\s+page\s*\d+\s*$|"
|
| 410 |
+
r"(?:section\s+)?pages?\s*$|"
|
| 411 |
+
r"seite\s+\d+(?:\s+(?:von|of|bis)\s+\d+)?\s*$|"
|
| 412 |
+
r"bundesrecht konsolidiert\b.*|"
|
| 413 |
+
r".*ris\.bka\.gv\.at.*$|"
|
| 414 |
+
r"\{\\rtf\d+\b.*|"
|
| 415 |
+
r"p[aá]gina\s+\d+\s*$|"
|
| 416 |
+
r"pagina\s+\d+\s*$|"
|
| 417 |
+
r"strona\s+\d+\s*$|"
|
| 418 |
+
r"p\.\s*\d+(?:\s+(?:of|di|von|sur|de)\s+\d+)?\s*$|"
|
| 419 |
+
r"pag\.\s*\d+(?:\s+(?:di|of|de)\s+\d+)?\s*$|"
|
| 420 |
+
r"blz\.\s*\d+\s*$|"
|
| 421 |
+
r"folio\s+\d+\s*$|"
|
| 422 |
+
r"foglio\s+\d+\s*$|"
|
| 423 |
+
r"лист\s+\d+\s*$|"
|
| 424 |
+
r"стр\.\s*\d+\s*$|"
|
| 425 |
+
r"ص\s*\.?\s*\d+\s*$|"
|
| 426 |
+
r"עמוד\s+\d+\s*$|"
|
| 427 |
+
r"trang\s+\d+\s*$|"
|
| 428 |
+
r"halaman\s+\d+\s*$|"
|
| 429 |
+
r"sayfa\s+\d+\s*$|"
|
| 430 |
+
r"oldal\s+\d+\s*$|"
|
| 431 |
+
r"stran(?:ica)?\s+\d+\s*$|"
|
| 432 |
+
r"www\.\S+\s*$|"
|
| 433 |
+
r"downloaded from\b.*|"
|
| 434 |
+
r"printed on\s+\d.*|"
|
| 435 |
+
r"generated by\b.*|"
|
| 436 |
+
r"e-?mail:\s*\S+@\S+\s*$|"
|
| 437 |
+
r"tel(?:ephone)?:\s*[+\d].*$|"
|
| 438 |
+
r"for more information visit\b.*|"
|
| 439 |
+
r"[-–—]\s*\d{1,4}\s*[-–—]\s*$|"
|
| 440 |
+
r"table of contents\s*$|"
|
| 441 |
+
r"table des mati[eè]res\s*$|"
|
| 442 |
+
r"inhaltsverzeichnis\s*$|"
|
| 443 |
+
r"(?:índice|indice)\s*$|"
|
| 444 |
+
r"sommaire\s*$|"
|
| 445 |
+
r".*\barrangement of (?:sections|provisions|regulations|rules)\.?(?:\s+cap\.\s*[\d.]+.*)?\s*$|"
|
| 446 |
+
r"contents\s*$|"
|
| 447 |
+
r"section\s*$|"
|
| 448 |
+
r"[\s.\-;,*/_×|+~•·{}()\\=»«®∞]+$|"
|
| 449 |
+
r"(?=.*[+|])[+\-|]{3,}\s*$|"
|
| 450 |
+
r"\[original service \d{4}\].*|"
|
| 451 |
+
r"statute law of the [a-z ]+$|"
|
| 452 |
+
r"[A-Z][A-Z .'\-]{0,40}\[ch\.\s*\d+.*|"
|
| 453 |
+
r"التاريخ:\s*$|"
|
| 454 |
+
r"republic of the marshall islands\s*$|"
|
| 455 |
+
r"jepilpilin ke ejukaan\s*$|"
|
| 456 |
+
r"zastupni[cč]ki dom hrvatskoga sabora\s*$|"
|
| 457 |
+
r"dr[zž]avni zavod za normizaciju i mjeriteljstvo\s*$|"
|
| 458 |
+
r"олдинги таҳрирга қаранг\.?\s*$|"
|
| 459 |
+
r"explanatory note\s*$|"
|
| 460 |
+
r"\.\s*\(\s*\d+\s*\)\s*$|"
|
| 461 |
+
r"(?:يناير|فبراير|مارس|أبريل|ابريل|مايو|يونيو|يوليو|أغسطس|اغسطس|سبتمبر|أكتوبر|اكتوبر|نوفمبر|ديسمبر)\s+\d{4}\s*$|"
|
| 462 |
+
r"laws of (?:the )?[a-z]+(?:\s+(?:&|[a-z]+)){0,4}\s*$|"
|
| 463 |
+
r"(?-i:LAWS OF (?:THE )?[A-Z]+(?:\s+[A-Z]+){0,6}\s+s\s*\d+\s*$)|"
|
| 464 |
+
r"(?:í|i)ndice legislativo\s*$|"
|
| 465 |
+
r"قائمة (?:المحتويات|احملتويات)\s*$|"
|
| 466 |
+
r"spis tre[sś]ci\s*$|"
|
| 467 |
+
r"содержание\s*$|"
|
| 468 |
+
r"πίνακας περιεχομένων\s*$|"
|
| 469 |
+
r"목차\s*$|"
|
| 470 |
+
r"目次\s*$|"
|
| 471 |
+
r"สารบัญ\s*$|"
|
| 472 |
+
r"[aα]ριθμός\s+\d+[^\n]{0,24}\s*$|"
|
| 473 |
+
r"[aα]ρ\.\s*\d+(?:/\d+)?[^\n]{0,12}\s*$|"
|
| 474 |
+
r"številka\s+\d+[^\n]{0,24}\s*$|"
|
| 475 |
+
r"(?:nr|no|n[uú]m(?:ero|éro|ber)?|broj|č[ií]slo|szám|sayı|номер)\.?\s*\d{2,}(?:/\d+)?[.\s]*$|"
|
| 476 |
+
r"№\s*\d+\s*$|"
|
| 477 |
+
r"copyright\s*©?\s*\d{4}.*$|"
|
| 478 |
+
r"©\s*\d{4}.*$|"
|
| 479 |
+
r"\d{1,2}[./-]\d{1,2}[./-]\d{2,4}\s*$|"
|
| 480 |
+
r"\d{4}-\d{2}-\d{2}\s*$|"
|
| 481 |
+
r"\d{1,2}\s+(?:january|february|march|april|may|june|july|august|september|october|november|december|"
|
| 482 |
+
r"janvier|f[eé]vrier|mars|avril|mai|juin|juillet|ao[uû]t|septembre|octobre|novembre|d[eé]cembre|"
|
| 483 |
+
r"enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)\s+\d{4}\s*$|"
|
| 484 |
+
r"end of (?:the )?document\s*$|"
|
| 485 |
+
r"fin du document\s*$|"
|
| 486 |
+
r"ende des dokuments?\s*$|"
|
| 487 |
+
r"fin del documento\s*$|"
|
| 488 |
+
r"fim do documento\s*$|"
|
| 489 |
+
r"[-*=._]{3,}\s*$|"
|
| 490 |
+
r"published\s*$|"
|
| 491 |
+
r"publi[eé]\s*$|"
|
| 492 |
+
r"publicado\s*$|"
|
| 493 |
+
r"veröffentlicht\s*$|"
|
| 494 |
+
r"\[?seal\]?\s*$|"
|
| 495 |
+
r"\(seal\)\s*$|"
|
| 496 |
+
r"l\.s\.?\s*$|"
|
| 497 |
+
r"god save the (?:king|queen)\s*$|"
|
| 498 |
+
r"vive la r[eé]publique\s*$|"
|
| 499 |
+
r"by (?:order|command)\s*$|"
|
| 500 |
+
r"signed\s*$|"
|
| 501 |
+
r"diario oficial(?: de la federación)?\s*$|"
|
| 502 |
+
r"gazzetta ufficiale(?: della repubblica(?: italiana)?)?\s*$|"
|
| 503 |
+
r"boletín oficial(?: del estado)?\s*$|"
|
| 504 |
+
r"diário da república\s*$|"
|
| 505 |
+
r"bundesgesetzblatt\s*$|"
|
| 506 |
+
r"moniteur belge\s*$|"
|
| 507 |
+
r"belgisch staatsblad\s*$|"
|
| 508 |
+
r"staatsblad\s*$|"
|
| 509 |
+
r"lovtidende\s*$|"
|
| 510 |
+
r"svensk författningssamling\s*$|"
|
| 511 |
+
r"uradni list\s*$|"
|
| 512 |
+
r"dziennik ustaw\s*$|"
|
| 513 |
+
r"monitorul oficial\s*$|"
|
| 514 |
+
r"εφημερίδα της κυβερνήσεως\s*$|"
|
| 515 |
+
r"resmi gazete\s*$|"
|
| 516 |
+
r"iris oifigiúil\s*$|"
|
| 517 |
+
r"latvijas vēstnesis\s*$|"
|
| 518 |
+
r"valstybės žinios\s*$|"
|
| 519 |
+
r"官報\s*$|"
|
| 520 |
+
r"国务院公报\s*$|"
|
| 521 |
+
r"관보\s*$|"
|
| 522 |
+
r"ราชกิจจานุเบกษา\s*$|"
|
| 523 |
+
r"(?:เล่ม|เลม)\s*[๐-๙0-9].*ราชกิจจานุเบกษา.*|"
|
| 524 |
+
r"اطلاق نسخة جديدة من الميزان\s*$|"
|
| 525 |
+
r"\[\d+/\d{4}(?:\s+wef\s+[\d/]+)?\]\s*$|"
|
| 526 |
+
r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+\s+\d{4}\]\s+.+\s+\d{1,4}\s*$|"
|
| 527 |
+
r"\[\d{1,2}(?:st|nd|rd|th)\s+[a-z]+,?\s+\d{4}\]\s*$|"
|
| 528 |
+
r"(?:18|19|20)\d{2}\s*$|"
|
| 529 |
+
r"gazette\.?\s*$|"
|
| 530 |
+
r"cap\.\s*\d+(?:\.\d+)*\s*$|"
|
| 531 |
+
r".+\scap\.?\s*[\d.]+\s+section\s+\d+\s*$|"
|
| 532 |
+
r"diario oficial\s*$|"
|
| 533 |
+
r"diário oficial(?: da união)?\s*$|"
|
| 534 |
+
r"gaceta oficial(?: de la república)?\s*$|"
|
| 535 |
+
r"registro oficial\s*$|"
|
| 536 |
+
r"sbírka zákonů\s*$|"
|
| 537 |
+
r"zbierka z[^\n]{0,40}\s*$|"
|
| 538 |
+
r"magyar közlöny\s*$|"
|
| 539 |
+
r"narodne novine\s*$|"
|
| 540 |
+
r"službeni glasnik\s*$|"
|
| 541 |
+
r"службени гласник\s*$|"
|
| 542 |
+
r"държавен вестник\s*$|"
|
| 543 |
+
r"monitorul oficial(?: al româniei)?\s*$|"
|
| 544 |
+
r"norsk lovtidend\s*$|"
|
| 545 |
+
r"suomen säädöskokoelma\s*$|"
|
| 546 |
+
r"finlands författningssamling\s*$|"
|
| 547 |
+
r"riigi teataja\s*$|"
|
| 548 |
+
r"российская газета\s*$|"
|
| 549 |
+
r"(?:the )?kenya gazette\s*$|"
|
| 550 |
+
r"federal negar[ie]t gazett?e\s*$|"
|
| 551 |
+
r"gazette officielle\s*$|"
|
| 552 |
+
r"amtsblatt(?: der europäischen union)?\s*$|"
|
| 553 |
+
r"official journal of the european union\s*$|"
|
| 554 |
+
r"journal officiel de l'union européenne\s*$|"
|
| 555 |
+
r"gazzetta ufficiale dell'unione europea\s*$|"
|
| 556 |
+
r"الجريدة الرسمية\b.*|"
|
| 557 |
+
r"ваш броузер застарів\b.*|"
|
| 558 |
+
r"your browser is (?:out of date|outdated|obsolete)\b.*|"
|
| 559 |
+
r"all rights reserved\b.*|"
|
| 560 |
+
r"subscribe to\s+(?:our\s+)?(?:newsletter|mailing(?:\s+list)?|updates|feed)\b.*|"
|
| 561 |
+
r"(?:we use|this (?:site|website) uses)\s+cookies\b.*|"
|
| 562 |
+
r".{0,80}використовуємо cookies\b.*|"
|
| 563 |
+
r".{0,80}використання cookies\b.*|"
|
| 564 |
+
r"продовжуючи відвідування сайту\b.*|"
|
| 565 |
+
r"al meezan\b.*|"
|
| 566 |
+
r"الميزان\b.*|"
|
| 567 |
+
r".{0,40}وزارة العدل(?: و الشؤون القانونية)?\s*$|"
|
| 568 |
+
r"التشريعات\b.*|"
|
| 569 |
+
r"page not found\b.*|"
|
| 570 |
+
r"(?:error\s+)?404(?:\s+not found)?\b.*|"
|
| 571 |
+
r"access denied\s*$|"
|
| 572 |
+
r"forbidden\s*$|"
|
| 573 |
+
r"public notification\s*$|"
|
| 574 |
+
r"[^\n]{0,40}@mjla\b.*|"
|
| 575 |
+
r".{0,40}gaceta oficial(?: digital)?\b.*|"
|
| 576 |
+
r"paragraph\s*$|"
|
| 577 |
+
r"[^\n]{0,60}slov-lex\s*$|"
|
| 578 |
+
r"(?:crown\s+)?copyright\s*(?:©\s*)?\d{4}\.?\s*$|"
|
| 579 |
+
r"copying\s*/\s*unauthori[sz]ed distribution strictly prohibited\.?\s*$|"
|
| 580 |
+
r"(?:revision|consolidation) date\s*:.*|"
|
| 581 |
+
r"showing the law as at\s+\d.*|"
|
| 582 |
+
r"this is a revised edition of the law\b.*|"
|
| 583 |
+
r"printed under authority by\s*$|"
|
| 584 |
+
r"(?:the )?regional law revision centre\b.*|"
|
| 585 |
+
r"continued on next page\b.*|"
|
| 586 |
+
r"back to (?:page one|the top|top)\s*$|"
|
| 587 |
+
r"page\s*:\s*\d+\s+date\s*:.*|"
|
| 588 |
+
r"bwpageid\s*::.*|"
|
| 589 |
+
r"bwservice\s*::.*|"
|
| 590 |
+
r".*ron_book\b.*|"
|
| 591 |
+
r"\d+\s+service\s+\d+\s*$|"
|
| 592 |
+
r"(?:pdf|word|audio)\s+download\s*$|"
|
| 593 |
+
r"login with (?:facebook|google|apple|twitter|email)\b.*|"
|
| 594 |
+
r"(?:view|print|e-?mail)\s*$|"
|
| 595 |
+
r"last updated(?:\s+on)?\s+\d.*|"
|
| 596 |
+
r"speakers office\s*$|"
|
| 597 |
+
r"fsm congress\s*$|"
|
| 598 |
+
r".*almeezan\b.*|"
|
| 599 |
+
r"add new section\s*$|"
|
| 600 |
+
r"section name\s*$|"
|
| 601 |
+
r".*hijripage\b.*|"
|
| 602 |
+
r"search in articles\s*$|"
|
| 603 |
+
r"privacy statement\s*$|"
|
| 604 |
+
r"terms of use\s*$|"
|
| 605 |
+
r"rate this website\s*$|"
|
| 606 |
+
r"feedback via reach\s*$|"
|
| 607 |
+
r"singapore statutes online\b.*|"
|
| 608 |
+
r".*reprint is authorised by\b.*|"
|
| 609 |
+
r"công báo\s*/\s*số\b.*|"
|
| 610 |
+
r"thời gian ký\s*:.*|"
|
| 611 |
+
r"lex\.?uz\b.*|"
|
| 612 |
+
r"\[?(?:окоз|тсз|спит)\s*:.*|"
|
| 613 |
+
r"\d+(?:\.\d{2}){3,}.*[\u0400-\u04FF].*|"
|
| 614 |
+
r"issue\s*:\s*\d+\s*,\s*amendment\s*:\s*\d+\b.*|"
|
| 615 |
+
r"presidential comm\.?\s*no\b.*|"
|
| 616 |
+
r"(?:january|february|march|april|may|june|july|august|september|october|november|december)\s+\d{1,2},?\s+\d{4}(?:\s+[a-z])?\s*$|"
|
| 617 |
+
r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\.\d+\b(?!.*\b(?!etc\b)[a-z]{3,}\b).*$)|"
|
| 618 |
+
r"(?-i:(?!.*\b(?!etc\b)[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\.\d+(?:\.\d+)*\s+\d{1,4}\s*$)|"
|
| 619 |
+
r"(?-i:\d{1,4}\s+[Cc][Aa][Pp]\.\s*\d+\s+(?!.*\b[a-z]{3,}\b).+$)|"
|
| 620 |
+
r"(?-i:(?!.*\b[a-z]{3,}\b).{0,90}\b[Cc][Aa][Pp]\.\s*\d+\s+\d{1,4}\s*$)|"
|
| 621 |
+
r"(?-i:\d{1,4}\s+[Cc]hap\.\s*\d+(?::\d+)?\b(?!.*\b[a-z]{3,}\b).*$)|"
|
| 622 |
+
r"(?-i:\d{1,4}\s+(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s*$)|"
|
| 623 |
+
r"(?-i:(?:[A-Z][A-Za-z]+(?:\s+|$)){3,12}(?:19|20)\d{2}\s+\d{1,4}\s*$)|"
|
| 624 |
+
r"constituci[oó]n pol[ií]tica del per[uú]\s+\d+\s*$|"
|
| 625 |
+
r"\d{1,4}\s+edici[oó]n del congreso\b.*|"
|
| 626 |
+
r"nr\.\s*\d+\s*\].*\[.*|"
|
| 627 |
+
r"st\.?\s*christopher and nevis\s*$|"
|
| 628 |
+
r"official gazette\s+nr\.\s*\d[\d\s/.-]*(?:\s+of\s+[\d/.-]+)?\s*$|"
|
| 629 |
+
r"www\.\S+(?:\s+(?!(?:for|under|and|the|is|of)\b)[A-Za-z][\w.-]{1,24}){1,2}\s*$|"
|
| 630 |
+
r".*laws\.africa\b.*|"
|
| 631 |
+
r".*share widely and freely.*|"
|
| 632 |
+
r".*no copyright on the legislative content.*|"
|
| 633 |
+
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*$)|"
|
| 634 |
+
r"(?-i:^Act\s+\d+\s+(?:[A-Z][a-z]+\s+){1,6}(?:19|20)\d{2}\s*$)|"
|
| 635 |
+
r"issue\s*:?\s*\d+(?:\.\d+)?\s+page\s+\d+\s+of\s+\d+\b.*|"
|
| 636 |
+
r"issue\s*:\s*\d+(?:\.\d+)?\s+\d+\s+\d{1,2}\s+[a-z]+\s+\d{4}\s*$|"
|
| 637 |
+
r".*edition officielle mise [aà] jour.*|"
|
| 638 |
+
r"code general des impots\s+\d{4}\s*$|"
|
| 639 |
+
r"\d{1,2}\.\d{1,2}\.\d{4}\s*-\s*\d{1,2}\.\d{1,2}\.\d{4}\s*$|"
|
| 640 |
+
r"(?!.*δημοσιευ)(?!.*\bστην\b)(?=.*εφημερ.{0,12}κυβερν)(?=.*(?:τευξ|τεύχ|\(\s*τευ)).{0,140}$|"
|
| 641 |
+
r"(?:\d{1,4}\s+)?επ[ιί]σημη\s+εφημερ[ιί]δ[αά]\b.*|"
|
| 642 |
+
r"sistema integrado de gest[aã]o de finan[cç]as p[uú]blicas\s*\(sigfip\)\s*\d+\s*/\s*\d+\s*$|"
|
| 643 |
+
r"editado por\s*:.*\beditado em\s*:.*|"
|
| 644 |
+
r"issue\s+\d{1,4}\s*$|"
|
| 645 |
+
r"\d{1,4}\s*\|\s*page\s*$|"
|
| 646 |
+
r"page\s*\|\s*\d{1,4}\s*$|"
|
| 647 |
+
r"\{\{[^}\n]*\}\}\s*$|"
|
| 648 |
+
r"lap tetej[eé]re\s*$|"
|
| 649 |
+
r"megnyitottak\s*$|"
|
| 650 |
+
r"jogszab[aá]lykeres[oő]\s*$|"
|
| 651 |
+
r".*slu[zž]beni glasnik\b.{0,50}stranica\s+\d+\s*$|"
|
| 652 |
+
r".*\(unknown\)/ron\b.*|"
|
| 653 |
+
r"\[the next page is\s+[\d,]+\s*\]\s*$|"
|
| 654 |
+
r"service\s+\d+\s+[\d,]+\s*$|"
|
| 655 |
+
r"\[act\s+\d+\s+of\s+\d{4}\s+wef\s+[\d/]+\]\s*$|"
|
| 656 |
+
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*$|"
|
| 657 |
+
r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})\s*-?\s*s[eé]rie\b.*\d.*|"
|
| 658 |
+
r"(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3})s[eé]rie\b.*\d.*|"
|
| 659 |
+
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*$|"
|
| 660 |
+
r"s[eé]rie\s+[ivx]+\s*,\s*nr\.\s*\d+\b.{0,80}p[aá]gina\s+\d+\s*$|"
|
| 661 |
+
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*$|"
|
| 662 |
+
r"\d+\s*[\(\)]+\s*مذكرة تفسيرية\b.*|"
|
| 663 |
+
r"-\s*\d+\s*-\s*\).*$|"
|
| 664 |
+
r".*constituteproject\.org.*|"
|
| 665 |
+
r"pdf generated\s*:.*|"
|
| 666 |
+
r"[a-z][a-z]+(?:\s+[a-z][a-z]+){0,3}\s+(?:19|20)\d{2}\s+page\s+\d+\s*$|"
|
| 667 |
+
r"الصفحة\s*\.?\s*[0-9٠-٩]+\s*$|"
|
| 668 |
+
r"\[state/territory\]\s*$|"
|
| 669 |
+
r"direction g[eé]n[eé]rale adjointe des imp[oô]ts\s*$|"
|
| 670 |
+
r"et des domaines\s*$|"
|
| 671 |
+
r"rio:\s*\d+\s*$|"
|
| 672 |
+
r"#+\s*journal officiel\b.*|"
|
| 673 |
+
r"journal officiel\s*-\s*banque des?\s*donn[eé]es juridiques\b.*|"
|
| 674 |
+
r"(?!.*\b(?:publie|publi[eé]|shall|entre)\b)journal officiel (?:de la r[eé]publique|du faso)\b.{0,50}$|"
|
| 675 |
+
r"\[(?:\.{3}|…)\]\s*$|"
|
| 676 |
+
r"bsd:\s*\d+\s*$|"
|
| 677 |
+
r"\d{1,2}\.?\s+(?:gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre)\s*$|"
|
| 678 |
+
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*$)|"
|
| 679 |
+
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*$)|"
|
| 680 |
+
r"printed on the orders? of government\s*\.?\s*$|"
|
| 681 |
+
r".*(?<![A-Za-z])(?:printed|thinted)\b.{0,80}government printing\b.*|"
|
| 682 |
+
r"to be purchased at the govt\.?\s*publications bureau\b.*|"
|
| 683 |
+
r"b\.?\s*l\.?\s*r\.?\s*o\.?\s*\d+\s*/\s*\d{4}\s*$|"
|
| 684 |
+
r"pages authorised\s*$|"
|
| 685 |
+
r"(?:current\s+)?authorised pages\s*$|"
|
| 686 |
+
r"\(inclusive\)\s*by\s+lro\.?\s*$|"
|
| 687 |
+
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*$)|"
|
| 688 |
+
r"code\s+\S+(?:\s+\S+){0,6}\s+\d{1,3}/\d{2,3}\s*$|"
|
| 689 |
+
r"index\s*$|"
|
| 690 |
+
r"ministry/program(?:me)?/sub(?:head|program(?:me)?)\s+page\s*$|"
|
| 691 |
+
r"page\s+\d{1,3}\s*/\s*\d{1,3}\s*$|"
|
| 692 |
+
r"\[?\s*printed by authority of the\s*$|"
|
| 693 |
+
r"printed in [a-z][a-z .'-]{0,40}by the government printer\s*$|"
|
| 694 |
+
r"[\w.+-]+@[\w.-]+\.[a-z]{2,}\s+www\.\S+\s*$|"
|
| 695 |
+
r"secr[eé]tariat g[eé]n[eé]ral du gouvernement\s+www\.\S+\s*$|"
|
| 696 |
+
r"site:\s*(?:https?://|www\.)\S+\s*$|"
|
| 697 |
+
r"justice sector support program\s*\(jssp\).*|"
|
| 698 |
+
r"serial number:\s*\d+\b.*|"
|
| 699 |
+
r"copyright government of [a-z]+(?:\s+[a-z]+){0,3}\s*$|"
|
| 700 |
+
r"this page was intentionally left blank\.?\s*$|"
|
| 701 |
+
r"this is page \d+ of \d+\s+pages? of the above table\.?\s*$|"
|
| 702 |
+
r"new provisions(?: in the schedule)? are printed in italics\.?\s*$|"
|
| 703 |
+
r"go to top page(?: next chapter)?\s*$|"
|
| 704 |
+
r"(?:\d{4}\s+)?parliamentary series\s+(?:nr\.|no\.?)\s*\d+\s*$|"
|
| 705 |
+
r"try reloading the page or downloading the pdf\.?\s*$|"
|
| 706 |
+
r"reload page\s*$|"
|
| 707 |
+
r"uploaded by:\s*https?://\S+\s*$|"
|
| 708 |
+
r"t[eé]l[eé]charg[eé] sur www\.\S+\s*$|"
|
| 709 |
+
r"ibirimo/summary/sommaire\b.*|"
|
| 710 |
+
r"website:\s*(?:https?://|www\.)\S+\s*$|"
|
| 711 |
+
r"www\.\S+\s+[\w.+-]+@[\w.-]+\s*$|"
|
| 712 |
+
r"gazette order page\.?\s*$|"
|
| 713 |
+
r"(?:lexis finder|esilec profesional)\s*-\s*www\.\S+\s*$|"
|
| 714 |
+
r"official gazette\s+(?:nr\.|no\.?)\s*(?:special(?:\s+bis)?|\d+\s*bis)\s+of\b.*|"
|
| 715 |
+
r"s[eé]rie\s+[ivxlcdm]+\s*,\s*nr\.\s*\S+(?:\s+[A-Za-z0-9]+)?\s*$|"
|
| 716 |
+
r"unofficial translat(?:ed|ion)\b.*|"
|
| 717 |
+
r"\(?\d[\d\s().-]{6,}\)?\s*\|\s*(?:https?://|www\.)\S+\s*$|"
|
| 718 |
+
r"volume:\s*\d+\s+issue no:\s*\d+\s+government gazette\s*$|"
|
| 719 |
+
r"tonga government gazette supplement\s*$|"
|
| 720 |
+
r"ministry of legal affairs\s+www\.\S+\s*$|"
|
| 721 |
+
r"\d+\s+www\.\S+\s*$|"
|
| 722 |
+
r"www\.\S+\s+\d+\s*/\s*\d+\s*$|"
|
| 723 |
+
r"www\.\S+\s+(?:(?!for\b|is\b|shall\b|the\b)[a-z][a-z .'-]{0,50})$|"
|
| 724 |
+
r".*/type/page>{2,}.*|"
|
| 725 |
+
r"subject\.\s*reference\.\s*page\.?\s*$|"
|
| 726 |
+
r"name reference page no\.?\s*$|"
|
| 727 |
+
r"sl\s*#\s*law\s*#\s*legislation commencement gazette\s*$|"
|
| 728 |
+
r"gn\s*=\s*gazette notice\b.*|"
|
| 729 |
+
r"de blank page\b.*|"
|
| 730 |
+
r"printed and published by the ministry of justice\b.*|"
|
| 731 |
+
r"rarotonga,\s*cook islands:\s*printed under the authority\b.*|"
|
| 732 |
+
r"e-?mail\s*:\s*\S+@\S+.*(?:site web|www\.)\S+.*|"
|
| 733 |
+
r"διεύθυνση στο διαδίκτυο\s*\(url\)\s*:\s*https?://\S+.*|"
|
| 734 |
+
r"spletna stran:\s*www\.\S+\s*$|"
|
| 735 |
+
r"copyright\s*$|"
|
| 736 |
+
r"copyright and designs act\s+\d{4}\s*$|"
|
| 737 |
+
r"copyright act\s+\d{4}\s*$|"
|
| 738 |
+
r"powered by tcpdf\b.*|"
|
| 739 |
+
r"pour l'acquisition de votre abonnement\b.*|"
|
| 740 |
+
r"a\s*bonnement au journal officiel\b.*|"
|
| 741 |
+
r"[eé]dit[eé] par la direction de l'[eé]dition du journal officiel\b.*|"
|
| 742 |
+
r"\[the inclusion of this page is authori[sz]ed by\b.*|"
|
| 743 |
+
r"ins\s*=\s*inserted\b.*|"
|
| 744 |
+
r"[a-z]{2,8}\s*=\s*gazette\b.*|"
|
| 745 |
+
r"site web\s*:\s*www\.\S+\s*$|"
|
| 746 |
+
r"web\s*sites?\s*:?\s*-?\s*www\.\S+\s*$|"
|
| 747 |
+
r".*www\.documents\.gov\.lk\s*$|"
|
| 748 |
+
r"τηλ\.?:?\s*[\d\s,]+φαξ:?\s*[\d\s]+\s*-\s*www\.\S+\s*$|"
|
| 749 |
+
r"das dokument ist einsehbar unter:\s*www\.\S+\s*$|"
|
| 750 |
+
r"sujet articles page\s*$|"
|
| 751 |
+
r"language is printed on uneven numbered pages\.?\s*$|"
|
| 752 |
+
r".*www\.nbs\.sk\.?\s*$|"
|
| 753 |
+
r"\d{2}-\d{4,6}\s+\d{1,3}/\d{1,3}\s*$|"
|
| 754 |
+
r"\d{1,3}/\d{1,3}\s+\d{2}-\d{4,6}\s*$|"
|
| 755 |
+
r"[as]/(?:res|prst)/\d+\s*\(\d{4}\)\s*$|"
|
| 756 |
+
r"ab\s+\d{4},\s*nr\.\s*\d+\s*$|"
|
| 757 |
+
r"grondslag\s*:\s*[.\-–\s]*$|"
|
| 758 |
+
r"رقم الهاتف\s*:.*|"
|
| 759 |
+
r"\+[\u0600-\u06FF]{1,2}\s*$|"
|
| 760 |
+
r"(?-i:(?!.*\b(?:est|sont|doit|shall)\b)(?!.*\b[a-z]{4,}\b).*\bImprimerie\s+[A-Z].*$)|"
|
| 761 |
+
r"(?-i:(?!.*\b(?:shall|is|are|means|under|must)\b).{8,120}\(Chapter\s+\d+(?::\d+)?\)\s+[A-Z][a-z]+\s*$)|"
|
| 762 |
+
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*$)|"
|
| 763 |
+
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*$)|"
|
| 764 |
+
r"\[\d{1,4}\]?\s*$|"
|
| 765 |
+
r"หน.?า\s+[0-9๐-๙]+\s*$|"
|
| 766 |
+
r"(?:home|blog|contact us|cookie|accueil|startseite|"
|
| 767 |
+
r"página inicial|página principal|επικοινωνία|αρχική)\s*$"
|
| 768 |
+
r")"
|
| 769 |
+
)
|
| 770 |
+
_CHROME_INLINE_RE = re.compile(
|
| 771 |
+
r"(?i)skip to (?:main )?content|all rights reserved|click here|"
|
| 772 |
+
r"légimonaco"
|
| 773 |
+
)
|
| 774 |
+
_JA_ART_RE = re.compile(r"第\s*[0-9一二三四五六七八九十百]+\s*[条條]")
|
| 775 |
+
_CIRCLED_ART_RE = re.compile(r"[①-⑳⑴-⒇❶-❿⓫-⓴]")
|
| 776 |
+
_CJK_ENUM_RE = re.compile(r"(?m)^[ \t]*[一二三四五六七八九十百]+、")
|
| 777 |
+
_CJK_PAREN_RE = re.compile(r"(?m)^[ \t]*[((][一二三四五六七八九十百]+[))]")
|
| 778 |
+
_CJK_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[0-90-9]+、")
|
| 779 |
+
_KO_GA_RE = re.compile(r"(?m)^[ \t]*[가나다라마바사아자차카타파하]\.")
|
| 780 |
+
_JA_KATA_ENUM_RE = re.compile(r"(?m)^[ \t]*[アイウエオカキクケコ]、")
|
| 781 |
+
_HANGUL_GA = "가나다라마바사아자차카타파하"
|
| 782 |
+
_KATA_ENUM = "アイウエオカキクケコ"
|
| 783 |
+
_AR_ABJAD_INDEX = {
|
| 784 |
+
"أ": "1", "ا": "1", "ب": "2", "ج": "3", "د": "4", "ه": "5",
|
| 785 |
+
"و": "6", "ز": "7", "ح": "8", "ط": "9", "ي": "10",
|
| 786 |
+
}
|
| 787 |
+
_HE_ALEF = "אבגדהוזחטי"
|
| 788 |
+
_TH_KO = "กขคงจฉชซฌญ"
|
| 789 |
+
_AR_ABJAD_RE = re.compile(r"(?m)^[ \t]*[(\[]?[أابجدهوزحطي][)\]]?\s*[-.)]")
|
| 790 |
+
_HE_ALEF_RE = re.compile(r"(?m)^[ \t]*[אבגדהוזחטי]\.")
|
| 791 |
+
_HE_PEREK_RE = re.compile(r"(?m)^[ \t]*פרק\s+[א-ת]{1,3}['׳]?")
|
| 792 |
+
_HE_SIMAN_RE = re.compile(r"(?m)^[ \t]*סימן\s+[א-ת]{1,3}['׳]?")
|
| 793 |
+
_HE_HELEK_RE = re.compile(r"(?m)^[ \t]*חלק\s+[א-ת]{1,3}['׳]?")
|
| 794 |
+
_HE_TOS_RE = re.compile(
|
| 795 |
+
r"(?m)^[ \t]*תוספת\s+(?:ראשונה|שנייה|שניה|שלישית|רביעית|חמישית|שישית|[א-ת]['׳]?|[0-9]+)"
|
| 796 |
+
)
|
| 797 |
+
_HE_TAKANA_RE = re.compile(r"(?m)^[ \t]*תקנה\s+[0-9]+")
|
| 798 |
+
_AR_ANNEX_RE = re.compile(r"(?m)^[ \t]*ملحق(?:\s*رقم)?\s*[0-9٠-٩()]+")
|
| 799 |
+
_AR_BAB_RE = re.compile(
|
| 800 |
+
r"(?m)^[ \t]*الباب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
|
| 801 |
+
)
|
| 802 |
+
_AR_FASL_RE = re.compile(
|
| 803 |
+
r"(?m)^[ \t]*الفصل\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
|
| 804 |
+
)
|
| 805 |
+
_AR_QISM_RE = re.compile(
|
| 806 |
+
r"(?m)^[ \t]*القسم\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
|
| 807 |
+
)
|
| 808 |
+
_AR_KITAB_RE = re.compile(
|
| 809 |
+
r"(?m)^[ \t]*الكتاب\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
|
| 810 |
+
)
|
| 811 |
+
_AR_FARA_RE = re.compile(
|
| 812 |
+
r"(?m)^[ \t]*الفرع\s+(?:[0-9٠-٩]+|" + _AR_ORD_M + r"|" + _AR_ORD + r")"
|
| 813 |
+
)
|
| 814 |
+
_FA_BAND_RE = re.compile(r"بند\s*[0-9۰-۹]+")
|
| 815 |
+
_CJK_ZHANG_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*章")
|
| 816 |
+
_KO_JANG_RE = re.compile(r"제\s*[0-9]+\s*장")
|
| 817 |
+
_TA_ART_RE = re.compile(r"பிரிவு\s*[0-9௦-௯]+")
|
| 818 |
+
_TE_ART_RE = re.compile(r"ప్రకరణ(?:ము)?\s*[0-9౦-౯]+")
|
| 819 |
+
_KN_ART_RE = re.compile(r"ಪ್ರಕರಣ\s*[0-9೦-೯]+")
|
| 820 |
+
_GU_ART_RE = re.compile(r"કલમ\s*[0-9૦-૯]+")
|
| 821 |
+
_PA_ART_RE = re.compile(r"ਧਾਰਾ\s*[0-9੦-੯]+")
|
| 822 |
+
_ML_ART_RE = re.compile(r"വകുപ്പ്\s*[0-9൦-൯]+")
|
| 823 |
+
_CJK_BIAN_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[编編]")
|
| 824 |
+
_KO_PYEON_RE = re.compile(r"제\s*[0-9]+\s*편")
|
| 825 |
+
_TH_LAK_RE = re.compile(r"(?m)^[ \t]*ลักษณะ\s*[0-9๐-๙]+")
|
| 826 |
+
_KM_CHAP_RE = re.compile(r"ជំពូក\s*[0-9០-៩]+")
|
| 827 |
+
_LO_PART_RE = re.compile(r"ພາກ\s*[0-9໐-໙]+")
|
| 828 |
+
_MY_CHAP_RE = re.compile(r"အခန်း\s*[0-9၀-၉]+")
|
| 829 |
+
_KA_CHAP_RE = re.compile(r"თავი\s+[IVXLCDM0-9]+")
|
| 830 |
+
_HY_CHAP_RE = re.compile(r"Գլուխ\s+[IVXLCDM0-9]+", re.IGNORECASE)
|
| 831 |
+
_HY_BAZHIN_RE = re.compile(r"(?m)^[ \t]*Բաժին\s+[0-9]+", re.IGNORECASE)
|
| 832 |
+
_HY_MAS_RE = re.compile(r"(?m)^[ \t]*Մաս\s+[IVXLCDM0-9]+", re.IGNORECASE)
|
| 833 |
+
_AM_CHAP_RE = re.compile(r"ምዕራፍ\s*[0-9፩-፻]+")
|
| 834 |
+
_HI_CHAP_RE = re.compile(r"���ध्याय\s*[0-9०-९]+")
|
| 835 |
+
_BN_CHAP_RE = re.compile(r"অধ্যায়\s*[0-9০-৯]+")
|
| 836 |
+
_UR_CHAP_RE = re.compile(r"باب\s*[0-9۰-۹]+")
|
| 837 |
+
_FA_FASL_RE = re.compile(r"فصل\s*[0-9۰-۹]+")
|
| 838 |
+
_NE_CHAP_RE = re.compile(r"परिच्छेद\s*[0-9०-९]+")
|
| 839 |
+
_CJK_JIE_RE = re.compile(r"第\s*[一二三四五六七八九十百千万零〇两0-9]+\s*[节節]")
|
| 840 |
+
_KO_JEOL_RE = re.compile(r"제\s*[0-9]+\s*절")
|
| 841 |
+
_TH_TON_RE = re.compile(r"(?m)^[ \t]*ตอน\s*[0-9๐-๙]+")
|
| 842 |
+
_SR_PART_RE = re.compile(r"(?:Одељак|ОДЕЉАК)\s+[IVXLCDM0-9]+", re.IGNORECASE)
|
| 843 |
+
_RU_TITLE_RE = re.compile(
|
| 844 |
+
r"(?:Раздел|РАЗДЕЛ|Розділ|РОЗДІЛ|Раздзел|РАЗДЗЕЛ)\s+[IVXLCDM0-9]+",
|
| 845 |
+
re.IGNORECASE,
|
| 846 |
+
)
|
| 847 |
+
_RU_CHAP_RE = re.compile(r"(?:Глава|ГЛАВА)\s+[IVXLCDM0-9]+", re.IGNORECASE)
|
| 848 |
+
_TH_KO_RE = re.compile(r"(?m)^[ \t]*[กขคงจฉชซฌญ]\.")
|
| 849 |
+
_HI_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[०-९]+\s*[.।]")
|
| 850 |
+
_BN_DIGIT_ENUM_RE = re.compile(r"(?m)^[ \t]*[০-৯]+\s*[.।]")
|
| 851 |
+
_CYR_AB = "абвгдежзийк"
|
| 852 |
+
_EL_AB = "αβγδεζηθικ"
|
| 853 |
+
_KA_AB = "აბგდევზთიკლ"
|
| 854 |
+
_HY_AB = "աբգդեզէըթժ"
|
| 855 |
+
_CYR_AB_RE = re.compile(r"(?im)^[ \t]*[абвгдежзийк]\s*[).]")
|
| 856 |
+
_EL_AB_RE = re.compile(r"(?im)^[ \t]*[αβγδεζηθικ]\s*[).]")
|
| 857 |
+
_KA_AB_RE = re.compile(r"(?m)^[ \t]*[აბგდევზთიკლ]\s*[).]")
|
| 858 |
+
_HY_AB_RE = re.compile(r"(?m)^[ \t]*[աբգդեզէըթժ]\s*[).]")
|
| 859 |
+
_MARK_AFTER = r"(?:\s+|(?=[^\x00-\x7f]))"
|
| 860 |
+
_LATIN_LETTER_RE = re.compile(
|
| 861 |
+
r"(?m)^[ \t]*(?:\(\s*(?P<paren>[a-z])\s*\)|(?P<bare>[a-z])\)|"
|
| 862 |
+
r"(?P<roman>viii|iii|vii|ii|iv|ix|vi|i|v|x)\.)"
|
| 863 |
+
+ _MARK_AFTER
|
| 864 |
+
)
|
| 865 |
+
_BULLET_RE = re.compile(r"(?m)^[ \t]*[•·●‣⁃*#]\s+")
|
| 866 |
+
_DASH_NUM_RE = re.compile(r"(?m)^[ \t]*-\s*(?P<bn>[0-9]{1,3})\s+(?=[^\W\d_])")
|
| 867 |
+
_LATIN_NUM_LIST_RE = re.compile(
|
| 868 |
+
r"(?m)^[ \t]*(?:"
|
| 869 |
+
r"\(\s*(?P<nparen>[0-9]{1,3})\s*\)|"
|
| 870 |
+
r"(?P<nclose>[0-9]{1,3})\)|"
|
| 871 |
+
r"(?P<nord>[0-9]{1,3})[º°o]|"
|
| 872 |
+
r"(?P<ndot>[0-9]{1,3})\.-|"
|
| 873 |
+
r"(?P<ncolon>[0-9]{1,3}):|"
|
| 874 |
+
r"(?P<ndash>[0-9]{1,3})-|"
|
| 875 |
+
r"(?P<dbl>([a-z])\2)\)"
|
| 876 |
+
r")"
|
| 877 |
+
+ _MARK_AFTER
|
| 878 |
+
)
|
| 879 |
+
_ROMAN_LOWER = {
|
| 880 |
+
"i": "1", "ii": "2", "iii": "3", "iv": "4", "x": "10",
|
| 881 |
+
"v": "5", "vi": "6", "vii": "7", "viii": "8", "ix": "9",
|
| 882 |
+
}
|
| 883 |
+
_JA_KOU_RE = re.compile(r"第[0-9一二三四五六七八九十百]+項")
|
| 884 |
+
_ZH_KUAN_RE = re.compile(r"第[一二三四五六七八九十百千万零〇两0-9]+款")
|
| 885 |
+
_KO_ART_RE = re.compile(r"제\s*[0-9]+\s*조")
|
| 886 |
+
_KO_HANG_RE = re.compile(r"제\s*[0-9]+\s*항")
|
| 887 |
+
_KO_HO_RE = re.compile(r"제\s*[0-9]+\s*호")
|
| 888 |
+
_TH_PARA_RE = re.compile(r"วรรค\s*[0-9๐-๙]+")
|
| 889 |
+
_TH_KHO_RE = re.compile(r"(?m)^[ \t]*ข้อ\s*[0-9๐-๙]+")
|
| 890 |
+
_TH_HUAT_RE = re.compile(r"(?m)^[ \t]*หมวด\s*[0-9๐-๙]+")
|
| 891 |
+
_FA_TAB_RE = re.compile(r"تبصره\s*[0-9۰-۹]+")
|
| 892 |
+
_HE_PARA_RE = re.compile(r"פסקה\s*[0-9]+")
|
| 893 |
+
_AR_PARA_RE = re.compile(r"الفقرة\s*[0-9٠-٩]+")
|
| 894 |
+
_AR_QARAR_RE = re.compile(r"قرار(?:\s*رقم)?\s*[0-9٠-٩]+")
|
| 895 |
+
_AR_DECREE_RE = re.compile(r"(?:مرسوم|أمر)(?:\s*رقم)?\s*[0-9٠-٩]+")
|
| 896 |
+
_RU_INST_RE = re.compile(r"(?:Указ|Постановление|Приказ)\s+[0-9]+", re.IGNORECASE)
|
| 897 |
+
_KO_RANGE_RE = re.compile(
|
| 898 |
+
r"제\s*[0-9]+\s*조\s*부터\s*제\s*[0-9]+\s*조(?:까지)?"
|
| 899 |
+
)
|
| 900 |
+
_HE_ART_RE = re.compile(
|
| 901 |
+
r"(?:סעיף\s*(?:[0-9]+|(?!קטן)[א-ת]{1,3}['׳]?)|\.\s*[0-9]+(?=[\u0590-\u05FF]))"
|
| 902 |
+
)
|
| 903 |
+
_HE_KATAN_RE = re.compile(r"סעיף\s+קטן\s*\(?\s*[א-ת]'?\)?")
|
| 904 |
+
_TH_ART_RE = re.compile(r"มาตรา\s*[0-9๐-๙]+")
|
| 905 |
+
_HI_ART_RE = re.compile(r"(?:धारा|ধারা)\s*[0-9০-৯]+")
|
| 906 |
+
_RU_ART_RE = re.compile(r"(?:Статья|СТАТЬЯ|Стаття|СТАТТЯ)\s+[0-9]+(?:-[0-9]+)?", re.IGNORECASE)
|
| 907 |
+
_KA_ART_RE = re.compile(r"მუხლი\s*[0-9]+")
|
| 908 |
+
_HY_ART_RE = re.compile(r"Հոդված\s*[0-9]+", re.IGNORECASE)
|
| 909 |
+
_AM_ART_RE = re.compile(r"አንቀጽ\s*[0-9፩-፻]+")
|
| 910 |
+
_BN_ART_RE = re.compile(r"ধারা\s*[0-9০-৯]+")
|
| 911 |
+
_LO_ART_RE = re.compile(r"ມາດຕາ\s*[0-9໐-໙]+")
|
| 912 |
+
_KM_ART_RE = re.compile(r"មាត្រា\s*[0-9០-៩]+")
|
| 913 |
+
_MY_ART_RE = re.compile(r"ပုဒ်မ\s*[0-9၀-၉]+")
|
| 914 |
+
_UZ_ART_RE = re.compile(r"[0-9]+\s*-\s*(?:модда|modda)", re.IGNORECASE)
|
| 915 |
+
_MN_ART_RE = re.compile(r"[0-9]+\s*(?:дүгээр|дугаар)\s*зүйл", re.IGNORECASE)
|
| 916 |
+
_KK_ART_RE = re.compile(r"[0-9]+\s*-?\s*бап", re.IGNORECASE)
|
| 917 |
+
_NE_ART_RE = re.compile(r"दफा\s*[0-9०-९]+")
|
| 918 |
+
_TI_ART_RE = re.compile(r"ዓንቀጽ\s*[0-9፩-፻]+")
|
| 919 |
+
_BO_ART_RE = re.compile(r"དོན་ཚན་\s*[0-9༠-༩]+")
|
| 920 |
+
_UG_ART_RE = re.compile(r"ماددا\s*[0-9۰-۹]+")
|
| 921 |
+
_AR_POINT_RE = re.compile(r"(?m)^[ \t]*(?:أولا|ثانيا|ثالثا|رابعا|خامسا)\s*[:/]")
|
| 922 |
+
_AR_POINT_NUM = (("أولا", "1"), ("ثانيا", "2"), ("ثالثا", "3"), ("رابعا", "4"), ("خامسا", "5"))
|
| 923 |
+
_SI_ART_RE = re.compile(r"වගන්තිය\s*[0-9෦-෯]+")
|
| 924 |
+
_UR_ART_RE = re.compile(r"دفعہ\s*[0-9۰-۹]+")
|
| 925 |
+
_KY_ART_RE = re.compile(r"[0-9]+\s*-?\s*берене", re.IGNORECASE)
|
| 926 |
+
_BE_ART_RE = re.compile(r"Артыкул\s*[0-9]+", re.IGNORECASE)
|
| 927 |
+
|
| 928 |
+
# "A R T Í C U L O 86" / "C A P I T U L O I" → ARTÍCULO 86 / CAPITULO I
|
| 929 |
+
_SPACED_KEYWORD_RE = re.compile(
|
| 930 |
+
r"(?iu)\b((?:[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ]\s+){3,}"
|
| 931 |
+
r"[A-ZÁÉÍÓÚÜÑÀÈÌÒÙÂÊÎÔÛÄËÏÖÜÃÕÇ])\b"
|
| 932 |
+
r"(?=\s*[.:\-–—]?\s*[0-9IVXLCDM])"
|
| 933 |
+
)
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def _squeeze_spaced_keyword(match: re.Match[str]) -> str:
|
| 937 |
+
return re.sub(r"\s+", "", match.group(1))
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
_ZW_RE = re.compile(
|
| 941 |
+
r"[\ufeff\u200b\u200c\u200d\u00ad\u2060\u200e\u200f\u202a-\u202e\u2066-\u2069]"
|
| 942 |
+
)
|
| 943 |
+
# Tashkeel, niqqud, Latin combining. Keep Thai/Lao/Khmer/Myanmar/Indic Mn.
|
| 944 |
+
_STRIP_MARKS_RE = re.compile(
|
| 945 |
+
"["
|
| 946 |
+
"\u0300-\u036f"
|
| 947 |
+
"\u0483-\u0489"
|
| 948 |
+
"\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7"
|
| 949 |
+
"\u0610-\u061a\u064b-\u065f\u0670\u06d6-\u06ed"
|
| 950 |
+
"\u08d3-\u08e1\u08e3-\u08ff"
|
| 951 |
+
"]"
|
| 952 |
+
)
|
| 953 |
+
_SCRIPT_CITE_TAIL_RE = re.compile(
|
| 954 |
+
r"(?i)^\s*(?:"
|
| 955 |
+
r"من\s*(?:الدستور|القانون|الأمر|المرسوم|القرار)|"
|
| 956 |
+
r"của\s+luật|"
|
| 957 |
+
r"של\s+(?:חוק|פקודה)"
|
| 958 |
+
r")"
|
| 959 |
+
)
|
| 960 |
+
|
| 961 |
+
# UTF-8 read as Latin-1: § (U+00C2 U+00A7) is §, é is é. Âmbito stays.
|
| 962 |
+
_LATIN1_UTF8_RE = re.compile(r"[\u00c2\u00c3][\u0080-\u00bf]")
|
| 963 |
+
|
| 964 |
+
|
| 965 |
+
def _repair_latin1_utf8(text: str) -> str:
|
| 966 |
+
if "\u00c2" not in text and "\u00c3" not in text:
|
| 967 |
+
return text
|
| 968 |
+
|
| 969 |
+
def repl(match: re.Match[str]) -> str:
|
| 970 |
+
try:
|
| 971 |
+
return match.group(0).encode("latin-1").decode("utf-8")
|
| 972 |
+
except UnicodeDecodeError:
|
| 973 |
+
return match.group(0)
|
| 974 |
+
|
| 975 |
+
return _LATIN1_UTF8_RE.sub(repl, text)
|
| 976 |
+
|
| 977 |
+
|
| 978 |
+
# Script-tagged gazettes that still publish English Article/Section translations.
|
| 979 |
+
_LATIN_FALLBACK_LANGS = frozenset(
|
| 980 |
+
{"ka", "km", "hy", "am", "lo", "my", "si", "th", "he", "ne", "fa"}
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
|
| 984 |
+
class _HTMLText(HTMLParser):
|
| 985 |
+
SKIP = {"script", "style", "noscript", "svg", "nav", "footer", "header"}
|
| 986 |
+
|
| 987 |
+
def __init__(self) -> None:
|
| 988 |
+
super().__init__(convert_charrefs=True)
|
| 989 |
+
self.parts: list[str] = []
|
| 990 |
+
self.skip = 0
|
| 991 |
+
|
| 992 |
+
def handle_starttag(self, tag, attrs):
|
| 993 |
+
if tag in self.SKIP:
|
| 994 |
+
self.skip += 1
|
| 995 |
+
if tag in {"br", "p", "tr", "div", "li", "h1", "h2", "h3"} and self.skip == 0:
|
| 996 |
+
self.parts.append("\n")
|
| 997 |
+
|
| 998 |
+
def handle_endtag(self, tag):
|
| 999 |
+
if tag in self.SKIP and self.skip:
|
| 1000 |
+
self.skip -= 1
|
| 1001 |
+
if tag in {"p", "div", "li", "tr"} and self.skip == 0:
|
| 1002 |
+
self.parts.append("\n")
|
| 1003 |
+
|
| 1004 |
+
def handle_data(self, data):
|
| 1005 |
+
if self.skip == 0:
|
| 1006 |
+
self.parts.append(data)
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def has_html_tags(text: str) -> bool:
|
| 1010 |
+
return bool(text and _HAS_TAG_RE.search(text))
|
| 1011 |
+
|
| 1012 |
+
|
| 1013 |
+
def strip_html(raw: str) -> str:
|
| 1014 |
+
"""Turn leftover HTML into visible legal text. No-op if there are no tags."""
|
| 1015 |
+
if not raw or not _HAS_TAG_RE.search(raw):
|
| 1016 |
+
return raw
|
| 1017 |
+
parser = _HTMLText()
|
| 1018 |
+
try:
|
| 1019 |
+
parser.feed(raw)
|
| 1020 |
+
parser.close()
|
| 1021 |
+
text = "".join(parser.parts)
|
| 1022 |
+
except Exception:
|
| 1023 |
+
text = re.sub(r"(?is)<script.*?>.*?</script>", " ", raw)
|
| 1024 |
+
text = re.sub(r"(?is)<style.*?>.*?</style>", " ", text)
|
| 1025 |
+
text = re.sub(r"(?is)<[^>]+>", " ", text)
|
| 1026 |
+
text = html_lib.unescape(text).replace("\xa0", " ")
|
| 1027 |
+
text = re.sub(r"[ \t]+", " ", text)
|
| 1028 |
+
text = re.sub(r"\n[ \t]+", "\n", text)
|
| 1029 |
+
text = re.sub(r"\n{3,}", "\n\n", text)
|
| 1030 |
+
return text.strip()
|
| 1031 |
+
|
| 1032 |
+
|
| 1033 |
+
_ROMAN_PAGE_RE = re.compile(
|
| 1034 |
+
r"(?i)(?:i{1,3}|iv|vi{0,3}|ix|xi{0,3}|xiv|xv)$"
|
| 1035 |
+
)
|
| 1036 |
+
|
| 1037 |
+
|
| 1038 |
+
def _is_roman_page_line(line: str, nxt: str) -> bool:
|
| 1039 |
+
"""A lone i/ii/iii between blocks is a page stamp, not a list item."""
|
| 1040 |
+
if _ROMAN_PAGE_RE.fullmatch(line.strip()) is None:
|
| 1041 |
+
return False
|
| 1042 |
+
nxt = nxt.strip()
|
| 1043 |
+
if not nxt:
|
| 1044 |
+
return True
|
| 1045 |
+
return not (nxt[:1].islower() or nxt.startswith("("))
|
| 1046 |
+
|
| 1047 |
+
|
| 1048 |
+
def _is_page_num_line(line: str) -> bool:
|
| 1049 |
+
token = line.strip()
|
| 1050 |
+
if 1 <= len(token) <= 4 and all(unicodedata.category(ch) == "Nd" for ch in token):
|
| 1051 |
+
return True
|
| 1052 |
+
# "1/3" between paragraphs is page 1 of 3, not a section.
|
| 1053 |
+
parts = token.split("/")
|
| 1054 |
+
if len(parts) == 2 and all(part.isascii() and part.isdigit() for part in parts):
|
| 1055 |
+
left, right = int(parts[0]), int(parts[1])
|
| 1056 |
+
return 1 <= left <= right <= 30
|
| 1057 |
+
return False
|
| 1058 |
+
|
| 1059 |
+
|
| 1060 |
+
def _is_facing_page_line(line: str) -> bool:
|
| 1061 |
+
"""'736 737' between blocks is a two-page spread, not a citation."""
|
| 1062 |
+
parts = line.split()
|
| 1063 |
+
if len(parts) != 2 or not all(part.isascii() and part.isdigit() for part in parts):
|
| 1064 |
+
return False
|
| 1065 |
+
left, right = int(parts[0]), int(parts[1])
|
| 1066 |
+
return 100 <= left and right == left + 1 and right <= 9999
|
| 1067 |
+
|
| 1068 |
+
|
| 1069 |
+
_PAGE_OF_RE = re.compile(r"(?i)(\d{1,2})\s+of\s+(\d{1,2})")
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
def _is_page_of_line(line: str) -> bool:
|
| 1073 |
+
"""'3 of 5' between blocks is a page count, not a citation."""
|
| 1074 |
+
match = _PAGE_OF_RE.fullmatch(line.strip())
|
| 1075 |
+
if match is None:
|
| 1076 |
+
return False
|
| 1077 |
+
left, right = int(match.group(1)), int(match.group(2))
|
| 1078 |
+
return 1 <= left <= right <= 30
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
def learned_patterns_path() -> Path:
|
| 1082 |
+
override = os.environ.get("COUNTRY_LAWS_LEARNED_PATTERNS")
|
| 1083 |
+
if override:
|
| 1084 |
+
return Path(override)
|
| 1085 |
+
return Path(__file__).resolve().parent / "data" / "learned_line_patterns.json"
|
| 1086 |
+
|
| 1087 |
+
|
| 1088 |
+
_LEARNED: tuple[float, re.Pattern[str] | None] | None = None
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
def learned_line_pattern() -> re.Pattern[str] | None:
|
| 1092 |
+
"""Whole-line rules added by the normalize loop. Compiled once per file change."""
|
| 1093 |
+
global _LEARNED
|
| 1094 |
+
path = learned_patterns_path()
|
| 1095 |
+
if not path.is_file():
|
| 1096 |
+
return None
|
| 1097 |
+
mtime = path.stat().st_mtime
|
| 1098 |
+
if _LEARNED is not None and _LEARNED[0] == mtime:
|
| 1099 |
+
return _LEARNED[1]
|
| 1100 |
+
try:
|
| 1101 |
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
| 1102 |
+
except (OSError, json.JSONDecodeError):
|
| 1103 |
+
_LEARNED = (mtime, None)
|
| 1104 |
+
return None
|
| 1105 |
+
parts: list[str] = []
|
| 1106 |
+
for item in payload.get("patterns") or []:
|
| 1107 |
+
if not isinstance(item, str):
|
| 1108 |
+
continue
|
| 1109 |
+
try:
|
| 1110 |
+
re.compile(item, re.IGNORECASE)
|
| 1111 |
+
except re.error:
|
| 1112 |
+
continue
|
| 1113 |
+
parts.append(item)
|
| 1114 |
+
compiled = re.compile("|".join(f"(?:{part})" for part in parts), re.IGNORECASE) if parts else None
|
| 1115 |
+
_LEARNED = (mtime, compiled)
|
| 1116 |
+
return compiled
|
| 1117 |
+
|
| 1118 |
+
|
| 1119 |
+
def strip_chrome_lines(text: str) -> str:
|
| 1120 |
+
"""Drop gazette-site chrome lines. Never invents replacement legal text."""
|
| 1121 |
+
if not text:
|
| 1122 |
+
return ""
|
| 1123 |
+
raw_lines = text.splitlines()
|
| 1124 |
+
multi = sum(1 for ln in raw_lines if ln.strip()) > 1
|
| 1125 |
+
learned = learned_line_pattern()
|
| 1126 |
+
# Index of the next non-empty line. Slicing the tail on every line is
|
| 1127 |
+
# quadratic and stalls multi-megabyte statutes.
|
| 1128 |
+
count = len(raw_lines)
|
| 1129 |
+
next_nonempty = [count] * count
|
| 1130 |
+
nxt_i = count
|
| 1131 |
+
for idx in range(count - 1, -1, -1):
|
| 1132 |
+
next_nonempty[idx] = nxt_i
|
| 1133 |
+
if raw_lines[idx].strip():
|
| 1134 |
+
nxt_i = idx
|
| 1135 |
+
kept = []
|
| 1136 |
+
for idx, ln in enumerate(raw_lines):
|
| 1137 |
+
stripped = ln.strip()
|
| 1138 |
+
if not stripped:
|
| 1139 |
+
continue
|
| 1140 |
+
# The chrome expression is superlinear on multi-megabyte lines.
|
| 1141 |
+
# Gazette chrome that it removes is a short line. A longer line is
|
| 1142 |
+
# kept, which does not drop statute text.
|
| 1143 |
+
if len(stripped) <= 400 and (
|
| 1144 |
+
_CHROME_LINE_RE.match(stripped) or _CHROME_INLINE_RE.search(ln)
|
| 1145 |
+
):
|
| 1146 |
+
continue
|
| 1147 |
+
if len(stripped) > 400 and _CHROME_INLINE_RE.search(stripped[:200]):
|
| 1148 |
+
continue
|
| 1149 |
+
if learned is not None and len(stripped) <= 400 and learned.match(stripped):
|
| 1150 |
+
continue
|
| 1151 |
+
# A lone "2" or "10" is an article number. The same token inside a
|
| 1152 |
+
# longer page is a page stamp.
|
| 1153 |
+
if multi and (
|
| 1154 |
+
_is_page_num_line(stripped)
|
| 1155 |
+
or _is_facing_page_line(stripped)
|
| 1156 |
+
or _is_page_of_line(stripped)
|
| 1157 |
+
):
|
| 1158 |
+
continue
|
| 1159 |
+
nxt = ""
|
| 1160 |
+
nxt_at = next_nonempty[idx]
|
| 1161 |
+
if nxt_at < count:
|
| 1162 |
+
nxt = raw_lines[nxt_at]
|
| 1163 |
+
if multi and _is_roman_page_line(stripped, nxt):
|
| 1164 |
+
continue
|
| 1165 |
+
kept.append(ln)
|
| 1166 |
+
return "\n".join(kept).strip()
|
| 1167 |
+
|
| 1168 |
+
|
| 1169 |
+
_HYPHEN_BREAK_RE = re.compile(r"(?<=[^\W\d_])-[ \t]*\n+[ \t]*([^\W\d_])")
|
| 1170 |
+
|
| 1171 |
+
|
| 1172 |
+
def _join_hyphen_breaks(text: str) -> str:
|
| 1173 |
+
"""Join a hyphenated word split across lines. Leave a following capital header."""
|
| 1174 |
+
|
| 1175 |
+
def repl(match: re.Match[str]) -> str:
|
| 1176 |
+
nxt = match.group(1)
|
| 1177 |
+
if nxt.isupper():
|
| 1178 |
+
return match.group(0)
|
| 1179 |
+
return nxt
|
| 1180 |
+
|
| 1181 |
+
return _HYPHEN_BREAK_RE.sub(repl, text)
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
def normalize_legal_text(value: Any) -> str:
|
| 1185 |
+
"""NFKC + HTML strip. Keeps newlines so heading detection still works."""
|
| 1186 |
+
if value is None:
|
| 1187 |
+
return ""
|
| 1188 |
+
text = unicodedata.normalize("NFKC", str(value)).replace("\x00", "")
|
| 1189 |
+
if text.startswith("ÿþ") or text.startswith("þÿ"):
|
| 1190 |
+
text = text[2:]
|
| 1191 |
+
text = re.sub(r"[\x00-\x08\x0b\x0e-\x1f\x7f]", " ", text)
|
| 1192 |
+
text = text.replace("\ufffd", " ")
|
| 1193 |
+
text = re.sub(r"[\ue000-\uf8ff]", "", text)
|
| 1194 |
+
text = _repair_latin1_utf8(text)
|
| 1195 |
+
text = re.sub(r"\(cid:\d+\)", " ", text)
|
| 1196 |
+
text = _ZW_RE.sub("", text).replace("ـ", "")
|
| 1197 |
+
text = _STRIP_MARKS_RE.sub("", text)
|
| 1198 |
+
text = re.sub(r"[\u2010-\u2015\u2212\ufe58\ufe63\uff0d]", "-", text)
|
| 1199 |
+
text = re.sub(r"[\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000]", " ", text)
|
| 1200 |
+
text = text.replace("\u2028", "\n").replace("\u2029", "\n").replace("\f", "\n")
|
| 1201 |
+
text = _join_hyphen_breaks(text)
|
| 1202 |
+
text = _NUMERO_FOLD_RE.sub("nr. ", text)
|
| 1203 |
+
text = re.sub(r"المادة\s*-\s*اختر\s*-\s*", "", text)
|
| 1204 |
+
text = re.sub(r"(?m)^[ \t]*©+\s*", "", text)
|
| 1205 |
+
text = re.sub(r"\b((?:19|20)\d{2}) \1\b", r"\1", text)
|
| 1206 |
+
text = re.sub(r"(?<=[A-Za-z])!+(?=\d)", " ", text)
|
| 1207 |
+
text = re.sub(r":!+", ":", text)
|
| 1208 |
+
text = re.sub(r"(?m)!+\s*$", "", text)
|
| 1209 |
+
text = _SPACED_KEYWORD_RE.sub(_squeeze_spaced_keyword, text)
|
| 1210 |
+
text = re.sub(r"(?s)<!--.*?-->", " ", text)
|
| 1211 |
+
text = strip_html(text)
|
| 1212 |
+
text = html_lib.unescape(text).replace("\xa0", " ")
|
| 1213 |
+
text = re.sub(r"_{3,}", " ", text)
|
| 1214 |
+
text = re.sub(r"\.{4,}", " ", text)
|
| 1215 |
+
text = re.sub(r"(?m)^[ \t]*#{1,6}[ \t]+", "", text)
|
| 1216 |
+
text = strip_chrome_lines(text)
|
| 1217 |
+
text = text.replace("\xa0", " ")
|
| 1218 |
+
text = re.sub(r"~\$\S{0,16}", " ", text)
|
| 1219 |
+
text = re.sub(r"\*\*([^*]{1,80})\*\*", r"\1", text)
|
| 1220 |
+
text = re.sub(r"__([^_]{1,80})__", r"\1", text)
|
| 1221 |
+
text = re.sub(r"'{3}([^']{1,80})'{3}", r"\1", text)
|
| 1222 |
+
text = re.sub(r"^={2,6}\s*(.+?)\s*={2,6}\s*$", r"\1", text, flags=re.MULTILINE)
|
| 1223 |
+
text = re.sub(r"[ \t]+", " ", text)
|
| 1224 |
+
text = re.sub(r"\n[ \t]+", "\n", text)
|
| 1225 |
+
text = re.sub(r"[ \t]+\n", "\n", text)
|
| 1226 |
+
text = _join_hyphen_breaks(text)
|
| 1227 |
+
text = re.sub(r"\n{3,}", "\n\n", text)
|
| 1228 |
+
return text.strip()
|
| 1229 |
+
|
| 1230 |
+
|
| 1231 |
+
@dataclass
|
| 1232 |
+
class StructureUnit:
|
| 1233 |
+
kind: str
|
| 1234 |
+
number: str
|
| 1235 |
+
heading: str
|
| 1236 |
+
body: str
|
| 1237 |
+
title_number: str = ""
|
| 1238 |
+
chapter_number: str = ""
|
| 1239 |
+
part_number: str = ""
|
| 1240 |
+
article_number: str = ""
|
| 1241 |
+
section_number: str = ""
|
| 1242 |
+
subsections: tuple[str, ...] = ()
|
| 1243 |
+
hierarchy_path: str = ""
|
| 1244 |
+
char_start: int = 0
|
| 1245 |
+
char_end: int = 0
|
| 1246 |
+
|
| 1247 |
+
def to_dict(self) -> dict[str, Any]:
|
| 1248 |
+
return {
|
| 1249 |
+
"kind": self.kind,
|
| 1250 |
+
"number": self.number,
|
| 1251 |
+
"heading": self.heading,
|
| 1252 |
+
"body": self.body,
|
| 1253 |
+
"title_number": self.title_number,
|
| 1254 |
+
"chapter_number": self.chapter_number,
|
| 1255 |
+
"part_number": self.part_number,
|
| 1256 |
+
"article_number": self.article_number,
|
| 1257 |
+
"section_number": self.section_number,
|
| 1258 |
+
"subsections": list(self.subsections),
|
| 1259 |
+
"hierarchy_path": self.hierarchy_path,
|
| 1260 |
+
"char_start": self.char_start,
|
| 1261 |
+
"char_end": self.char_end,
|
| 1262 |
+
}
|
| 1263 |
+
|
| 1264 |
+
|
| 1265 |
+
def _cursor_path(cursor: dict[str, str]) -> str:
|
| 1266 |
+
parts = []
|
| 1267 |
+
for key, label in (
|
| 1268 |
+
("title", "Title"),
|
| 1269 |
+
("chapter", "Chapter"),
|
| 1270 |
+
("part", "Part"),
|
| 1271 |
+
("article", "Article"),
|
| 1272 |
+
("section", "Section"),
|
| 1273 |
+
):
|
| 1274 |
+
value = cursor.get(key) or ""
|
| 1275 |
+
if value:
|
| 1276 |
+
parts.append(f"{label} {value}")
|
| 1277 |
+
return " > ".join(parts)
|
| 1278 |
+
|
| 1279 |
+
|
| 1280 |
+
def _subsection_tokens(text: str) -> tuple[str, ...]:
|
| 1281 |
+
seen: list[str] = []
|
| 1282 |
+
for match in _SUBSECTION_RE.finditer(text):
|
| 1283 |
+
token = match.group(1)
|
| 1284 |
+
if token not in seen:
|
| 1285 |
+
seen.append(token)
|
| 1286 |
+
if len(seen) >= 40:
|
| 1287 |
+
break
|
| 1288 |
+
return tuple(seen)
|
| 1289 |
+
|
| 1290 |
+
|
| 1291 |
+
def check_exclusive_cover(text: str, units: list[StructureUnit]) -> bool:
|
| 1292 |
+
"""True iff units are contiguous, non-overlapping, and cover *text* exactly."""
|
| 1293 |
+
if not units:
|
| 1294 |
+
return not text
|
| 1295 |
+
ordered = sorted(units, key=lambda u: u.char_start)
|
| 1296 |
+
if ordered[0].char_start != 0 or ordered[-1].char_end != len(text):
|
| 1297 |
+
return False
|
| 1298 |
+
prev = 0
|
| 1299 |
+
for unit in ordered:
|
| 1300 |
+
if unit.char_start != prev or unit.char_end < unit.char_start:
|
| 1301 |
+
return False
|
| 1302 |
+
if text[unit.char_start : unit.char_end] != unit.body:
|
| 1303 |
+
return False
|
| 1304 |
+
prev = unit.char_end
|
| 1305 |
+
return True
|
| 1306 |
+
|
| 1307 |
+
|
| 1308 |
+
def _script_regex(language: str):
|
| 1309 |
+
from .profiles import iso_lang
|
| 1310 |
+
|
| 1311 |
+
lang = iso_lang(language)
|
| 1312 |
+
if lang in {"zh", "zh-cn", "zh-tw"}:
|
| 1313 |
+
return _ZH_ART_RE
|
| 1314 |
+
if lang == "ar":
|
| 1315 |
+
return _AR_ART_RE
|
| 1316 |
+
if lang == "fa":
|
| 1317 |
+
return _FA_ART_RE
|
| 1318 |
+
if lang == "ja":
|
| 1319 |
+
return _JA_ART_RE
|
| 1320 |
+
if lang == "ko":
|
| 1321 |
+
return _KO_ART_RE
|
| 1322 |
+
if lang == "he":
|
| 1323 |
+
return _HE_ART_RE
|
| 1324 |
+
if lang == "th":
|
| 1325 |
+
return _TH_ART_RE
|
| 1326 |
+
if lang == "hi":
|
| 1327 |
+
return _HI_ART_RE
|
| 1328 |
+
if lang == "bn":
|
| 1329 |
+
return _BN_ART_RE
|
| 1330 |
+
if lang in {"ru", "uk", "be"}:
|
| 1331 |
+
return _RU_ART_RE
|
| 1332 |
+
if lang == "ka":
|
| 1333 |
+
return _KA_ART_RE
|
| 1334 |
+
if lang == "hy":
|
| 1335 |
+
return _HY_ART_RE
|
| 1336 |
+
if lang == "am":
|
| 1337 |
+
return _AM_ART_RE
|
| 1338 |
+
if lang == "ti":
|
| 1339 |
+
return _TI_ART_RE
|
| 1340 |
+
if lang == "bo":
|
| 1341 |
+
return _BO_ART_RE
|
| 1342 |
+
if lang == "ug":
|
| 1343 |
+
return _UG_ART_RE
|
| 1344 |
+
if lang == "lo":
|
| 1345 |
+
return _LO_ART_RE
|
| 1346 |
+
if lang == "km":
|
| 1347 |
+
return _KM_ART_RE
|
| 1348 |
+
if lang == "my":
|
| 1349 |
+
return _MY_ART_RE
|
| 1350 |
+
if lang == "uz":
|
| 1351 |
+
return _UZ_ART_RE
|
| 1352 |
+
if lang == "mn":
|
| 1353 |
+
return _MN_ART_RE
|
| 1354 |
+
if lang == "kk":
|
| 1355 |
+
return _KK_ART_RE
|
| 1356 |
+
if lang == "ne":
|
| 1357 |
+
return _NE_ART_RE
|
| 1358 |
+
if lang == "si":
|
| 1359 |
+
return _SI_ART_RE
|
| 1360 |
+
if lang == "ta":
|
| 1361 |
+
return _TA_ART_RE
|
| 1362 |
+
if lang == "te":
|
| 1363 |
+
return _TE_ART_RE
|
| 1364 |
+
if lang == "kn":
|
| 1365 |
+
return _KN_ART_RE
|
| 1366 |
+
if lang == "gu":
|
| 1367 |
+
return _GU_ART_RE
|
| 1368 |
+
if lang == "pa":
|
| 1369 |
+
return _PA_ART_RE
|
| 1370 |
+
if lang == "ml":
|
| 1371 |
+
return _ML_ART_RE
|
| 1372 |
+
if lang == "ur":
|
| 1373 |
+
return _UR_ART_RE
|
| 1374 |
+
if lang == "ky":
|
| 1375 |
+
return _KY_ART_RE
|
| 1376 |
+
if lang == "be":
|
| 1377 |
+
return _BE_ART_RE
|
| 1378 |
+
return None
|
| 1379 |
+
|
| 1380 |
+
|
| 1381 |
+
def _detected_script_regexes(text: str, language: str) -> list:
|
| 1382 |
+
found: list = []
|
| 1383 |
+
primary = _script_regex(language)
|
| 1384 |
+
if primary is not None:
|
| 1385 |
+
found.append(primary)
|
| 1386 |
+
if re.search(r"[①-⑳⑴-⒇❶-❿⓫-⓴]", text):
|
| 1387 |
+
found.append(_CIRCLED_ART_RE)
|
| 1388 |
+
if re.search(r"[\u4e00-\u9fff]", text):
|
| 1389 |
+
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))
|
| 1390 |
+
if re.search(r"[\uac00-\ud7af]", text):
|
| 1391 |
+
found.extend((_KO_ART_RE, _KO_HANG_RE, _KO_HO_RE, _KO_GA_RE, _KO_JANG_RE, _KO_PYEON_RE, _KO_JEOL_RE))
|
| 1392 |
+
if re.search(r"[\u30a0-\u30ff]", text):
|
| 1393 |
+
found.append(_JA_KATA_ENUM_RE)
|
| 1394 |
+
if re.search(r"[\u0600-\u06ff]", text):
|
| 1395 |
+
found.extend((
|
| 1396 |
+
_AR_ART_RE, _FA_ART_RE, _FA_TAB_RE, _FA_BAND_RE, _FA_FASL_RE, _AR_PARA_RE, _AR_QARAR_RE, _AR_DECREE_RE,
|
| 1397 |
+
_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,
|
| 1398 |
+
))
|
| 1399 |
+
if re.search(r"[\u0590-\u05ff]", text):
|
| 1400 |
+
found.extend((
|
| 1401 |
+
_HE_ART_RE, _HE_PARA_RE, _HE_ALEF_RE, _HE_PEREK_RE, _HE_SIMAN_RE,
|
| 1402 |
+
_HE_HELEK_RE, _HE_TOS_RE, _HE_TAKANA_RE, _HE_KATAN_RE,
|
| 1403 |
+
))
|
| 1404 |
+
if re.search(r"[\u0e00-\u0e7f]", text):
|
| 1405 |
+
found.extend((_TH_ART_RE, _TH_PARA_RE, _TH_KO_RE, _TH_KHO_RE, _TH_HUAT_RE, _TH_LAK_RE, _TH_TON_RE))
|
| 1406 |
+
if re.search(r"[\u0900-\u097f]", text):
|
| 1407 |
+
found.extend((_HI_ART_RE, _HI_DIGIT_ENUM_RE, _HI_CHAP_RE, _NE_CHAP_RE))
|
| 1408 |
+
if re.search(r"[\u0980-\u09ff]", text):
|
| 1409 |
+
found.extend((_BN_ART_RE, _BN_DIGIT_ENUM_RE, _BN_CHAP_RE))
|
| 1410 |
+
if re.search(r"[\u0b80-\u0bff]", text):
|
| 1411 |
+
found.append(_TA_ART_RE)
|
| 1412 |
+
if re.search(r"[\u0c00-\u0c7f]", text):
|
| 1413 |
+
found.append(_TE_ART_RE)
|
| 1414 |
+
if re.search(r"[\u0c80-\u0cff]", text):
|
| 1415 |
+
found.append(_KN_ART_RE)
|
| 1416 |
+
if re.search(r"[\u0a80-\u0aff]", text):
|
| 1417 |
+
found.append(_GU_ART_RE)
|
| 1418 |
+
if re.search(r"[\u0a00-\u0a7f]", text):
|
| 1419 |
+
found.append(_PA_ART_RE)
|
| 1420 |
+
if re.search(r"[\u0d00-\u0d7f]", text):
|
| 1421 |
+
found.append(_ML_ART_RE)
|
| 1422 |
+
if re.search(r"[\u0e80-\u0eff]", text):
|
| 1423 |
+
found.extend((_LO_ART_RE, _LO_PART_RE))
|
| 1424 |
+
if re.search(r"[\u1780-\u17ff]", text):
|
| 1425 |
+
found.extend((_KM_ART_RE, _KM_CHAP_RE))
|
| 1426 |
+
if re.search(r"[\u1000-\u109f]", text):
|
| 1427 |
+
found.extend((_MY_ART_RE, _MY_CHAP_RE))
|
| 1428 |
+
if re.search(r"[\u1200-\u137f]", text):
|
| 1429 |
+
found.extend((_AM_ART_RE, _AM_CHAP_RE, _TI_ART_RE))
|
| 1430 |
+
if re.search(r"[\u0f00-\u0fff]", text):
|
| 1431 |
+
found.append(_BO_ART_RE)
|
| 1432 |
+
if re.search(r"[\u10a0-\u10ff]", text):
|
| 1433 |
+
found.extend((_KA_ART_RE, _KA_AB_RE, _KA_CHAP_RE))
|
| 1434 |
+
if re.search(r"[\u0530-\u058f]", text):
|
| 1435 |
+
found.extend((_HY_ART_RE, _HY_AB_RE, _HY_CHAP_RE, _HY_BAZHIN_RE, _HY_MAS_RE))
|
| 1436 |
+
if re.search(r"[\u0400-\u04ff]", text):
|
| 1437 |
+
found.extend((_CYR_AB_RE, _RU_TITLE_RE, _RU_CHAP_RE, _SR_PART_RE))
|
| 1438 |
+
if re.search(r"[\u0370-\u03ff]", text):
|
| 1439 |
+
found.append(_EL_AB_RE)
|
| 1440 |
+
if "модда" in text.casefold() or re.search(r"\bmodda\b", text, re.IGNORECASE):
|
| 1441 |
+
found.append(_UZ_ART_RE)
|
| 1442 |
+
if re.search(r"зүйл", text, re.IGNORECASE):
|
| 1443 |
+
found.append(_MN_ART_RE)
|
| 1444 |
+
if re.search(r"бап", text, re.IGNORECASE):
|
| 1445 |
+
found.append(_KK_ART_RE)
|
| 1446 |
+
if "दफा" in text:
|
| 1447 |
+
found.append(_NE_ART_RE)
|
| 1448 |
+
if "परिच्छेद" in text:
|
| 1449 |
+
found.append(_NE_CHAP_RE)
|
| 1450 |
+
if "වගන්තිය" in text:
|
| 1451 |
+
found.append(_SI_ART_RE)
|
| 1452 |
+
if "دفعہ" in text:
|
| 1453 |
+
found.append(_UR_ART_RE)
|
| 1454 |
+
if re.search(r"берене", text, re.IGNORECASE):
|
| 1455 |
+
found.append(_KY_ART_RE)
|
| 1456 |
+
if re.search(r"артыкул", text, re.IGNORECASE):
|
| 1457 |
+
found.append(_BE_ART_RE)
|
| 1458 |
+
if re.search(r"статья|стаття", text, re.IGNORECASE):
|
| 1459 |
+
found.append(_RU_ART_RE)
|
| 1460 |
+
if re.search(r"указ|постановление|приказ", text, re.IGNORECASE):
|
| 1461 |
+
found.append(_RU_INST_RE)
|
| 1462 |
+
# Preserve order, drop duplicate pattern objects.
|
| 1463 |
+
out: list = []
|
| 1464 |
+
seen: set[int] = set()
|
| 1465 |
+
for regex in found:
|
| 1466 |
+
key = id(regex)
|
| 1467 |
+
if key not in seen:
|
| 1468 |
+
seen.add(key)
|
| 1469 |
+
out.append(regex)
|
| 1470 |
+
return out
|
| 1471 |
+
|
| 1472 |
+
|
| 1473 |
+
def _lexicon_heading_re() -> re.Pattern[str]:
|
| 1474 |
+
"""Heading matcher generated from HEADING_LEXICON so new languages are data."""
|
| 1475 |
+
global _LEXICON_HEADING_RE, _LEXICON_KIND
|
| 1476 |
+
if _LEXICON_HEADING_RE is not None:
|
| 1477 |
+
return _LEXICON_HEADING_RE
|
| 1478 |
+
from .profiles import HEADING_LEXICON
|
| 1479 |
+
|
| 1480 |
+
words: list[str] = []
|
| 1481 |
+
kinds: dict[str, str] = {}
|
| 1482 |
+
for token, hits in HEADING_LEXICON.items():
|
| 1483 |
+
token = (token or "").strip()
|
| 1484 |
+
if len(token) < 2:
|
| 1485 |
+
continue
|
| 1486 |
+
kinds_found = [kind for kind, _lang in hits if kind in {"article", "section", "title", "chapter", "part"}]
|
| 1487 |
+
if not kinds_found:
|
| 1488 |
+
continue
|
| 1489 |
+
folded = _latin_fold(token)
|
| 1490 |
+
words.append(folded)
|
| 1491 |
+
kinds[folded.casefold()] = kinds_found[0]
|
| 1492 |
+
words.sort(key=len, reverse=True)
|
| 1493 |
+
escaped = [re.escape(w) for w in words]
|
| 1494 |
+
_LEXICON_HEADING_RE = re.compile(
|
| 1495 |
+
_latin_fold(
|
| 1496 |
+
r"(?im)" + _HEADING_START + r"(?:l['’])?(?P<lex>"
|
| 1497 |
+
+ "|".join(escaped)
|
| 1498 |
+
+ r")(?![A-Za-z])(?:\s*(?:n\.?[o°º”'“*´`]|nr|no)\.?\s*)?\s*[.\s:–—-]*\(?\s*(?P<lex_n>"
|
| 1499 |
+
+ _ARTICLE_N
|
| 1500 |
+
+ r")\)?"
|
| 1501 |
+
)
|
| 1502 |
+
)
|
| 1503 |
+
_LEXICON_KIND = kinds
|
| 1504 |
+
return _LEXICON_HEADING_RE
|
| 1505 |
+
|
| 1506 |
+
|
| 1507 |
+
def _plausible_cw_number(raw: str) -> bool:
|
| 1508 |
+
"""Drop year-like '1902. Amendment' titles from keyword-less numbering."""
|
| 1509 |
+
digits = re.sub(r"\D", "", raw or "")
|
| 1510 |
+
if not digits:
|
| 1511 |
+
return False
|
| 1512 |
+
value = int(digits)
|
| 1513 |
+
if value <= 0 or value > 2000:
|
| 1514 |
+
return False
|
| 1515 |
+
if 1800 <= value <= 2099:
|
| 1516 |
+
return False
|
| 1517 |
+
return True
|
| 1518 |
+
|
| 1519 |
+
|
| 1520 |
+
def _fold_digits_in_number(raw: str) -> str:
|
| 1521 |
+
"""Map Nd digits (١, १, ๑, …) to ASCII so retrieval numbers stay decimal."""
|
| 1522 |
+
if not raw:
|
| 1523 |
+
return raw
|
| 1524 |
+
out: list[str] = []
|
| 1525 |
+
changed = False
|
| 1526 |
+
for ch in raw:
|
| 1527 |
+
if unicodedata.category(ch) == "Nd":
|
| 1528 |
+
digit = unicodedata.digit(ch)
|
| 1529 |
+
if digit is not None:
|
| 1530 |
+
mapped = str(digit)
|
| 1531 |
+
out.append(mapped)
|
| 1532 |
+
if mapped != ch:
|
| 1533 |
+
changed = True
|
| 1534 |
+
continue
|
| 1535 |
+
out.append(ch)
|
| 1536 |
+
return "".join(out) if changed else raw
|
| 1537 |
+
|
| 1538 |
+
|
| 1539 |
+
def _unicode_digit_runs(text: str) -> list[str]:
|
| 1540 |
+
"""ASCII-fold Nd runs (Thai ๑, Myanmar ၁, Arabic-Indic, …)."""
|
| 1541 |
+
runs: list[str] = []
|
| 1542 |
+
cur: list[str] = []
|
| 1543 |
+
for char in text:
|
| 1544 |
+
if unicodedata.category(char) == "Nd":
|
| 1545 |
+
cur.append(str(unicodedata.digit(char)))
|
| 1546 |
+
elif cur:
|
| 1547 |
+
runs.append("".join(cur))
|
| 1548 |
+
cur = []
|
| 1549 |
+
if cur:
|
| 1550 |
+
runs.append("".join(cur))
|
| 1551 |
+
return runs
|
| 1552 |
+
|
| 1553 |
+
|
| 1554 |
+
_AR_ORDINAL_NUM = (
|
| 1555 |
+
("الحادية عشرة", "11"),
|
| 1556 |
+
("الثانية عشرة", "12"),
|
| 1557 |
+
("الثالثة عشرة", "13"),
|
| 1558 |
+
("الرابعة عشرة", "14"),
|
| 1559 |
+
("الخامسة عشرة", "15"),
|
| 1560 |
+
("السادسة عشرة", "16"),
|
| 1561 |
+
("السابعة عشرة", "17"),
|
| 1562 |
+
("الثامنة عشرة", "18"),
|
| 1563 |
+
("التاسعة عشرة", "19"),
|
| 1564 |
+
("الحادية والعشرون", "21"),
|
| 1565 |
+
("الثانية والعشرون", "22"),
|
| 1566 |
+
("الثالثة والعشرون", "23"),
|
| 1567 |
+
("الرابعة والعشرون", "24"),
|
| 1568 |
+
("الخامسة والعشرون", "25"),
|
| 1569 |
+
("السادسة والعشرون", "26"),
|
| 1570 |
+
("السابعة والعشرون", "27"),
|
| 1571 |
+
("الثامنة والعشرون", "28"),
|
| 1572 |
+
("التاسعة والعشرون", "29"),
|
| 1573 |
+
("العشرون", "20"),
|
| 1574 |
+
("الأولى", "1"),
|
| 1575 |
+
("الأولي", "1"),
|
| 1576 |
+
("األولى", "1"),
|
| 1577 |
+
("الاولى", "1"),
|
| 1578 |
+
("الثانية", "2"),
|
| 1579 |
+
("الثالثة", "3"),
|
| 1580 |
+
("الرابعة", "4"),
|
| 1581 |
+
("الخامسة", "5"),
|
| 1582 |
+
("السادسة", "6"),
|
| 1583 |
+
("السابعة", "7"),
|
| 1584 |
+
("الثامنة", "8"),
|
| 1585 |
+
("التاسعة", "9"),
|
| 1586 |
+
("العاشرة", "10"),
|
| 1587 |
+
("الأول", "1"),
|
| 1588 |
+
("الاول", "1"),
|
| 1589 |
+
("الثاني", "2"),
|
| 1590 |
+
("الثالث", "3"),
|
| 1591 |
+
("الرابع", "4"),
|
| 1592 |
+
("الخامس", "5"),
|
| 1593 |
+
("السادس", "6"),
|
| 1594 |
+
("السابع", "7"),
|
| 1595 |
+
("الثامن", "8"),
|
| 1596 |
+
("التاسع", "9"),
|
| 1597 |
+
("العاشر", "10"),
|
| 1598 |
+
)
|
| 1599 |
+
_HE_VALUES = {
|
| 1600 |
+
"א": 1, "ב": 2, "ג": 3, "ד": 4, "ה": 5, "ו": 6, "ז": 7, "ח": 8, "ט": 9,
|
| 1601 |
+
"י": 10, "כ": 20, "ך": 20, "ל": 30, "מ": 40, "ם": 40, "נ": 50, "ן": 50,
|
| 1602 |
+
"ס": 60, "ע": 70, "פ": 80, "ף": 80, "צ": 90, "ץ": 90, "ק": 100,
|
| 1603 |
+
"ר": 200, "ש": 300, "ת": 400,
|
| 1604 |
+
}
|
| 1605 |
+
_HE_ORDINAL_NUM = (
|
| 1606 |
+
("ראשונה", "1"),
|
| 1607 |
+
("שנייה", "2"),
|
| 1608 |
+
("שניה", "2"),
|
| 1609 |
+
("שלישית", "3"),
|
| 1610 |
+
("רביעית", "4"),
|
| 1611 |
+
("חמישית", "5"),
|
| 1612 |
+
("שישית", "6"),
|
| 1613 |
+
)
|
| 1614 |
+
_ETH_VALUES = {
|
| 1615 |
+
"፩": 1, "፪": 2, "፫": 3, "፬": 4, "፭": 5, "፮": 6, "፯": 7, "፰": 8, "፱": 9,
|
| 1616 |
+
"፲": 10, "፳": 20, "፴": 30, "፵": 40, "፶": 50, "፷": 60, "፸": 70, "፹": 80, "፺": 90,
|
| 1617 |
+
"፻": 100, "፼": 10000,
|
| 1618 |
+
}
|
| 1619 |
+
_FA_ORDINAL_NUM = (
|
| 1620 |
+
("دوازدهم", "12"),
|
| 1621 |
+
("سیزدهم", "13"),
|
| 1622 |
+
("چهاردهم", "14"),
|
| 1623 |
+
("پانزدهم", "15"),
|
| 1624 |
+
("شانزدهم", "16"),
|
| 1625 |
+
("هفدهم", "17"),
|
| 1626 |
+
("هجدهم", "18"),
|
| 1627 |
+
("نوزدهم", "19"),
|
| 1628 |
+
("یازدهم", "11"),
|
| 1629 |
+
("بیستم", "20"),
|
| 1630 |
+
("چهارم", "4"),
|
| 1631 |
+
("چارم", "4"),
|
| 1632 |
+
("جارم", "4"),
|
| 1633 |
+
("پنجم", "5"),
|
| 1634 |
+
("ششم", "6"),
|
| 1635 |
+
("هفتم", "7"),
|
| 1636 |
+
("هشتم", "8"),
|
| 1637 |
+
("نهم", "9"),
|
| 1638 |
+
("دهم", "10"),
|
| 1639 |
+
("سوم", "3"),
|
| 1640 |
+
("دوم", "2"),
|
| 1641 |
+
("اولی", "1"),
|
| 1642 |
+
("اول", "1"),
|
| 1643 |
+
("نخست", "1"),
|
| 1644 |
+
)
|
| 1645 |
+
_CJK_DIGIT = {
|
| 1646 |
+
"零": 0, "〇": 0, "一": 1, "二": 2, "三": 3, "四": 4,
|
| 1647 |
+
"五": 5, "六": 6, "七": 7, "八": 8, "九": 9,
|
| 1648 |
+
}
|
| 1649 |
+
|
| 1650 |
+
|
| 1651 |
+
def _cjk_numeral_value(text: str) -> str | None:
|
| 1652 |
+
body = re.sub(r"[第条條項款章编編节節之조항호편절、]", "", text)
|
| 1653 |
+
if not body or not all(ch in _CJK_DIGIT or ch == "十" or ch == "百" for ch in body):
|
| 1654 |
+
return None
|
| 1655 |
+
if body == "十":
|
| 1656 |
+
return "10"
|
| 1657 |
+
if body.startswith("十"):
|
| 1658 |
+
return str(10 + _CJK_DIGIT.get(body[1], 0))
|
| 1659 |
+
if "百" in body:
|
| 1660 |
+
left, right = body.split("百", 1)
|
| 1661 |
+
if not left:
|
| 1662 |
+
hundreds = 100
|
| 1663 |
+
elif left in _CJK_DIGIT:
|
| 1664 |
+
hundreds = _CJK_DIGIT[left] * 100
|
| 1665 |
+
else:
|
| 1666 |
+
return None
|
| 1667 |
+
if not right:
|
| 1668 |
+
return str(hundreds)
|
| 1669 |
+
rest = _cjk_numeral_value(right)
|
| 1670 |
+
if rest is None:
|
| 1671 |
+
return None
|
| 1672 |
+
return str(hundreds + int(rest))
|
| 1673 |
+
if "十" in body:
|
| 1674 |
+
left, right = body.split("十", 1)
|
| 1675 |
+
tens = _CJK_DIGIT.get(left, 0) * 10
|
| 1676 |
+
ones = _CJK_DIGIT.get(right, 0) if right else 0
|
| 1677 |
+
return str(tens + ones)
|
| 1678 |
+
if body in _CJK_DIGIT:
|
| 1679 |
+
return str(_CJK_DIGIT[body])
|
| 1680 |
+
return None
|
| 1681 |
+
|
| 1682 |
+
|
| 1683 |
+
def _circled_to_int(char: str) -> str | None:
|
| 1684 |
+
if not char:
|
| 1685 |
+
return None
|
| 1686 |
+
code = ord(char[0])
|
| 1687 |
+
if 0x2460 <= code <= 0x2473:
|
| 1688 |
+
return str(code - 0x2460 + 1)
|
| 1689 |
+
if 0x2474 <= code <= 0x2487:
|
| 1690 |
+
return str(code - 0x2474 + 1)
|
| 1691 |
+
if 0x2488 <= code <= 0x249B:
|
| 1692 |
+
return str(code - 0x2488 + 1)
|
| 1693 |
+
if 0x2776 <= code <= 0x277F:
|
| 1694 |
+
return str(code - 0x2776 + 1)
|
| 1695 |
+
if 0x24EB <= code <= 0x24F4:
|
| 1696 |
+
return str(code - 0x24EB + 11)
|
| 1697 |
+
return None
|
| 1698 |
+
|
| 1699 |
+
|
| 1700 |
+
def _ethiopic_numeral_value(text: str) -> str | None:
|
| 1701 |
+
chars = [ch for ch in text if ch in _ETH_VALUES]
|
| 1702 |
+
if not chars:
|
| 1703 |
+
return None
|
| 1704 |
+
body = "".join(chars)
|
| 1705 |
+
if "፼" in body:
|
| 1706 |
+
left, right = body.split("፼", 1)
|
| 1707 |
+
mul = _ethiopic_numeral_value(left) if left else "1"
|
| 1708 |
+
rest = _ethiopic_numeral_value(right) if right else "0"
|
| 1709 |
+
if mul is None or rest is None:
|
| 1710 |
+
return None
|
| 1711 |
+
return str(int(mul) * 10000 + int(rest))
|
| 1712 |
+
if "፻" in body:
|
| 1713 |
+
left, right = body.split("፻", 1)
|
| 1714 |
+
mul = sum(_ETH_VALUES[ch] for ch in left) if left else 1
|
| 1715 |
+
rest = sum(_ETH_VALUES[ch] for ch in right)
|
| 1716 |
+
return str(mul * 100 + rest)
|
| 1717 |
+
return str(sum(_ETH_VALUES[ch] for ch in chars))
|
| 1718 |
+
|
| 1719 |
+
|
| 1720 |
+
def _hebrew_letter_num(raw: str) -> str | None:
|
| 1721 |
+
"""Map פרק א' / תוספת שניה / סעיף יא to decimal. Long Hebrew words stay unmapped."""
|
| 1722 |
+
cleaned = re.sub(r"['׳״\"`]", "", raw)
|
| 1723 |
+
for word, num in _HE_ORDINAL_NUM:
|
| 1724 |
+
if word in cleaned:
|
| 1725 |
+
return num
|
| 1726 |
+
katan = re.search(r"סעיף\s+קטן\s*\(?\s*([א-ת])", cleaned)
|
| 1727 |
+
if katan:
|
| 1728 |
+
ch = katan.group(1)
|
| 1729 |
+
return str(_HE_VALUES[ch]) if ch in _HE_VALUES else ch
|
| 1730 |
+
match = re.search(r"(?:פרק|סימן|חלק|תוספת|סעיף)\s*(?!קטן)([א-ת]{1,3})", cleaned)
|
| 1731 |
+
if not match:
|
| 1732 |
+
return None
|
| 1733 |
+
total = sum(_HE_VALUES.get(ch, 0) for ch in match.group(1))
|
| 1734 |
+
return str(total) if total else None
|
| 1735 |
+
|
| 1736 |
+
|
| 1737 |
+
def _script_hit_kind(regex: re.Pattern[str]) -> str:
|
| 1738 |
+
if regex is _RU_TITLE_RE or regex is _TH_LAK_RE:
|
| 1739 |
+
return "title"
|
| 1740 |
+
if regex in (
|
| 1741 |
+
_HE_PEREK_RE, _AR_BAB_RE, _TH_HUAT_RE, _CJK_ZHANG_RE, _KO_JANG_RE,
|
| 1742 |
+
_RU_CHAP_RE, _KM_CHAP_RE, _MY_CHAP_RE, _KA_CHAP_RE, _HY_CHAP_RE, _AM_CHAP_RE,
|
| 1743 |
+
_HI_CHAP_RE, _BN_CHAP_RE, _UR_CHAP_RE, _FA_FASL_RE, _NE_CHAP_RE,
|
| 1744 |
+
):
|
| 1745 |
+
return "chapter"
|
| 1746 |
+
if regex in (_HE_HELEK_RE, _AR_KITAB_RE, _CJK_BIAN_RE, _KO_PYEON_RE, _LO_PART_RE, _SR_PART_RE, _HY_MAS_RE):
|
| 1747 |
+
return "part"
|
| 1748 |
+
if regex in (
|
| 1749 |
+
_HE_SIMAN_RE,
|
| 1750 |
+
_HE_TOS_RE,
|
| 1751 |
+
_HE_TAKANA_RE,
|
| 1752 |
+
_HE_PARA_RE,
|
| 1753 |
+
_HE_KATAN_RE,
|
| 1754 |
+
_AR_ANNEX_RE,
|
| 1755 |
+
_AR_PARA_RE,
|
| 1756 |
+
_AR_FASL_RE,
|
| 1757 |
+
_AR_QISM_RE,
|
| 1758 |
+
_AR_FARA_RE,
|
| 1759 |
+
_HY_BAZHIN_RE,
|
| 1760 |
+
_JA_KOU_RE,
|
| 1761 |
+
_ZH_KUAN_RE,
|
| 1762 |
+
_KO_HANG_RE,
|
| 1763 |
+
_KO_HO_RE,
|
| 1764 |
+
_TH_PARA_RE,
|
| 1765 |
+
_TH_KHO_RE,
|
| 1766 |
+
_TH_TON_RE,
|
| 1767 |
+
_FA_TAB_RE,
|
| 1768 |
+
_FA_BAND_RE,
|
| 1769 |
+
_AR_POINT_RE,
|
| 1770 |
+
_CJK_JIE_RE,
|
| 1771 |
+
_KO_JEOL_RE,
|
| 1772 |
+
):
|
| 1773 |
+
return "section"
|
| 1774 |
+
return "article"
|
| 1775 |
+
|
| 1776 |
+
|
| 1777 |
+
def _script_article_number(raw: str) -> str:
|
| 1778 |
+
stripped = raw.strip()
|
| 1779 |
+
for word, num in _AR_POINT_NUM:
|
| 1780 |
+
if stripped.startswith(word):
|
| 1781 |
+
return num
|
| 1782 |
+
compact = raw.strip().strip("()[] \t\u3001\uff08\uff09.、-–—")
|
| 1783 |
+
circled = _circled_to_int(compact)
|
| 1784 |
+
if circled:
|
| 1785 |
+
return circled
|
| 1786 |
+
if compact and len(compact) <= 3:
|
| 1787 |
+
first = compact[0]
|
| 1788 |
+
if first in _HANGUL_GA:
|
| 1789 |
+
return str(_HANGUL_GA.index(first) + 1)
|
| 1790 |
+
if first in _KATA_ENUM:
|
| 1791 |
+
return str(_KATA_ENUM.index(first) + 1)
|
| 1792 |
+
if first in _AR_ABJAD_INDEX:
|
| 1793 |
+
return _AR_ABJAD_INDEX[first]
|
| 1794 |
+
if first in _HE_ALEF:
|
| 1795 |
+
return str(_HE_ALEF.index(first) + 1)
|
| 1796 |
+
if first in _TH_KO:
|
| 1797 |
+
return str(_TH_KO.index(first) + 1)
|
| 1798 |
+
low = first.casefold()
|
| 1799 |
+
if low in _CYR_AB:
|
| 1800 |
+
return str(_CYR_AB.index(low) + 1)
|
| 1801 |
+
if low in _EL_AB:
|
| 1802 |
+
return str(_EL_AB.index(low) + 1)
|
| 1803 |
+
if first in _KA_AB:
|
| 1804 |
+
return str(_KA_AB.index(first) + 1)
|
| 1805 |
+
if first in _HY_AB:
|
| 1806 |
+
return str(_HY_AB.index(first) + 1)
|
| 1807 |
+
cjk_early = _cjk_numeral_value(compact)
|
| 1808 |
+
if cjk_early:
|
| 1809 |
+
return cjk_early
|
| 1810 |
+
he = _hebrew_letter_num(raw)
|
| 1811 |
+
if he:
|
| 1812 |
+
return he
|
| 1813 |
+
digits = _unicode_digit_runs(raw)
|
| 1814 |
+
if digits:
|
| 1815 |
+
if len(digits) >= 2 and re.search(r"[0-9٠-٩۰-۹]+-[0-9٠-٩۰-۹]+", raw):
|
| 1816 |
+
return "-".join(digits[:2])
|
| 1817 |
+
return digits[0]
|
| 1818 |
+
eth = _ethiopic_numeral_value(raw)
|
| 1819 |
+
if eth:
|
| 1820 |
+
return eth
|
| 1821 |
+
compact = re.sub(r"[\s\u0640]+", "", raw)
|
| 1822 |
+
for word, num in _AR_ORDINAL_NUM + _FA_ORDINAL_NUM:
|
| 1823 |
+
needle = re.sub(r"[\s\u0640]+", "", word)
|
| 1824 |
+
if needle and needle in compact:
|
| 1825 |
+
return num
|
| 1826 |
+
cjk = _cjk_numeral_value(compact)
|
| 1827 |
+
if cjk:
|
| 1828 |
+
return cjk
|
| 1829 |
+
tail = re.search(r"([0-9٠-٩۰-۹]+|[IVXLCDM]{1,8})$", compact)
|
| 1830 |
+
if tail:
|
| 1831 |
+
return tail.group(1)
|
| 1832 |
+
return compact
|
| 1833 |
+
|
| 1834 |
+
|
| 1835 |
+
def _in_range_boilerplate(text: str, start: int) -> bool:
|
| 1836 |
+
for regex in (_KO_RANGE_RE, _CJK_RANGE_RE):
|
| 1837 |
+
for match in regex.finditer(text):
|
| 1838 |
+
if match.start() <= start < match.end():
|
| 1839 |
+
return True
|
| 1840 |
+
return False
|
| 1841 |
+
|
| 1842 |
+
|
| 1843 |
+
def _kind_number_from_heading_match(match: re.Match) -> tuple[str, str]:
|
| 1844 |
+
for name in ("title", "chapter", "part", "article", "section"):
|
| 1845 |
+
if match.group(name):
|
| 1846 |
+
return name, (match.group(f"{name}_n") or "").strip()
|
| 1847 |
+
if match.group("section_sym"):
|
| 1848 |
+
return "section", (match.group("section_sym_n") or "").strip()
|
| 1849 |
+
if match.group("section_pre"):
|
| 1850 |
+
return "section", (match.group("section_pre_n") or "").strip()
|
| 1851 |
+
if match.group("grein"):
|
| 1852 |
+
return "article", (match.group("grein_n") or "").strip()
|
| 1853 |
+
if match.group("straipsnis"):
|
| 1854 |
+
return "article", (match.group("straipsnis_n") or "").strip()
|
| 1855 |
+
if match.group("artikulua"):
|
| 1856 |
+
return "article", (match.group("artikulua_n") or "").strip()
|
| 1857 |
+
if match.group("ledd"):
|
| 1858 |
+
return "section", (match.group("ledd_n") or "").strip()
|
| 1859 |
+
if match.group("kap"):
|
| 1860 |
+
return "chapter", (match.group("kap_n") or "").strip()
|
| 1861 |
+
if match.group("luku"):
|
| 1862 |
+
return "chapter", (match.group("luku_n") or "").strip()
|
| 1863 |
+
if match.group("fejezet"):
|
| 1864 |
+
return "chapter", (match.group("fejezet_n") or "").strip()
|
| 1865 |
+
if match.group("peatukk"):
|
| 1866 |
+
return "chapter", (match.group("peatukk_n") or "").strip()
|
| 1867 |
+
if match.group("skyrius"):
|
| 1868 |
+
return "chapter", (match.group("skyrius_n") or "").strip()
|
| 1869 |
+
if match.group("nodala"):
|
| 1870 |
+
return "chapter", (match.group("nodala_n") or "").strip()
|
| 1871 |
+
if match.group("kafli"):
|
| 1872 |
+
return "chapter", (match.group("kafli_n") or "").strip()
|
| 1873 |
+
if match.group("bob"):
|
| 1874 |
+
return "chapter", (match.group("bob_n") or "").strip()
|
| 1875 |
+
if match.group("tarau"):
|
| 1876 |
+
return "chapter", (match.group("tarau_n") or "").strip()
|
| 1877 |
+
if match.group("bolum"):
|
| 1878 |
+
return "chapter", (match.group("bolum_n") or "").strip()
|
| 1879 |
+
if match.group("modda"):
|
| 1880 |
+
return "article", (match.group("modda_n") or "").strip()
|
| 1881 |
+
if match.group("mn"):
|
| 1882 |
+
return "article", (match.group("mn_n") or "").strip()
|
| 1883 |
+
if match.group("kk"):
|
| 1884 |
+
return "article", (match.group("kk_n") or "").strip()
|
| 1885 |
+
if match.group("disp"):
|
| 1886 |
+
return "article", (match.group("disp_n") or "").strip()
|
| 1887 |
+
if match.group("mom"):
|
| 1888 |
+
return "section", (match.group("mom_n") or "").strip()
|
| 1889 |
+
if match.group("order"):
|
| 1890 |
+
return "section", (match.group("order_n") or "").strip()
|
| 1891 |
+
if match.group("kidogo"):
|
| 1892 |
+
return "section", (match.group("kidogo_n") or "").strip()
|
| 1893 |
+
if match.group("esresol"):
|
| 1894 |
+
word = _latin_fold(match.group("esresol") or "").casefold()
|
| 1895 |
+
return "section", {
|
| 1896 |
+
"primero": "1", "segundo": "2", "tercero": "3", "cuarto": "4",
|
| 1897 |
+
"quinto": "5", "sexto": "6", "septimo": "7", "octavo": "8",
|
| 1898 |
+
"noveno": "9", "decimo": "10",
|
| 1899 |
+
"erstens": "1", "zweitens": "2", "drittens": "3", "viertens": "4", "funftens": "5",
|
| 1900 |
+
"premierement": "1", "deuxiemement": "2", "troisiemement": "3",
|
| 1901 |
+
"quatriemement": "4", "cinquiemement": "5",
|
| 1902 |
+
}.get(word, word)
|
| 1903 |
+
return "", ""
|
| 1904 |
+
|
| 1905 |
+
|
| 1906 |
+
@dataclass
|
| 1907 |
+
class _Hit:
|
| 1908 |
+
start: int
|
| 1909 |
+
kind: str
|
| 1910 |
+
number: str
|
| 1911 |
+
heading: str
|
| 1912 |
+
|
| 1913 |
+
|
| 1914 |
+
_PAREN_XREF_RE = re.compile(
|
| 1915 |
+
r"(?i)^\s*(?:\([a-z0-9]{1,4}\))?\s+"
|
| 1916 |
+
r"(?:is|are|or|and|of|have|has|was|were|by|to|for|from|in|that|shall)\b"
|
| 1917 |
+
)
|
| 1918 |
+
|
| 1919 |
+
|
| 1920 |
+
def _paren_letter_xref(raw: str, number: str, rest: str) -> bool:
|
| 1921 |
+
"""Skip 'paragraph (i) or …' / 'subsection (l)(b) is …' cross-references."""
|
| 1922 |
+
if len(number) != 1 or not number.isalpha() or "(" not in raw:
|
| 1923 |
+
return False
|
| 1924 |
+
return _PAREN_XREF_RE.match(rest) is not None
|
| 1925 |
+
|
| 1926 |
+
|
| 1927 |
+
def _collect_hits(text: str, *, language: str, latin: bool) -> list[_Hit]:
|
| 1928 |
+
hits: list[_Hit] = []
|
| 1929 |
+
folded = _latin_fold(text) if latin else text
|
| 1930 |
+
if latin:
|
| 1931 |
+
for match in _HEADING_RE.finditer(folded):
|
| 1932 |
+
kind, number = _kind_number_from_heading_match(match)
|
| 1933 |
+
if not kind:
|
| 1934 |
+
continue
|
| 1935 |
+
if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]):
|
| 1936 |
+
continue
|
| 1937 |
+
if _paren_letter_xref(match.group(0), number, folded[match.end() : match.end() + 48]):
|
| 1938 |
+
continue
|
| 1939 |
+
for gname in (
|
| 1940 |
+
"title_n", "chapter_n", "part_n", "article_n", "section_n",
|
| 1941 |
+
"section_sym_n", "section_pre_n", "grein_n", "straipsnis_n",
|
| 1942 |
+
"artikulua_n", "ledd_n", "kap_n", "luku_n",
|
| 1943 |
+
"fejezet_n", "peatukk_n", "skyrius_n", "nodala_n",
|
| 1944 |
+
"kafli_n", "bob_n", "tarau_n", "bolum_n",
|
| 1945 |
+
"modda_n", "mn_n", "kk_n", "mom_n", "order_n", "kidogo_n", "disp_n",
|
| 1946 |
+
):
|
| 1947 |
+
try:
|
| 1948 |
+
start, end = match.span(gname)
|
| 1949 |
+
except IndexError:
|
| 1950 |
+
continue
|
| 1951 |
+
if start >= 0:
|
| 1952 |
+
number = text[start:end]
|
| 1953 |
+
break
|
| 1954 |
+
number = _fold_digits_in_number(number.strip().rstrip(".-:–—"))
|
| 1955 |
+
line_end = text.find("\n", match.start())
|
| 1956 |
+
if line_end < 0:
|
| 1957 |
+
line_end = len(text)
|
| 1958 |
+
heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
|
| 1959 |
+
hits.append(_Hit(match.start(), kind, number, heading))
|
| 1960 |
+
for match in _lexicon_heading_re().finditer(folded):
|
| 1961 |
+
if _CITE_TAIL_RE.match(folded[match.end() : match.end() + 48]):
|
| 1962 |
+
continue
|
| 1963 |
+
token = (match.group("lex") or "").casefold()
|
| 1964 |
+
kind = _LEXICON_KIND.get(token, "article")
|
| 1965 |
+
start, end = match.span("lex_n")
|
| 1966 |
+
number = _fold_digits_in_number(
|
| 1967 |
+
(text[start:end] if start >= 0 else match.group("lex_n") or "").strip().rstrip(".-:–—")
|
| 1968 |
+
)
|
| 1969 |
+
if not number:
|
| 1970 |
+
continue
|
| 1971 |
+
line_end = text.find("\n", match.start())
|
| 1972 |
+
if line_end < 0:
|
| 1973 |
+
line_end = len(text)
|
| 1974 |
+
heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
|
| 1975 |
+
hits.append(_Hit(match.start(), kind, number, heading))
|
| 1976 |
+
for match in _LATIN_LETTER_RE.finditer(text):
|
| 1977 |
+
letter = match.group("paren") or match.group("bare")
|
| 1978 |
+
if letter:
|
| 1979 |
+
number = str(ord(letter) - 96)
|
| 1980 |
+
else:
|
| 1981 |
+
number = _ROMAN_LOWER.get(match.group("roman") or "", "")
|
| 1982 |
+
if not number:
|
| 1983 |
+
continue
|
| 1984 |
+
line_end = text.find("\n", match.start())
|
| 1985 |
+
if line_end < 0:
|
| 1986 |
+
line_end = len(text)
|
| 1987 |
+
heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
|
| 1988 |
+
hits.append(_Hit(match.start(), "section", number, heading))
|
| 1989 |
+
for match in _LATIN_NUM_LIST_RE.finditer(text):
|
| 1990 |
+
number = (
|
| 1991 |
+
match.group("nparen")
|
| 1992 |
+
or match.group("nclose")
|
| 1993 |
+
or match.group("nord")
|
| 1994 |
+
or match.group("ndot")
|
| 1995 |
+
or match.group("ncolon")
|
| 1996 |
+
or match.group("ndash")
|
| 1997 |
+
or ""
|
| 1998 |
+
)
|
| 1999 |
+
dbl = match.group("dbl")
|
| 2000 |
+
if dbl:
|
| 2001 |
+
number = str(ord(dbl[0]) - 96)
|
| 2002 |
+
if not number:
|
| 2003 |
+
continue
|
| 2004 |
+
line_end = text.find("\n", match.start())
|
| 2005 |
+
if line_end < 0:
|
| 2006 |
+
line_end = len(text)
|
| 2007 |
+
heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
|
| 2008 |
+
hits.append(_Hit(match.start(), "section", number, heading))
|
| 2009 |
+
for i, match in enumerate(_BULLET_RE.finditer(text), start=1):
|
| 2010 |
+
line_end = text.find("\n", match.start())
|
| 2011 |
+
if line_end < 0:
|
| 2012 |
+
line_end = len(text)
|
| 2013 |
+
heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
|
| 2014 |
+
hits.append(_Hit(match.start(), "section", str(i), heading))
|
| 2015 |
+
for match in _DASH_NUM_RE.finditer(text):
|
| 2016 |
+
number = (match.group("bn") or "").strip()
|
| 2017 |
+
if not number:
|
| 2018 |
+
continue
|
| 2019 |
+
line_end = text.find("\n", match.start())
|
| 2020 |
+
if line_end < 0:
|
| 2021 |
+
line_end = len(text)
|
| 2022 |
+
heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
|
| 2023 |
+
hits.append(_Hit(match.start(), "section", number, heading))
|
| 2024 |
+
for regex in _detected_script_regexes(text, language):
|
| 2025 |
+
for match in regex.finditer(text):
|
| 2026 |
+
if _in_range_boilerplate(text, match.start()):
|
| 2027 |
+
continue
|
| 2028 |
+
if _SCRIPT_CITE_TAIL_RE.match(text[match.end() : match.end() + 48]):
|
| 2029 |
+
continue
|
| 2030 |
+
raw = match.group(0)
|
| 2031 |
+
number = _fold_digits_in_number(_script_article_number(raw))
|
| 2032 |
+
heading = re.sub(r"\s+", " ", raw).strip()[:240]
|
| 2033 |
+
hits.append(_Hit(match.start(), _script_hit_kind(regex), number, heading))
|
| 2034 |
+
if latin:
|
| 2035 |
+
from .profiles import iso_lang
|
| 2036 |
+
|
| 2037 |
+
for match in _MARGINAL_NOTE_RE.finditer(text):
|
| 2038 |
+
word = _latin_fold(match.group("marginal") or "").casefold().rstrip(".")
|
| 2039 |
+
if not word or word in _MARGINAL_STOP:
|
| 2040 |
+
continue
|
| 2041 |
+
number = _fold_digits_in_number((match.group("marginal_n") or "").strip())
|
| 2042 |
+
if not number:
|
| 2043 |
+
continue
|
| 2044 |
+
line_end = text.find("\n", match.start())
|
| 2045 |
+
if line_end < 0:
|
| 2046 |
+
line_end = len(text)
|
| 2047 |
+
heading = re.sub(r"\s+", " ", text[match.start() : line_end]).strip()[:240]
|
| 2048 |
+
hits.append(_Hit(match.start(), "section", number, heading))
|
| 2049 |
+
lang = iso_lang(language)
|
| 2050 |
+
keyword_hits = [
|
| 2051 |
+
hit
|
| 2052 |
+
for hit in hits
|
| 2053 |
+
if hit.kind in {"article", "section"} and not _PAREN_SUBSECTION_RE.match(hit.heading.lstrip())
|
| 2054 |
+
]
|
| 2055 |
+
if len(keyword_hits) < MIN_SPLIT_HEADINGS and lang in _CW_NUM_LANGS:
|
| 2056 |
+
for match in _CW_NUM_RE.finditer(text):
|
| 2057 |
+
number = (match.group("cw_n") or "").strip()
|
| 2058 |
+
if not _plausible_cw_number(number):
|
| 2059 |
+
continue
|
| 2060 |
+
if _MONTH_START_RE.match(text[match.end() : match.end() + 16]):
|
| 2061 |
+
continue
|
| 2062 |
+
hits.append(
|
| 2063 |
+
_Hit(
|
| 2064 |
+
match.start(),
|
| 2065 |
+
"section",
|
| 2066 |
+
number,
|
| 2067 |
+
match.group(0).strip()[:240],
|
| 2068 |
+
)
|
| 2069 |
+
)
|
| 2070 |
+
hits.sort(key=lambda h: (h.start, -len(h.heading)))
|
| 2071 |
+
merged: list[_Hit] = []
|
| 2072 |
+
seen_starts: set[int] = set()
|
| 2073 |
+
for hit in hits:
|
| 2074 |
+
if hit.start in seen_starts:
|
| 2075 |
+
continue
|
| 2076 |
+
seen_starts.add(hit.start)
|
| 2077 |
+
merged.append(hit)
|
| 2078 |
+
return _drop_parenthetical_subsections(merged)
|
| 2079 |
+
|
| 2080 |
+
|
| 2081 |
+
def _drop_parenthetical_subsections(hits: list[_Hit]) -> list[_Hit]:
|
| 2082 |
+
"""Keep ``(1)`` on the parent clause when a real section heading exists."""
|
| 2083 |
+
|
| 2084 |
+
parents = [
|
| 2085 |
+
hit
|
| 2086 |
+
for hit in hits
|
| 2087 |
+
if hit.kind in {"article", "section"}
|
| 2088 |
+
and not _PAREN_SUBSECTION_RE.match(hit.heading.lstrip())
|
| 2089 |
+
]
|
| 2090 |
+
if not parents:
|
| 2091 |
+
return hits
|
| 2092 |
+
return [
|
| 2093 |
+
hit
|
| 2094 |
+
for hit in hits
|
| 2095 |
+
if not (hit.kind == "section" and _PAREN_SUBSECTION_RE.match(hit.heading.lstrip()))
|
| 2096 |
+
]
|
| 2097 |
+
|
| 2098 |
+
|
| 2099 |
+
def _units_from_hits(text: str, hits: list[_Hit]) -> list[StructureUnit]:
|
| 2100 |
+
if not hits:
|
| 2101 |
+
return [
|
| 2102 |
+
StructureUnit(kind="preamble", number="", heading="", body=text, char_start=0, char_end=len(text))
|
| 2103 |
+
]
|
| 2104 |
+
cursor = {"title": "", "chapter": "", "part": "", "article": "", "section": ""}
|
| 2105 |
+
units: list[StructureUnit] = []
|
| 2106 |
+
if hits[0].start > 0:
|
| 2107 |
+
units.append(
|
| 2108 |
+
StructureUnit(
|
| 2109 |
+
kind="preamble",
|
| 2110 |
+
number="",
|
| 2111 |
+
heading="",
|
| 2112 |
+
body=text[0 : hits[0].start],
|
| 2113 |
+
char_start=0,
|
| 2114 |
+
char_end=hits[0].start,
|
| 2115 |
+
)
|
| 2116 |
+
)
|
| 2117 |
+
for i, hit in enumerate(hits):
|
| 2118 |
+
start = hit.start
|
| 2119 |
+
end = hits[i + 1].start if i + 1 < len(hits) else len(text)
|
| 2120 |
+
body = text[start:end]
|
| 2121 |
+
cursor[hit.kind] = hit.number
|
| 2122 |
+
for lower, rank in _KIND_RANK.items():
|
| 2123 |
+
if rank > _KIND_RANK.get(hit.kind, 99):
|
| 2124 |
+
cursor[lower] = ""
|
| 2125 |
+
units.append(
|
| 2126 |
+
StructureUnit(
|
| 2127 |
+
kind=hit.kind,
|
| 2128 |
+
number=hit.number,
|
| 2129 |
+
heading=hit.heading[:240],
|
| 2130 |
+
body=body,
|
| 2131 |
+
title_number=cursor["title"],
|
| 2132 |
+
chapter_number=cursor["chapter"],
|
| 2133 |
+
part_number=cursor["part"],
|
| 2134 |
+
article_number=cursor["article"],
|
| 2135 |
+
section_number=cursor["section"],
|
| 2136 |
+
subsections=_subsection_tokens(body),
|
| 2137 |
+
hierarchy_path=_cursor_path(cursor),
|
| 2138 |
+
char_start=start,
|
| 2139 |
+
char_end=end,
|
| 2140 |
+
)
|
| 2141 |
+
)
|
| 2142 |
+
return units
|
| 2143 |
+
|
| 2144 |
+
|
| 2145 |
+
def segment_exclusive(text: str, *, language: str = "") -> list[StructureUnit]:
|
| 2146 |
+
"""Internal exclusive-span segmentation of *text* (includes preamble)."""
|
| 2147 |
+
from .profiles import iso_lang, latin_split_allowed
|
| 2148 |
+
|
| 2149 |
+
if not text:
|
| 2150 |
+
return []
|
| 2151 |
+
latin = not language or latin_split_allowed(language)
|
| 2152 |
+
hits = _collect_hits(text, language=language, latin=latin)
|
| 2153 |
+
retrieval_like = [h for h in hits if h.kind in {"article", "section"}]
|
| 2154 |
+
if (
|
| 2155 |
+
not latin
|
| 2156 |
+
and len(retrieval_like) < MIN_SPLIT_HEADINGS
|
| 2157 |
+
and iso_lang(language) in _LATIN_FALLBACK_LANGS
|
| 2158 |
+
):
|
| 2159 |
+
hits = _collect_hits(text, language=language, latin=True)
|
| 2160 |
+
return _units_from_hits(text, hits)
|
| 2161 |
+
|
| 2162 |
+
|
| 2163 |
+
def split_script_units(text: str, language: str) -> list[StructureUnit]:
|
| 2164 |
+
"""Retrieval projection of script-specific exclusive spans."""
|
| 2165 |
+
internal = segment_exclusive(text, language=language)
|
| 2166 |
+
retrieval = [u for u in internal if u.kind == "article" and len(u.body.strip()) >= 16]
|
| 2167 |
+
return retrieval if len(retrieval) >= MIN_SPLIT_HEADINGS else []
|
| 2168 |
+
|
| 2169 |
+
|
| 2170 |
+
def split_structured_units(text: str, *, language: str = "") -> list[StructureUnit]:
|
| 2171 |
+
"""Retrieval units. Empty list means keep the whole instrument.
|
| 2172 |
+
|
| 2173 |
+
Prefers article/section. When those are scarce, numbered chapter then title
|
| 2174 |
+
headings (Cameroon CHAPITRE, Bolivia TÍTULO, Cape Verde CAPÍTULO).
|
| 2175 |
+
"""
|
| 2176 |
+
if not text or len(text) < 16:
|
| 2177 |
+
return []
|
| 2178 |
+
from .profiles import latin_split_allowed
|
| 2179 |
+
|
| 2180 |
+
internal = segment_exclusive(text, language=language)
|
| 2181 |
+
|
| 2182 |
+
def _take(kinds: set[str]) -> list[StructureUnit]:
|
| 2183 |
+
out: list[StructureUnit] = []
|
| 2184 |
+
for u in internal:
|
| 2185 |
+
if u.kind not in kinds:
|
| 2186 |
+
continue
|
| 2187 |
+
min_len = 16 if u.number else MIN_UNIT_CHARS
|
| 2188 |
+
if language and not latin_split_allowed(language):
|
| 2189 |
+
min_len = 16
|
| 2190 |
+
if len(u.body.strip()) >= min_len:
|
| 2191 |
+
out.append(u)
|
| 2192 |
+
return out
|
| 2193 |
+
|
| 2194 |
+
for kinds in (
|
| 2195 |
+
{"article", "section"},
|
| 2196 |
+
{"chapter"},
|
| 2197 |
+
{"part"},
|
| 2198 |
+
{"title"},
|
| 2199 |
+
):
|
| 2200 |
+
retrieval = _take(kinds)
|
| 2201 |
+
if len(retrieval) >= MIN_SPLIT_HEADINGS:
|
| 2202 |
+
return retrieval
|
| 2203 |
+
return []
|