File size: 12,272 Bytes
4655dd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import re
import json
import csv
import pathlib
from typing import List, Dict, Any
from .schemas import BenchmarkTask

def detect_language(text: str) -> str:
    # Arabic if contains Arabic unicode
    if re.search(r'[\u0600-\u06FF]', text):
        return "ar"
    return "en"

def infer_category(prompt: str, language: str) -> str:
    low = prompt.lower()
    # Coding indicators
    code_kw = ["def ", "function", "code", "كود", "python", "for ", "while ", "class ", "import ", "return"]
    if any(k in low for k in code_kw) or "```" in prompt:
        return "coding"
    # Summarization
    sum_kw = ["summarize", "تلخيص", "لخص", "summary", "خلاصة"]
    if any(k in low for k in sum_kw):
        return "summarization"
    # Reasoning
    reason_kw = ["reason", "logic", "منطق", "احسب", "calculate", "if ", "كم ", "ما هو", "why", "because"]
    if any(k in low for k in reason_kw):
        return "reasoning"
    # Fallback by language
    if language == "ar":
        return "arabic"
    return "reasoning"

def parse_csv_file(path: pathlib.Path) -> List[Dict[str, Any]]:
    rows = []
    with open(path, 'r', encoding='utf-8-sig', newline='') as f:
        # Use sniff
        try:
            dialect = csv.Sniffer().sniff(f.read(2048))
            f.seek(0)
        except:
            f.seek(0)
            dialect = csv.excel
        reader = csv.DictReader(f, dialect=dialect)
        # If no header, treat as plain
        if reader.fieldnames is None:
            f.seek(0)
            reader = csv.reader(f)
            for i, row in enumerate(reader):
                if not row or not row[0].strip():
                    continue
                rows.append({"prompt": row[0], "expected": row[1] if len(row)>1 else None, "category": row[2] if len(row)>2 else None})
            return rows
        # Normalize fieldnames lower
        lower_fields = [h.lower().strip() for h in reader.fieldnames] if reader.fieldnames else []
        # Map possible headers
        prompt_keys = ["prompt", "question", "input", "text", "السؤال", "النص"]
        expected_keys = ["expected", "answer", "target", "expected_answer", "الإجابة", "الجواب"]
        regex_keys = ["expected_regex", "regex", "pattern"]
        cat_keys = ["category", "cat", "type", "الفئة"]
        name_keys = ["name", "title", "id"]
        for row in reader:
            # lower keys dict
            low_row = {k.lower().strip(): v for k,v in row.items() if k}
            prompt = None
            for k in prompt_keys:
                if k in low_row and low_row[k]:
                    prompt = low_row[k]
                    break
            if not prompt:
                # fallback first column
                prompt = next((v for v in row.values() if v), None)
            if not prompt or not prompt.strip():
                continue
            expected = None
            for k in expected_keys:
                if k in low_row and low_row[k]:
                    expected = low_row[k]
                    break
            expected_regex = None
            for k in regex_keys:
                if k in low_row and low_row[k]:
                    expected_regex = low_row[k]
                    break
            category = None
            for k in cat_keys:
                if k in low_row and low_row[k]:
                    category = low_row[k].lower().strip()
                    break
            name = None
            for k in name_keys:
                if k in low_row and low_row[k]:
                    name = low_row[k]
                    break
            rows.append({"prompt": prompt.strip(), "expected": expected.strip() if expected else None, "expected_regex": expected_regex.strip() if expected_regex else None, "category": category, "name": name})
    return rows

def parse_json_file(path: pathlib.Path) -> List[Dict[str, Any]]:
    with open(path, 'r', encoding='utf-8') as f:
        data = json.load(f)
    # Handle various wrappers
    if isinstance(data, dict):
        # Look for list inside
        for key in ["data", "tasks", "items", "dataset", "examples"]:
            if key in data and isinstance(data[key], list):
                data = data[key]
                break
        else:
            # Single object
            data = [data]
    if not isinstance(data, list):
        raise ValueError("JSON must be list or dict with list")
    rows = []
    for item in data:
        if not isinstance(item, dict):
            continue
        # Map keys case-insensitive
        low = {k.lower(): v for k,v in item.items()}
        prompt = low.get("prompt") or low.get("question") or low.get("input") or low.get("text") or low.get("instruction")
        expected = low.get("expected") or low.get("answer") or low.get("target") or low.get("output")
        expected_regex = low.get("expected_regex") or low.get("regex") or low.get("pattern")
        category = low.get("category") or low.get("cat") or low.get("type")
        name = low.get("name") or low.get("title") or low.get("id")
        if prompt:
            rows.append({"prompt": str(prompt), "expected": str(expected) if expected else None, "expected_regex": str(expected_regex) if expected_regex else None, "category": str(category).lower() if category else None, "name": str(name) if name else None})
    return rows

