MRBeDev commited on
Commit
4bdce1f
·
verified ·
1 Parent(s): 47829ed

add filter script

Browse files
Files changed (1) hide show
  1. filter_correct_answer.py +346 -0
filter_correct_answer.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ HF dataset temizleyici: Çoktan seçmeli sorulardan doğru cevap dışındaki şıkları siler.
4
+
5
+ Hazırlayan: Behlül
6
+
7
+ Desteklenen dataset formatları (fizik, tarih, matematik için aynı script):
8
+ - conversations: [{"from": "human/gpt", "value": "..."}]
9
+ - messages: [{"role": "user/assistant", "content": "..."}]
10
+
11
+ Desteklenen cevap prefixleri (asistan mesajından doğru harf çıkarılır):
12
+ - Türkçe: "Cevap: B)" / "Cevap: **B**" / "Doğru cevap: B"
13
+ - İngilizce: "Answer: B" / "**Answer:** B" / "The answer is B"
14
+ - Sondaki tek harf: "...\nB"
15
+
16
+ Kullanım:
17
+ # HF'ten indir + filtrele (3 split birlikte)
18
+ python filter_correct_answer.py --hf mrbe-share/fizik80k --outdir ./out/fizik
19
+
20
+ # Tek dosya
21
+ python filter_correct_answer.py --file train.jsonl --output train_clean.jsonl
22
+
23
+ # Çoktan seçmeli olmayanları at
24
+ python filter_correct_answer.py --hf mrbe-share/fizik80k --outdir ./out/fizik --drop-non-mc
25
+ """
26
+
27
+ import argparse
28
+ import json
29
+ import os
30
+ import re
31
+ import sys
32
+ import urllib.request
33
+ from pathlib import Path
34
+
35
+
36
+ # ---------- Regex ----------
37
+
38
+ # Sorudaki seçenek satırı: "A) ...", "A. ...", "A- ...", "**A)** ..."
39
+ OPTION_LINE_RE = re.compile(
40
+ r'^\s*\*{0,2}\s*([A-Z])\s*\*{0,2}\s*[\)\.\-]\s*\S',
41
+ re.MULTILINE,
42
+ )
43
+
44
+ # Cevap harfini çıkarmak için pattern'lar (öncelik sırasına göre)
45
+ ANSWER_PATTERNS = [
46
+ # "Cevap: B)" / "Cevap: **B**" / "Cevap : B."
47
+ re.compile(r'[Cc]evap\s*[:\-]\s*\*{0,2}\s*([A-Z])\b'),
48
+ # "Doğru cevap: B"
49
+ re.compile(r'[Dd]o[ğg]ru\s+cevap\s*[:\-]\s*\*{0,2}\s*([A-Z])\b'),
50
+ # "**Answer:** B" / "Answer: B"
51
+ re.compile(r'\*{0,2}\s*[Aa]nswer\s*\*{0,2}\s*[:\-]\s*\*{0,2}\s*([A-Z])\b'),
52
+ # "The answer is B" / "the correct answer is B"
53
+ re.compile(r'[Tt]he\s+(?:correct\s+)?answer\s+is\s*[:\-]?\s*\*{0,2}\s*([A-Z])\b'),
54
+ # "**B** is correct" / "B is the correct answer"
55
+ re.compile(r'\*{0,2}([A-Z])\*{0,2}\s+is\s+(?:the\s+)?correct'),
56
+ # Son çare: metin sonunda tek başına duran tek büyük harf
57
+ re.compile(r'(?:^|\n)\s*\*{0,2}([A-Z])\*{0,2}\s*\.?\s*$'),
58
+ ]
59
+
60
+
61
+ def extract_correct_letter(answer_text: str) -> str | None:
62
+ """Asistan cevabından doğru seçeneğin harfini çıkarır (A-Z)."""
63
+ if not answer_text:
64
+ return None
65
+ for pat in ANSWER_PATTERNS:
66
+ m = pat.search(answer_text)
67
+ if m:
68
+ return m.group(1).upper()
69
+ return None
70
+
71
+
72
+ def find_option_letters(question: str) -> set[str]:
73
+ """Sorudaki seçenek harflerini bulur (ör. {'A','B','C','D'})."""
74
+ return {m.upper() for m in OPTION_LINE_RE.findall(question)}
75
+
76
+
77
+ def strip_distractors(question: str, correct_letter: str) -> tuple[str, bool]:
78
+ """
79
+ Sorudan doğru şık dışındaki bütün seçenek satırlarını siler.
80
+ Aynı seçenek birden fazla satıra yayılabileceği için "bu seçenek bloğu
81
+ hangi harfle başladı" state'ini takip ediyoruz.
82
+ """
83
+ lines = question.split('\n')
84
+ out = []
85
+ current_letter = None # şu anda hangi şıkkın içindeyiz
86
+ removed_any = False
87
+ kept_correct = False
88
+
89
+ for line in lines:
90
+ m = re.match(r'^\s*\*{0,2}\s*([A-Z])\s*\*{0,2}\s*[\)\.\-]\s*', line)
91
+ if m:
92
+ current_letter = m.group(1).upper()
93
+ if current_letter == correct_letter:
94
+ out.append(line)
95
+ kept_correct = True
96
+ else:
97
+ removed_any = True
98
+ # skip (doğru şık değil)
99
+ else:
100
+ # devam satırı mı yoksa normal soru metni mi?
101
+ is_blank = line.strip() == ''
102
+ if current_letter is None:
103
+ # soru gövdesi — her zaman tut
104
+ out.append(line)
105
+ else:
106
+ # bir şıkkın devamı
107
+ if is_blank:
108
+ # boş satır şıkkın bittiğini gösterir
109
+ current_letter = None
110
+ out.append(line)
111
+ elif current_letter == correct_letter:
112
+ out.append(line)
113
+ # else: yanlış şıkkın devam satırı — at
114
+ # Cevap: / Answer: gibi ipuçları gelirse şıkkı bitir
115
+ if re.match(r'^\s*\*{0,2}\s*(Cevap|Answer|Doğru cevap)\b', line, re.IGNORECASE):
116
+ current_letter = None
117
+
118
+ return '\n'.join(out), (removed_any and kept_correct)
119
+
120
+
121
+ # ---------- Kayıt işleme ----------
122
+
123
+ def _get_msg_iface(rec: dict):
124
+ """Kaydın mesaj yapısını tespit eder, (msgs_list, role_key, content_key, user_roles, assistant_roles) döner."""
125
+ if 'conversations' in rec and isinstance(rec['conversations'], list):
126
+ return rec['conversations'], 'from', 'value', ('human', 'user'), ('gpt', 'assistant')
127
+ if 'messages' in rec and isinstance(rec['messages'], list):
128
+ return rec['messages'], 'role', 'content', ('user',), ('assistant',)
129
+ return None
130
+
131
+
132
+ def process_record(rec: dict) -> tuple[dict, bool, str]:
133
+ """
134
+ Bir kaydı işler.
135
+ Dönüş: (yeni_kayıt, filtrelendi_mi, sebep_etiketi)
136
+ """
137
+ iface = _get_msg_iface(rec)
138
+ if iface is None:
139
+ return rec, False, 'unknown_format'
140
+ msgs, role_key, content_key, user_roles, asst_roles = iface
141
+
142
+ # Son user/assistant çiftini bul
143
+ user_idx = None
144
+ for i, m in enumerate(msgs):
145
+ if m.get(role_key) in user_roles:
146
+ user_idx = i
147
+ if user_idx is None:
148
+ return rec, False, 'no_user_msg'
149
+
150
+ asst_idx = None
151
+ for j in range(user_idx + 1, len(msgs)):
152
+ if msgs[j].get(role_key) in asst_roles:
153
+ asst_idx = j
154
+ break
155
+ if asst_idx is None:
156
+ return rec, False, 'no_assistant_msg'
157
+
158
+ question = msgs[user_idx].get(content_key, '')
159
+ answer = msgs[asst_idx].get(content_key, '')
160
+
161
+ if not isinstance(question, str) or not isinstance(answer, str):
162
+ return rec, False, 'non_string_content'
163
+
164
+ option_letters = find_option_letters(question)
165
+ if len(option_letters) < 2:
166
+ return rec, False, 'not_multichoice'
167
+
168
+ correct_letter = extract_correct_letter(answer)
169
+ if not correct_letter:
170
+ return rec, False, 'no_correct_letter'
171
+
172
+ if correct_letter not in option_letters:
173
+ return rec, False, f'answer_letter_{correct_letter}_not_in_options'
174
+
175
+ new_question, changed = strip_distractors(question, correct_letter)
176
+ if not changed:
177
+ return rec, False, 'no_distractors_stripped'
178
+
179
+ # Immutable kopya
180
+ new_rec = dict(rec)
181
+ new_msgs = [dict(m) for m in msgs]
182
+ new_msgs[user_idx] = dict(new_msgs[user_idx])
183
+ new_msgs[user_idx][content_key] = new_question
184
+
185
+ if 'conversations' in rec:
186
+ new_rec['conversations'] = new_msgs
187
+ else:
188
+ new_rec['messages'] = new_msgs
189
+
190
+ return new_rec, True, 'filtered'
191
+
192
+
193
+ # ---------- I/O ----------
194
+
195
+ def download_hf_file(repo_id: str, path: str, out_path: Path, token: str | None = None) -> None:
196
+ url = f'https://huggingface.co/datasets/{repo_id}/resolve/main/{path}'
197
+ out_path.parent.mkdir(parents=True, exist_ok=True)
198
+ req = urllib.request.Request(url)
199
+ if token:
200
+ req.add_header('Authorization', f'Bearer {token}')
201
+ sys.stderr.write(f'[indir] {url}\n')
202
+ with urllib.request.urlopen(req) as resp, open(out_path, 'wb') as f:
203
+ size = 0
204
+ while True:
205
+ chunk = resp.read(1024 * 1024)
206
+ if not chunk:
207
+ break
208
+ f.write(chunk)
209
+ size += len(chunk)
210
+ sys.stderr.write(f'\r {size/1024/1024:.1f} MB')
211
+ sys.stderr.flush()
212
+ sys.stderr.write(f'\n[hazır] {out_path} ({out_path.stat().st_size/1024/1024:.1f} MB)\n')
213
+
214
+
215
+ def list_hf_files(repo_id: str, token: str | None = None) -> list[str]:
216
+ url = f'https://huggingface.co/api/datasets/{repo_id}/tree/main?recursive=true'
217
+ req = urllib.request.Request(url)
218
+ if token:
219
+ req.add_header('Authorization', f'Bearer {token}')
220
+ with urllib.request.urlopen(req) as resp:
221
+ data = json.loads(resp.read().decode('utf-8'))
222
+ return [d['path'] for d in data if d.get('type') == 'file' and d['path'].endswith('.jsonl')]
223
+
224
+
225
+ def process_file(in_path: Path, out_path: Path, drop_non_mc: bool = False) -> dict:
226
+ stats = {
227
+ 'total': 0,
228
+ 'filtered': 0,
229
+ 'kept_unchanged': 0,
230
+ 'dropped': 0,
231
+ 'parse_errors': 0,
232
+ 'reasons': {},
233
+ }
234
+ out_path.parent.mkdir(parents=True, exist_ok=True)
235
+ with open(in_path, encoding='utf-8') as fin, open(out_path, 'w', encoding='utf-8') as fout:
236
+ for line in fin:
237
+ line = line.rstrip('\n')
238
+ if not line.strip():
239
+ continue
240
+ stats['total'] += 1
241
+ try:
242
+ rec = json.loads(line)
243
+ except json.JSONDecodeError:
244
+ stats['parse_errors'] += 1
245
+ continue
246
+
247
+ new_rec, was_filtered, reason = process_record(rec)
248
+
249
+ if was_filtered:
250
+ stats['filtered'] += 1
251
+ fout.write(json.dumps(new_rec, ensure_ascii=False) + '\n')
252
+ else:
253
+ stats['reasons'][reason] = stats['reasons'].get(reason, 0) + 1
254
+ if drop_non_mc and reason == 'not_multichoice':
255
+ stats['dropped'] += 1
256
+ continue
257
+ stats['kept_unchanged'] += 1
258
+ fout.write(json.dumps(rec, ensure_ascii=False) + '\n')
259
+ return stats
260
+
261
+
262
+ def print_stats(label: str, stats: dict) -> None:
263
+ print(f'\n=== {label} ===')
264
+ print(f'Toplam satır : {stats["total"]}')
265
+ print(f'Filtrelendi : {stats["filtered"]} (yanlış şıklar silindi)')
266
+ print(f'Değişmeden geçti : {stats["kept_unchanged"]}')
267
+ if stats.get('dropped'):
268
+ print(f'Atıldı : {stats["dropped"]}')
269
+ if stats.get('parse_errors'):
270
+ print(f'Parse hatası : {stats["parse_errors"]}')
271
+ if stats['reasons']:
272
+ print('Atlama nedenleri:')
273
+ for r, c in sorted(stats['reasons'].items(), key=lambda x: -x[1]):
274
+ print(f' {r:<40} {c}')
275
+
276
+
277
+ # ---------- CLI ----------
278
+
279
+ def main():
280
+ p = argparse.ArgumentParser(
281
+ description='Çoktan seçmeli HF dataset\'lerinden yanlış şıkları siler, doğru cevabı bırakır.',
282
+ formatter_class=argparse.RawDescriptionHelpFormatter,
283
+ epilog=__doc__.split('Kullanım:')[1] if 'Kullanım:' in __doc__ else '',
284
+ )
285
+ src = p.add_mutually_exclusive_group(required=True)
286
+ src.add_argument('--hf', help='HF dataset id (ör. mrbe-share/fizik80k)')
287
+ src.add_argument('--file', help='Lokal .jsonl dosya yolu')
288
+
289
+ p.add_argument('--split-path', action='append', default=None,
290
+ help='HF içindeki belirli dosya yolu (birden fazla kez verilebilir). Boş bırakılırsa tüm .jsonl dosyaları işlenir.')
291
+ p.add_argument('--output', help='Tek dosya modu için çıkış yolu (--file ile)')
292
+ p.add_argument('--outdir', help='Çoklu dosya modu için çıkış dizini (--hf ile)')
293
+ p.add_argument('--token', default=os.environ.get('HF_TOKEN'), help='HF API token (özel dataset için gerekli)')
294
+ p.add_argument('--cache-dir', default='/tmp/hf_dataset_cache', help='İndirilen dosyaların cache dizini')
295
+ p.add_argument('--drop-non-mc', action='store_true', help='Çoktan seçmeli olmayan kayıtları at')
296
+ p.add_argument('--force-download', action='store_true', help='Cache\'i yok say, yeniden indir')
297
+
298
+ args = p.parse_args()
299
+
300
+ if args.file:
301
+ if not args.output:
302
+ p.error('--file ile birlikte --output zorunlu')
303
+ stats = process_file(Path(args.file), Path(args.output), drop_non_mc=args.drop_non_mc)
304
+ print_stats(args.file, stats)
305
+ print(f'\nÇıktı: {args.output}')
306
+ return
307
+
308
+ # --hf modu
309
+ if not args.outdir:
310
+ p.error('--hf ile birlikte --outdir zorunlu')
311
+
312
+ splits = args.split_path
313
+ if not splits:
314
+ print(f'[info] {args.hf} için tüm .jsonl dosyaları listeleniyor...')
315
+ splits = list_hf_files(args.hf, token=args.token)
316
+ if not splits:
317
+ print('HATA: dataset\'te .jsonl dosyası bulunamadı', file=sys.stderr)
318
+ sys.exit(1)
319
+ print(f'[info] {len(splits)} dosya bulundu: {splits}')
320
+
321
+ cache_base = Path(args.cache_dir) / args.hf.replace('/', '_')
322
+ outdir = Path(args.outdir)
323
+ outdir.mkdir(parents=True, exist_ok=True)
324
+
325
+ grand_total = {'total': 0, 'filtered': 0, 'kept_unchanged': 0, 'dropped': 0, 'parse_errors': 0}
326
+ for sp in splits:
327
+ cache_path = cache_base / sp
328
+ if args.force_download or not cache_path.exists():
329
+ download_hf_file(args.hf, sp, cache_path, token=args.token)
330
+
331
+ # Düz dosya adı: splits/train.jsonl → splits__train.jsonl
332
+ safe_name = sp.replace('/', '__')
333
+ out_path = outdir / safe_name
334
+
335
+ stats = process_file(cache_path, out_path, drop_non_mc=args.drop_non_mc)
336
+ print_stats(f'{args.hf} / {sp}', stats)
337
+ print(f'Çıktı: {out_path}')
338
+ for k in grand_total:
339
+ grand_total[k] += stats.get(k, 0)
340
+
341
+ if len(splits) > 1:
342
+ print_stats(f'TOPLAM ({args.hf})', {**grand_total, 'reasons': {}})
343
+
344
+
345
+ if __name__ == '__main__':
346
+ main()