File size: 11,069 Bytes
474bad4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
import pandas as pd
import re
from pathlib import Path
from typing import List, Dict, Optional, Union

class OldEnglishDictionary:
    """A class to query the aligned Old English Dictionary dataset."""
    
    def __init__(self, data_path: str = "data/unified_index.tab"):
        """Initialize the dictionary with the unified index.
        
        Args:
            data_path: Path to the unified_index.tab file
        """
        self.data_path = Path(data_path)
        self.df = pd.read_csv(self.data_path, sep='\t')
        
        # Fill NaN values with empty strings for easier processing
        self.df = self.df.fillna('')
        
        # Create lowercase versions of key columns for case-insensitive search
        self.df['canonical_key_lower'] = self.df['canonical_key'].str.lower()
        self.df['normalised_form_lower'] = self.df['normalised_form'].str.lower()
        
        # Dictionary sources
        self.sources = ['BT', 'CH', 'Sweet', 'DOE', 'ParCorOE']
        
        # Count total entries
        self.total_entries = len(self.df)
        print(f"Loaded {self.total_entries} aligned entries from {self.data_path}")
    
    def search(self, query: str, 
               mode: str = 'canonical', 
               exact: bool = False, 
               pos: Optional[str] = None, 
               source: Optional[str] = None) -> pd.DataFrame:
        """Search for entries matching the query.
        
        Args:
            query: The search term
            mode: Search mode ('canonical', 'normalised', 'headword')
            exact: If True, match the entire term; if False, use substring matching
            pos: Filter by part of speech
            source: Filter by dictionary source
            
        Returns:
            DataFrame with matching entries
        """
        query = query.lower()
        
        # Base query logic
        if mode == 'canonical':
            if exact:
                results = self.df[self.df['canonical_key_lower'] == query]
            else:
                results = self.df[self.df['canonical_key_lower'].str.contains(query, regex=False)]
        
        elif mode == 'normalised':
            if exact:
                results = self.df[self.df['normalised_form_lower'] == query]
            else:
                results = self.df[self.df['normalised_form_lower'].str.contains(query, regex=False)]
        
        elif mode == 'headword':
            # Search across all dictionary headword columns
            mask = pd.Series(False, index=self.df.index)
            for source in self.sources:
                col = f"{source}_headword"
                if col in self.df.columns:
                    if exact:
                        mask |= (self.df[col].str.lower() == query)
                    else:
                        mask |= (self.df[col].str.lower().str.contains(query, regex=False, na=False))
            results = self.df[mask]
            
        else:
            raise ValueError(f"Invalid search mode: {mode}. Use 'canonical', 'normalised', or 'headword'.")
        
        # Apply filters
        if pos:
            results = results[results['POS'].str.lower() == pos.lower()]
            
        if source:
            col = f"{source}_headword"
            if col in self.df.columns:
                results = results[results[col] != '']
            else:
                raise ValueError(f"Invalid source: {source}. Use one of {self.sources}")
        
        return results
    
    def display_entry(self, entry: pd.Series) -> None:
        """Display a single dictionary entry in a readable format.
        
        Args:
            entry: A single row from the dataframe
        """
        print("\n" + "=" * 80)
        print(f"CANONICAL KEY: {entry['canonical_key']}")
        print(f"NORMALIZED FORM: {entry['normalised_form']}")
        print(f"MATCH TYPE: {entry['match_type']}")
        if entry['POS']:
            print(f"PART OF SPEECH: {entry['POS']}")
        if entry['Gloss']:
            print(f"GLOSS: {entry['Gloss']}")
        print("-" * 80)
        
        print("DICTIONARY HEADWORDS:")
        for source in self.sources:
            col = f"{source}_headword"
            if col in entry and entry[col]:
                print(f"  {source}: {entry[col]}")
        print("=" * 80)
    
    def display_results(self, results: pd.DataFrame, limit: int = 10) -> None:
        """Display search results in a readable format.
        
        Args:
            results: DataFrame containing search results
            limit: Maximum number of results to display
        """
        num_results = len(results)
        
        if num_results == 0:
            print("No matching entries found.")
            return
        
        print(f"\nFound {num_results} matching entries.")
        
        if num_results > limit:
            print(f"Displaying first {limit} results.")
            results = results.head(limit)
        
        for _, entry in results.iterrows():
            self.display_entry(entry)
    
    def find_similar(self, query: str, method: str = 'sound') -> pd.DataFrame:
        """Find entries similar to the query using various similarity methods.
        
        Args:
            query: The search term
            method: The similarity method ('sound', 'edit', 'prefix')
            
        Returns:
            DataFrame with similar entries
        """
        query = query.lower()
        
        if method == 'sound':
            # Apply Ellis vocalic transformations similar to those used in alignment
            variations = self._generate_ellis_variations(query)
            mask = pd.Series(False, index=self.df.index)
            for variation in variations:
                mask |= (self.df['canonical_key_lower'] == variation)
            return self.df[mask]
            
        elif method == 'edit':
            # Crude edit distance approximation - finding entries 
            # that share at least half their characters with the query
            query_set = set(query)
            results = []
            
            for idx, row in self.df.iterrows():
                canonical = row['canonical_key_lower']
                # Skip very short terms or terms with big length difference
                if len(canonical) < 3 or abs(len(canonical) - len(query)) > 3:
                    continue
                
                canonical_set = set(canonical)
                intersection = len(query_set.intersection(canonical_set))
                union = len(query_set.union(canonical_set))
                
                # Jaccard similarity threshold
                if intersection / union > 0.6:
                    results.append(idx)
            
            return self.df.loc[results]
            
        elif method == 'prefix':
            # Find entries that start with the query
            return self.df[self.df['canonical_key_lower'].str.startswith(query)]
            
        else:
            raise ValueError(f"Invalid method: {method}. Use 'sound', 'edit', or 'prefix'.")
    
    def _generate_ellis_variations(self, word: str) -> List[str]:
        """Generate variations based on Ellis vocalic correspondences.
        
        Args:
            word: The input word
            
        Returns:
            List of phonologically plausible variations
        """
        variations = [word]
        
        # Ellis vocalic correspondences
        transformations = [
            (r'ie', r'y'),    # fierd/fyrd
            (r'y', r'ie'),    # fyrd/fierd
            (r'ie', r'i'),    # diere/dire
            (r'i', r'ie'),    # diren/dieren
            (r'io', r'eo'),   # bion/beon
            (r'eo', r'io'),   # beorht/biorht
            (r'on', r'an'),   # monig/manig
            (r'an', r'on'),   # manig/monig
            (r'om', r'am'),   # from/fram
            (r'am', r'om'),   # fram/from
            (r'rg', r'rh'),   # burg/burh
            (r'rh', r'rg'),   # burh/burg
            (r'ea', r'a'),    # eald/ald
            (r'a', r'ea'),    # ald/eald
            (r'eo', r'e')     # eofot/efot
        ]
        
        for pattern, replacement in transformations:
            if pattern in word:
                variations.append(word.replace(pattern, replacement))
        
        return variations

    def get_statistics(self) -> Dict[str, Union[int, float]]:
        """Get statistics about the dictionary dataset.
        
        Returns:
            Dictionary with statistics
        """
        stats = {
            "total_entries": self.total_entries,
            "multi_source_entries": len(self.df[self.df['match_type'] != 'single']),
            "exact_matches": len(self.df[self.df['match_type'] == 'exact']),
            "ellis_matches": len(self.df[self.df['match_type'] == 'ellis_vocalic']),
            "single_source": len(self.df[self.df['match_type'] == 'single'])
        }
        
        # Add source-specific counts
        for source in self.sources:
            col = f"{source}_headword"
            if col in self.df.columns:
                stats[f"{source}_entries"] = len(self.df[self.df[col] != ''])
        
        # Add POS distribution
        pos_counts = self.df['POS'].value_counts().to_dict()
        stats["pos_distribution"] = pos_counts
        
        return stats


