-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess_kanun.py
More file actions
311 lines (254 loc) · 11.1 KB
/
process_kanun.py
File metadata and controls
311 lines (254 loc) · 11.1 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import re
import json
from typing import List, Dict
from dataclasses import dataclass
import hashlib
@dataclass
class KanunChunk:
madde_no: str
madde_baslik: str
kisim: str
bolum: str
icerik: str
full_path: str
chunk_id: str
class NoterlikKanunuProcessor:
def __init__(self):
self.maddeler = []
self.chunks = []
self.current_kisim = ""
self.current_bolum = ""
def parse_kanun_text(self, text: str) -> List[Dict]:
lines = text.split('\n')
maddeler = []
current_madde = None
current_content = []
for line in lines:
line = line.strip()
if not line:
continue
# KISIM başlığı kontrolü
kisim_match = re.match(r'^(BİRİNCİ|İKİNCİ|ÜÇÜNCÜ|DÖRDÜNCÜ|BEŞİNCİ|ALTINCI|YEDİNCİ|SEKİZİNCİ|DOKUZUNCU|ONUNCU)\s+KISIM\s*$', line, re.IGNORECASE)
if kisim_match:
self.current_kisim = line
self.current_bolum = ""
continue
# alt başlık
if self.current_kisim and not line.startswith('Madde') and not line.startswith('BÖLÜM'):
# Eğer önceki satırda KISIM vardı ve bu satır Madde ile başlamıyorsa, KISIM başlığının devamı
if not re.match(r'^[a-z]', line): # Küçük harfle başlamıyorsa başlık olabilir
self.current_kisim = f"{self.current_kisim} - {line}"
continue
# BÖLÜM başlığı kontrolü
bolum_match = re.match(r'^(BİRİNCİ|İKİNCİ|ÜÇÜNCÜ|DÖRDÜNCÜ|BEŞİNCİ)\s+BÖLÜM\s*$', line, re.IGNORECASE)
if bolum_match:
self.current_bolum = line
continue
# BÖLÜM alt başlık
if self.current_bolum and not line.startswith('Madde') and not self.current_bolum.endswith(line):
if not re.match(r'^[a-z]', line):
self.current_bolum = f"{self.current_bolum} - {line}"
continue
# Madde başlangıcı kontrolü
madde_match = re.match(r'^Madde\s+(\d+(?:/[A-Z])?)\s*[–-]\s*(?:\(.*?\))?\s*(.*)$', line)
if madde_match:
# Önceki maddeyi kaydet
if current_madde:
maddeler.append({
'madde_no': current_madde['madde_no'],
'madde_baslik': current_madde['madde_baslik'],
'kisim': current_madde['kisim'],
'bolum': current_madde['bolum'],
'icerik': '\n'.join(current_content).strip()
})
# Yeni madde başlat
madde_no = madde_match.group(1)
madde_devam = madde_match.group(2).strip()
current_madde = {
'madde_no': madde_no,
'madde_baslik': '',
'kisim': self.current_kisim,
'bolum': self.current_bolum,
}
current_content = []
if madde_devam:
current_content.append(madde_devam)
continue
# iki nokta üst üste ile biten satırlar genelde başlıktır
if current_madde and line.endswith(':') and not current_madde['madde_baslik']:
current_madde['madde_baslik'] = line.rstrip(':')
continue
# Normal içerik satırı
if current_madde:
current_content.append(line)
# Son maddeyi kaydet
if current_madde and current_content:
maddeler.append({
'madde_no': current_madde['madde_no'],
'madde_baslik': current_madde['madde_baslik'],
'kisim': current_madde['kisim'],
'bolum': current_madde['bolum'],
'icerik': '\n'.join(current_content).strip()
})
return maddeler
def create_chunks(self, madde: Dict) -> List[KanunChunk]:
chunks = []
alt_chunks = self.split_madde_content(madde['icerik'])
for i, chunk_content in enumerate(alt_chunks):
# Hiyerarşik içerik oluştur (genelgeler gibi)
hierarchical_content = self._create_hierarchical_content(
madde_no=madde['madde_no'],
madde_baslik=madde['madde_baslik'],
kisim=madde['kisim'],
bolum=madde['bolum'],
chunk_content=chunk_content
)
chunk_id = hashlib.md5(
f"kanun-{madde['madde_no']}-{i}-{chunk_content[:50]}".encode()
).hexdigest()[:12]
full_path = f"Noterlik Kanunu > Madde {madde['madde_no']}"
if madde['madde_baslik']:
full_path += f" ({madde['madde_baslik']})"
chunk = KanunChunk(
madde_no=madde['madde_no'],
madde_baslik=madde['madde_baslik'],
kisim=madde['kisim'],
bolum=madde['bolum'],
icerik=hierarchical_content,
full_path=full_path,
chunk_id=chunk_id
)
chunks.append(chunk)
return chunks
def _create_hierarchical_content(
self,
madde_no: str,
madde_baslik: str,
kisim: str,
bolum: str,
chunk_content: str
) -> str:
hierarchical = f"NOTERLİK KANUNU (1512)\n"
if kisim:
hierarchical += f"{kisim}\n"
if bolum:
hierarchical += f"{bolum}\n"
hierarchical += f"Madde {madde_no}"
if madde_baslik:
hierarchical += f" - {madde_baslik}"
hierarchical += "\n"
hierarchical += "---\n"
hierarchical += chunk_content
return hierarchical
def split_madde_content(
self,
content: str,
max_length: int = 1500,
overlap: int = 200
) -> List[str]:
"""
İçeriği chunklara böler, overlap ile context korunur
"""
if len(content) <= max_length:
return [content]
chunks = []
# Numaralandırılmış bentlere göre böl (1., 2., 3. vb.)
bent_pattern = r'(\d+\.\s+)'
parts = re.split(bent_pattern, content)
current_chunk = ""
for i in range(0, len(parts)):
part = parts[i]
if len(current_chunk + part) <= max_length:
current_chunk += part
else:
if current_chunk:
chunks.append(current_chunk.strip())
# Overlap
if len(current_chunk) > overlap:
current_chunk = current_chunk[-overlap:] + part
else:
current_chunk = part
else:
# Part kendisi çok uzunsa, cümlelere göre böl
sentences = re.split(r'([.!?]\s+)', part)
temp_chunk = ""
for j in range(0, len(sentences)):
sentence = sentences[j]
if len(temp_chunk + sentence) <= max_length:
temp_chunk += sentence
else:
if temp_chunk:
chunks.append(temp_chunk.strip())
temp_chunk = sentence
else:
# Tek cümle bile çok uzunsa, zorla böl
chunks.append(sentence[:max_length].strip())
temp_chunk = sentence[max_length:]
if temp_chunk:
current_chunk = temp_chunk
if current_chunk.strip():
chunks.append(current_chunk.strip())
return chunks if chunks else [content]
def process_file(self, file_path: str) -> List[KanunChunk]:
with open(file_path, 'r', encoding='utf-8') as f:
text = f.read()
print("🔄 Noterlik Kanunu parse ediliyor...")
self.maddeler = self.parse_kanun_text(text)
print(f"✅ {len(self.maddeler)} madde bulundu")
print("🔄 Chunklar oluşturuluyor...")
for madde in self.maddeler:
chunks = self.create_chunks(madde)
self.chunks.extend(chunks)
print(f"✅ {len(self.chunks)} chunk oluşturuldu")
return self.chunks
def export_for_rag(self, output_path: str):
rag_data = []
for chunk in self.chunks:
rag_data.append({
'id': chunk.chunk_id,
'content': chunk.icerik,
'metadata': {
'source_type': 'kanun',
'kanun_adi': 'Noterlik Kanunu',
'kanun_no': '1512',
'madde_no': chunk.madde_no,
'madde_baslik': chunk.madde_baslik,
'kisim': chunk.kisim,
'bolum': chunk.bolum,
'full_path': chunk.full_path,
'source': 'Noterlik Kanunu (1512)'
}
})
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(rag_data, f, ensure_ascii=False, indent=2)
print(f"✅ {len(rag_data)} chunk '{output_path}' dosyasına kaydedildi")
def get_statistics(self):
return {
'toplam_madde': len(self.maddeler),
'toplam_chunk': len(self.chunks),
'ortalama_chunk_uzunlugu': (
sum(len(chunk.icerik) for chunk in self.chunks) / len(self.chunks)
if self.chunks else 0
),
'kisimlar': list(set(m['kisim'] for m in self.maddeler if m['kisim'])),
'madde_basina_chunk': (
len(self.chunks) / len(self.maddeler) if self.maddeler else 0
)
}
if __name__ == "__main__":
processor = NoterlikKanunuProcessor()
chunks = processor.process_file("kanun_extracted.txt")
processor.export_for_rag("noterlik_kanunu_rag.json")
stats = processor.get_statistics()
print("\n📊 İşlem İstatistikleri:")
print(f"Toplam Madde: {stats['toplam_madde']}")
print(f"Toplam Chunk: {stats['toplam_chunk']}")
print(f"Ortalama Chunk Uzunluğu: {stats['ortalama_chunk_uzunlugu']:.0f} karakter")
print(f"Madde Başına Chunk: {stats['madde_basina_chunk']:.2f}")
print(f"\nBulunan Kısımlar: {len(stats['kisimlar'])}")
print("\n📝 Örnek Chunklar:")
for i, chunk in enumerate(chunks[:3]):
print(f"\n{i+1}. {chunk.full_path}")
print(f" ID: {chunk.chunk_id}")
print(f" Kısım: {chunk.kisim[:50]}...")
print(f" İçerik: {chunk.icerik[:150]}...")