def parse_jsonl_file(path: pathlib.Path) -> List[Dict[str, Any]]:
    rows = []
    with open(path, 'r', encoding='utf-8') as f:
        for line in f:
            line=line.strip()
            if not line:
                continue
            try:
                obj = json.loads(line)
                low = {k.lower(): v for k,v in obj.items()} if isinstance(obj, dict) else {}
                prompt = low.get("prompt") or low.get("question") or low.get("input") or low.get("text")
                expected = low.get("expected") or low.get("answer")
                expected_regex = low.get("expected_regex") or low.get("regex")
                category = low.get("category")
                name = low.get("name") or low.get("id")
                if prompt:
                    rows.append({"prompt": str(prompt), "expected": str(expected) if expected else None, "expected_regex": str(expected_regex) if expected_regex else None, "category": str(category).lower() if category else None, "name": str(name) if name else None})
            except json.JSONDecodeError:
                # Treat line as prompt|expected
                if "|" in line:
                    parts = line.split("|",1)
                    rows.append({"prompt": parts[0].strip(), "expected": parts[1].strip(), "expected_regex": None, "category": None, "name": None})
                elif "\t" in line:
                    parts = line.split("\t",1)
                    rows.append({"prompt": parts[0].strip(), "expected": parts[1].strip() if len(parts)>1 else None, "expected_regex": None, "category": None, "name": None})
                else:
                    rows.append({"prompt": line, "expected": None, "expected_regex": None, "category": None, "name": None})
    return rows

def parse_txt_file(path: pathlib.Path) -> List[Dict[str, Any]]:
    rows=[]
    with open(path, 'r', encoding='utf-8', errors='ignore') as f:
        for line in f:
            line=line.strip()
            if not line or line.startswith("#"):
                continue
            # Support prompt|expected or prompt<TAB>expected
            if "|" in line:
                p,e = line.split("|",1)
                rows.append({"prompt": p.strip(), "expected": e.strip(), "expected_regex": None, "category": None, "name": None})
            elif "\t" in line:
                p,e = line.split("\t",1)
                rows.append({"prompt": p.strip(), "expected": e.strip(), "category": None, "expected_regex": None, "name": None})
            else:
                rows.append({"prompt": line, "expected": None, "expected_regex": None, "category": None, "name": None})
    return rows

def parse_file(path: pathlib.Path) -> List[Dict[str, Any]]:
    ext = path.suffix.lower()
    if ext == ".csv":
        return parse_csv_file(path)
    elif ext == ".json":
        return parse_json_file(path)
    elif ext == ".jsonl":
        return parse_jsonl_file(path)
    elif ext in [".txt", ".text", ".dat"]:
        return parse_txt_file(path)
    elif ext in [".md"]:
        return parse_txt_file(path)
    else:
        # Try json, then txt
        try:
            return parse_json_file(path)
        except:
            try:
                return parse_jsonl_file(path)
            except:
                return parse_txt_file(path)

def scan_folder(folder: pathlib.Path) -> Dict[str, Any]:
    if not folder.exists() or not folder.is_dir():
        raise FileNotFoundError(f"المجلد غير موجود: {folder}")
    supported = {".csv",".json",".jsonl",".txt",".md"}
    files = [p for p in folder.rglob("*") if p.is_file() and p.suffix.lower() in supported]
    # Also include .txt without suffix? already
    all_rows = []
    per_file = {}
    language_counts = {"ar":0, "en":0}
    for fp in files:
        try:
            rows = parse_file(fp)
            per_file[str(fp.relative_to(folder))] = len(rows)
            for r in rows:
                lang = detect_language(r["prompt"])
                language_counts[lang]+=1
                # Auto fill missing fields
                if not r.get("category"):
                    r["category"] = infer_category(r["prompt"], lang)
                # Normalize category
                cat = r["category"].lower().strip()
                if cat not in ["reasoning","coding","arabic","summarization"]:
                    # Map arabic synonyms
                    if cat in ["ar","arabic_quality","عربي"]:
                        cat="arabic"
                    elif cat in ["code","برمجة"]:
                        cat="coding"
                    elif cat in ["reason","منطق"]:
                        cat="reasoning"
                    else:
                        # keep inferred
                        cat = infer_category(r["prompt"], lang)
                    r["category"]=cat
                # Auto regex if missing and expected exists: escape expected as regex
                if not r.get("expected_regex") and r.get("expected"):
                    # Simple word boundary regex
                    exp = r["expected"].strip()
                    # Escape but keep simple
                    r["expected_regex"] = re.escape(exp[:40])
                    # For Arabic, keep as is
                    if lang=="ar":
                        r["expected_regex"] = exp[:40]
                # Name fallback
                if not r.get("name"):
                    r["name"] = f"{r['category']}-{len(all_rows)+1}"
                r["language"] = lang
                r["source_file"] = str(fp.name)
            all_rows.extend(rows)
        except Exception as e:
            per_file[str(fp.relative_to(folder))] = f"error: {e}"
    return {
        "folder": str(folder),
        "files_found": len(files),
        "per_file_counts": per_file,
        "total_tasks": len(all_rows),
        "language_counts": language_counts,
        "rows": all_rows
    }

def rows_to_tasks(rows: List[Dict[str, Any]]) -> List[BenchmarkTask]:
    tasks = []
    for i, r in enumerate(rows):
        prompt = r["prompt"]
        expected = r.get("expected")
        expected_regex = r.get("expected_regex")
        cat = r.get("category", "reasoning")
        name = r.get("name") or f"custom-{i+1}"
        # Ensure valid category
        if cat not in ["reasoning","coding","arabic","summarization"]:
            cat="reasoning"
        lang = r.get("language") or detect_language(prompt)
        # Auto adjust max_tokens by category
        max_tokens = 256
        if cat=="coding":
            max_tokens=300
        elif cat=="summarization":
            max_tokens=200
        tasks.append(BenchmarkTask(
            id=f"custom-{i+1:04d}",
            name=name,
            category=cat,
            prompt=prompt,
            expected=expected,
            expected_regex=expected_regex,
            max_tokens=max_tokens
        ))
    return tasks