# Example usage
if __name__ == "__main__":
    oe_dict = OldEnglishDictionary()
    
    # Simple demo of the search functionality
    print("\n=== SEARCH DEMONSTRATION ===")
    
    # Search by canonical key
    print("\nSearching for entries with canonical key containing 'abelgan'...")
    results = oe_dict.search("abelgan", mode="canonical")
    oe_dict.display_results(results)
    
    # Search by normalized form
    print("\nSearching for entries with normalized form containing 'ābēodan'...")
    results = oe_dict.search("ābēodan", mode="normalised", exact=True)
    oe_dict.display_results(results)
    
    # Search by headword across all dictionaries
    print("\nSearching for entries where any dictionary has headword containing 'cyning'...")
    results = oe_dict.search("cyning", mode="headword")
    oe_dict.display_results(results, limit=5)
    
    # Filter by part of speech
    print("\nSearching for noun entries with canonical key containing 'helm'...")
    results = oe_dict.search("helm", mode="canonical", pos="N")
    oe_dict.display_results(results, limit=5)
    
    # Find similar words
    print("\nFinding entries similar to 'beon' using sound correspondences...")
    results = oe_dict.find_similar("beon", method="sound")
    oe_dict.display_results(results)
    
    # Show dictionary statistics
    stats = oe_dict.get_statistics()
    print("\n=== DICTIONARY STATISTICS ===")
    for key, value in stats.items():
        if key != "pos_distribution":
            print(f"{key}: {value}")
    
    print("\nPart of Speech Distribution:")
    for pos, count in stats["pos_distribution"].items():
        if pos:  # Skip empty POS
            print(f"  {pos}: {count}")