|
|
|
|
|
import pandas as pd |
|
|
import numpy as np |
|
|
import json |
|
|
import pickle |
|
|
from pathlib import Path |
|
|
from datasets import load_dataset |
|
|
from typing import Dict, List, Tuple, Optional |
|
|
import networkx as nx |
|
|
|
|
|
class ProcessedLegalDatabaseLoader: |
|
|
""" |
|
|
Efficient loader for preprocessed Indonesian legal database |
|
|
""" |
|
|
|
|
|
def __init__(self, repo_or_path: str, local_mode: bool = False): |
|
|
""" |
|
|
Initialize loader |
|
|
|
|
|
Args: |
|
|
repo_or_path: HuggingFace repo ID or local path |
|
|
local_mode: If True, load from local files |
|
|
""" |
|
|
self.repo_or_path = repo_or_path |
|
|
self.local_mode = local_mode |
|
|
self.df = None |
|
|
self.embeddings = None |
|
|
self.tfidf_components = None |
|
|
self.knowledge_graph = None |
|
|
self.config = None |
|
|
|
|
|
def load_database(self) -> pd.DataFrame: |
|
|
"""Load main database""" |
|
|
if self.local_mode: |
|
|
db_path = Path(self.repo_or_path) / "processed_legal_database.parquet" |
|
|
self.df = pd.read_parquet(db_path) |
|
|
else: |
|
|
dataset = load_dataset(self.repo_or_path, split='train') |
|
|
self.df = dataset.to_pandas() |
|
|
|
|
|
|
|
|
self.df['kg_entities'] = self.df['kg_entities'].apply( |
|
|
lambda x: json.loads(x) if isinstance(x, str) else x |
|
|
) |
|
|
self.df['kg_concepts'] = self.df['kg_concepts'].apply( |
|
|
lambda x: json.loads(x) if isinstance(x, str) else x |
|
|
) |
|
|
|
|
|
print(f"Database loaded: {len(self.df)} records") |
|
|
return self.df |
|
|
|
|
|
def load_embeddings(self) -> np.ndarray: |
|
|
"""Load embeddings array""" |
|
|
if self.local_mode: |
|
|
emb_path = Path(self.repo_or_path) / "embeddings.npy" |
|
|
self.embeddings = np.load(emb_path) |
|
|
else: |
|
|
|
|
|
if self.df is None: |
|
|
self.load_database() |
|
|
|
|
|
embeddings_list = [] |
|
|
for embedding in self.df['embedding']: |
|
|
if isinstance(embedding, list): |
|
|
embeddings_list.append(np.array(embedding, dtype=np.float32)) |
|
|
else: |
|
|
embeddings_list.append(embedding) |
|
|
|
|
|
self.embeddings = np.vstack(embeddings_list) |
|
|
|
|
|
print(f"Embeddings loaded: {self.embeddings.shape}") |
|
|
return self.embeddings |
|
|
|
|
|
def load_tfidf_components(self) -> Dict: |
|
|
"""Load TF-IDF components""" |
|
|
if self.local_mode: |
|
|
tfidf_path = Path(self.repo_or_path) / "tfidf_components.pkl" |
|
|
with open(tfidf_path, 'rb') as f: |
|
|
self.tfidf_components = pickle.load(f) |
|
|
else: |
|
|
print("TF-IDF components only available in local mode") |
|
|
return None |
|
|
|
|
|
print("TF-IDF components loaded") |
|
|
return self.tfidf_components |
|
|
|
|
|
def load_knowledge_graph(self) -> nx.DiGraph: |
|
|
"""Load knowledge graph""" |
|
|
if self.local_mode: |
|
|
kg_path = Path(self.repo_or_path) / "knowledge_graph.json" |
|
|
else: |
|
|
|
|
|
from huggingface_hub import hf_hub_download |
|
|
kg_path = hf_hub_download( |
|
|
repo_id=self.repo_or_path, |
|
|
filename="knowledge_graph.json", |
|
|
repo_type="dataset" |
|
|
) |
|
|
|
|
|
with open(kg_path, 'r', encoding='utf-8') as f: |
|
|
kg_data = json.load(f) |
|
|
|
|
|
self.knowledge_graph = nx.node_link_graph(kg_data['graph']) |
|
|
|
|
|
print(f"Knowledge graph loaded: {self.knowledge_graph.number_of_nodes()} nodes, {self.knowledge_graph.number_of_edges()} edges") |
|
|
return self.knowledge_graph |
|
|
|
|
|
def load_config(self) -> Dict: |
|
|
"""Load configuration""" |
|
|
if self.local_mode: |
|
|
config_path = Path(self.repo_or_path) / "config.json" |
|
|
else: |
|
|
from huggingface_hub import hf_hub_download |
|
|
config_path = hf_hub_download( |
|
|
repo_id=self.repo_or_path, |
|
|
filename="config.json", |
|
|
repo_type="dataset" |
|
|
) |
|
|
|
|
|
with open(config_path, 'r', encoding='utf-8') as f: |
|
|
self.config = json.load(f) |
|
|
|
|
|
print("Configuration loaded") |
|
|
return self.config |
|
|
|
|
|
def load_all(self) -> Tuple[pd.DataFrame, np.ndarray, Dict, nx.DiGraph, Dict]: |
|
|
"""Load all components""" |
|
|
database = self.load_database() |
|
|
embeddings = self.load_embeddings() |
|
|
tfidf = self.load_tfidf_components() |
|
|
kg = self.load_knowledge_graph() |
|
|
config = self.load_config() |
|
|
|
|
|
return database, embeddings, tfidf, kg, config |
|
|
|
|
|
def get_statistics(self) -> Dict: |
|
|
"""Get database statistics""" |
|
|
if self.df is None: |
|
|
self.load_database() |
|
|
|
|
|
stats = { |
|
|
'total_records': len(self.df), |
|
|
'unique_regulation_types': self.df['regulation_type'].nunique(), |
|
|
'date_range': f"{self.df['year'].min()} - {self.df['year'].max()}", |
|
|
'avg_authority_score': self.df['authority_score'].mean(), |
|
|
'avg_temporal_score': self.df['temporal_score'].mean(), |
|
|
'avg_legal_richness': self.df['legal_richness'].mean(), |
|
|
'avg_kg_connectivity': self.df['kg_connectivity'].mean(), |
|
|
'embedding_dim': self.df['embedding_dim'].iloc[0] if 'embedding_dim' in self.df.columns else None |
|
|
} |
|
|
|
|
|
return stats |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|