File size: 5,718 Bytes
923ad88
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

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()
            
            # Convert JSON strings back to objects
            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:
            # Extract from DataFrame
            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:
            # Download from HuggingFace
            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

# Example usage:
# loader = ProcessedLegalDatabaseLoader("your-username/indonesian-legal-rag-processed")
# df, embeddings, tfidf, kg, config = loader.load_all()