File size: 8,430 Bytes
bda2b5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Chapter-level structural analysis for Tibetan legal manuscripts.
Provides differential highlighting, change detection, and structural alignment.
"""

import difflib
import re


def detect_structural_changes(text1: str, text2: str, 
                           min_change_length: int = 5,
                           context_window: int = 10) -> dict:
    """
    Detect structural changes between two Tibetan text chapters.
    
    Args:
        text1: First text chapter
        text2: Second text chapter
        min_change_length: Minimum length of change to report
        context_window: Number of characters to include as context
        
    Returns:
        Dictionary with detected changes: insertions, deletions, modifications
    """
    
    # Clean texts for comparison
    def clean_text(text):
        # Remove extra whitespace and normalize
        text = re.sub(r'\s+', ' ', text.strip())
        return text
    
    clean1 = clean_text(text1)
    clean2 = clean_text(text2)
    
    # Use difflib to detect changes
    differ = difflib.Differ()
    diff = list(differ.compare(clean1.split(), clean2.split()))
    
    changes = {
        'insertions': [],
        'deletions': [],
        'modifications': [],
        'unchanged': []
    }
    
    # Track current position in both texts
    pos1 = 0
    pos2 = 0
    
    for i, line in enumerate(diff):
        if line.startswith('  '):  # Unchanged
            word = line[2:]
            changes['unchanged'].append({
                'word': word,
                'position1': pos1,
                'position2': pos2,
                'length': len(word)
            })
            pos1 += len(word) + 1
            pos2 += len(word) + 1
            
        elif line.startswith('- '):  # Deletion
            word = line[2:]
            if len(word) >= min_change_length:
                changes['deletions'].append({
                    'word': word,
                    'position': pos1,
                    'length': len(word),
                    'context': get_context(clean1, pos1, context_window)
                })
            pos1 += len(word) + 1
            
        elif line.startswith('+ '):  # Insertion
            word = line[2:]
            if len(word) >= min_change_length:
                changes['insertions'].append({
                    'word': word,
                    'position': pos2,
                    'length': len(word),
                    'context': get_context(clean2, pos2, context_window)
                })
            pos2 += len(word) + 1
    
    # Detect modifications (adjacent deletions and insertions)
    modifications = detect_modifications(changes['deletions'], changes['insertions'])
    changes['modifications'] = modifications
    
    return changes


def get_context(text: str, position: int, window: int) -> str:
    """Get context around a position in text."""
    start = max(0, position - window)
    end = min(len(text), position + window)
    return text[start:end]


def detect_modifications(deletions: list[dict], insertions: list[dict]) -> list[dict]:
    """Detect modifications by pairing nearby deletions and insertions."""
    modifications = []
    
    for deletion in deletions[:]:  # Copy to avoid modification during iteration
        for insertion in insertions[:]:
            # If deletion and insertion are close (within 5 positions)
            if abs(deletion['position'] - insertion['position']) <= 5:
                modifications.append({
                    'original': deletion['word'],
                    'replacement': insertion['word'],
                    'position': deletion['position'],
                    'deletion_context': deletion['context'],
                    'insertion_context': insertion['context']
                })
                # Remove from original lists to avoid duplicates
                if deletion in deletions:
                    deletions.remove(deletion)
                if insertion in insertions:
                    insertions.remove(insertion)
                break
    
    return modifications


def generate_structural_alignment(text1: str, text2: str) -> dict[str, list]:
    """
    Generate structural alignment between two text chapters.
    
    Returns:
        Dictionary with alignment information including gaps and matches
    """
    
    # Split into sentences or clauses for alignment
    def split_into_segments(text):
        # Split on Tibetan punctuation
        segments = re.split(r'[།༎༏༐༑༔]', text)
        return [seg.strip() for seg in segments if seg.strip()]
    
    segments1 = split_into_segments(text1)
    segments2 = split_into_segments(text2)
    
    # Create alignment using sequence matcher
    matcher = difflib.SequenceMatcher(None, segments1, segments2)
    
    alignment = {
        'matches': [],
        'gaps': [],
        'mismatches': [],
        'segments1': segments1,
        'segments2': segments2
    }
    
    for tag, i1, i2, j1, j2 in matcher.get_opcodes():
        if tag == 'equal':
            alignment['matches'].append({
                'segments1': segments1[i1:i2],
                'segments2': segments2[j1:j2],
                'type': 'match'
            })
        elif tag == 'delete':
            alignment['gaps'].append({
                'segments': segments1[i1:i2],
                'type': 'deletion',
                'position': 'text1'
            })
        elif tag == 'insert':
            alignment['gaps'].append({
                'segments': segments2[j1:j2],
                'type': 'insertion',
                'position': 'text2'
            })
        elif tag == 'replace':
            alignment['mismatches'].append({
                'original': segments1[i1:i2],
                'replacement': segments2[j1:j2],
                'type': 'modification'
            })
    
    return alignment


def calculate_structural_similarity_score(text1: str, text2: str) -> dict[str, float]:
    """
    Calculate various structural similarity scores between two texts.
    
    Returns:
        Dictionary with multiple similarity metrics
    """
    
    changes = detect_structural_changes(text1, text2)
    alignment = generate_structural_alignment(text1, text2)
    
    # Calculate scores
    total_changes = len(changes['insertions']) + len(changes['deletions']) + len(changes['modifications'])
    
    # Structural similarity score (inverse of changes)
    text_length = max(len(text1.split()), len(text2.split()))
    structural_score = max(0, 1 - (total_changes / text_length)) if text_length > 0 else 0
    
    # Alignment-based score
    total_segments = len(alignment['segments1']) + len(alignment['segments2'])
    matches = len(alignment['matches'])
    alignment_score = matches / (total_segments / 2) if total_segments > 0 else 0
    
    return {
        'structural_similarity': structural_score,
        'alignment_score': alignment_score,
        'insertions': len(changes['insertions']),
        'deletions': len(changes['deletions']),
        'modifications': len(changes['modifications']),
        'total_changes': total_changes
    }


def generate_differential_report(text1: str, text2: str, 
                               file1_name: str = "Text 1", 
                               file2_name: str = "Text 2") -> dict[str, any]:
    """
    Generate a comprehensive differential report for two text chapters.
    
    Returns:
        Complete report with changes, alignment, and recommendations
    """
    
    changes = detect_structural_changes(text1, text2)
    alignment = generate_structural_alignment(text1, text2)
    scores = calculate_structural_similarity_score(text1, text2)
    
    report = {
        'file1': file1_name,
        'file2': file2_name,
        'changes': changes,
        'alignment': alignment,
        'scores': scores,
        'summary': {
            'significant_differences': len([c for c in changes['modifications'] if len(c['original']) > 10 or len(c['replacement']) > 10]),
            'minor_variants': len([c for c in changes['modifications'] if len(c['original']) <= 5 and len(c['replacement']) <= 5]),
            'structural_preservation': scores['alignment_score'] > 0.8,
            'recommendation': 'Manuscripts are structurally similar' if scores['alignment_score'] > 0.7 else 'Significant structural differences detected'
        }
    }
    
    return report