File size: 8,091 Bytes
1fe29b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8948fa2
 
 
1fe29b6
 
 
 
 
 
 
 
8948fa2
 
1fe29b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8948fa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1fe29b6
 
 
 
 
 
 
 
 
 
 
5e02f4e
 
1fe29b6
 
 
 
 
5e02f4e
 
1fe29b6
8948fa2
1fe29b6
8948fa2
1fe29b6
8948fa2
1fe29b6
 
 
 
 
 
 
 
 
 
8948fa2
1fe29b6
 
 
 
 
 
 
 
 
 
 
5e02f4e
8948fa2
1fe29b6
 
 
 
 
8948fa2
 
 
 
5e02f4e
 
1fe29b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8948fa2
1fe29b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import pandas as pd
from src.utils import read_data_file

SEP = "*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*"

def split_execution_traces(log_text: str):
    parts = log_text.strip().split(SEP)
    return [p.strip() for p in parts if p.strip()]

def _extract_code(block: str):
    lines = block.splitlines()
    start_idx = None
    for i, ln in enumerate(lines):
        if ln.strip().lower().startswith("-- code:"):
            start_idx = i + 1
            break
    if start_idx is None:
        return None, None  # (code_text, code_end_idx)

    end_idx = len(lines)
    for j in range(start_idx, len(lines)):
        s = lines[j].strip()
        if s.startswith("-- ") and s.endswith(":"):
            end_idx = j
            break
    code_block = "\n".join(lines[start_idx:end_idx]).strip("\n")
    return (code_block if code_block.strip() else None), end_idx

def _extract_test_output(block: str):
    lines = block.splitlines()
    _, after_code_idx = _extract_code(block)
    if after_code_idx is None:
        return None, None

    section_idx = None
    section_tag = None
    for k in range(after_code_idx, len(lines)):
        tag = lines[k].strip().lower()
        if tag.startswith("-- output:") or tag.startswith("-- error:"):
            section_idx = k
            section_tag = tag
            break
    if section_idx is None:
        return None, None

    end_idx = len(lines)
    for t in range(section_idx + 1, len(lines)):
        s = lines[t].strip()
        if s.startswith("-- ") and s.endswith(":"):
            end_idx = t
            break

    content = "\n".join(lines[section_idx + 1 : end_idx]).strip("\n")
    if not content.strip():
        content = None

    out_type = "stdout" if section_tag.startswith("-- output:") else "stderr"
    return out_type, content

def _read_scalar_after_section(lines, idx):
    """Return the first non-empty line after lines[idx], or None."""
    for j in range(idx + 1, len(lines)):
        txt = lines[j].strip()
        if not txt:
            # allow empty line(s) before the scalar
            continue
        return txt
    return None

def _extract_submission(block: str):
    """
    Extract from a SUBMISSION/SUBMITION block:
      - execution_time (float, seconds)
      - grade (float, percent 0..100)
      - testcases (list of dicts with index, input, correct_output, user_output) OR None
      - output_type: "stdout" (for test cases) or "stderr" (for error trace)
      - output_content: raw text of test cases+grade or the error message
    """
    lines = block.splitlines()
    _, after_code_idx = _extract_code(block)
    scan_start = after_code_idx if after_code_idx is not None else 0

    execution_time = None
    grade = None
    testcases = []
    output_lines = []
    output_type, output_content = None, None

    i = scan_start
    while i < len(lines):
        raw = lines[i].strip()
        low = raw.lower()

        # -- EXECUTION TIME:
        if low.startswith("-- execution time:"):
            val = _read_scalar_after_section(lines, i)
            if val is not None:
                try:
                    execution_time = float(val)
                except:
                    pass
            i += 1
            continue

        # -- ERROR:
        if low.startswith("-- error:"):
            output_type = "stderr"
            # collect everything until next "-- " section or end
            j = i + 1
            err_lines = []
            while j < len(lines):
                if lines[j].strip().startswith("-- "):
                    break
                err_lines.append(lines[j])
                j += 1
            output_content = "\n".join(err_lines).strip()
            i = j
            continue

        # -- TEST CASE N:
        if low.startswith("-- test case"):
            idx = None
            try:
                head = raw.split(":", 1)[0]
                idx = int(head.lower().split("test case", 1)[1].strip())
            except:
                pass

            j = i + 1
            current = {"index": idx, "input": "", "correct_output": "", "user_output": ""}
            active = None
            output_lines.append(lines[i])  # keep the "-- TEST CASE ..." line

            while j < len(lines):
                sraw = lines[j].rstrip("\n")
                slow = sraw.strip().lower()
                if slow.startswith("-- test case") or slow.startswith("-- grade:"):
                    break
                output_lines.append(sraw)
                if slow.startswith("---- input:"):
                    active = "input"; current["input"] = ""
                elif slow.startswith("---- correct output:"):
                    active = "correct_output"; current["correct_output"] = ""
                elif slow.startswith("---- user output:"):
                    active = "user_output"; current["user_output"] = ""
                else:
                    if active:
                        current[active] += (sraw + "\n")
                j += 1

            for k in ("input", "correct_output", "user_output"):
                current[k] = current[k].rstrip("\n")

            testcases.append(current)
            i = j
            output_type = "stdout"
            continue

        # -- GRADE:
        if low.startswith("-- grade:"):
            val = _read_scalar_after_section(lines, i)
            if val is not None:
                v = val.strip().rstrip("%").strip()
                try:
                    grade = float(v)
                except:
                    pass
            output_lines.append(lines[i])
            if val: output_lines.append(val)
            i += 1
            continue

        i += 1

    if output_type == "stdout":
        output_content = "\n".join(output_lines).strip() or None

    return execution_time, grade, testcases or None, output_type, output_content



def parse_execution_data(full_path):
    """
    Returns one row per trace with:
      user, class_number, type, timestamp, code,
      output_type, output_content (for TEST),
      execution_time, grade, testcases (for SUBMISSION/SUBMITION),
      trace
    """

    print(f"Parsing execution data from {full_path}...")
    
    user = full_path.split("/")[-3]
    class_number = full_path.split("/")[-5]
    assessment_id, exercise_id = full_path.split("/")[-1].replace(".log", "").split("_")
    assessment_id = int(assessment_id)
    exercise_id = int(exercise_id)

    log_text = read_data_file(full_path)  # you provide this

    rows = []
    for block in split_execution_traces(log_text):
        # header '== TYPE (timestamp)'
        first = next((ln.strip() for ln in block.splitlines() if ln.strip()), "")
        header = first.lstrip("=").strip()

        typ, ts = None, None
        if "(" in header and ")" in header:
            left, rest = header.split("(", 1)
            typ = left.strip()
            ts = rest.split(")", 1)[0].strip()
        else:
            typ = header

        code, _ = _extract_code(block)

        # Defaults
        output_type, output_content = None, None
        execution_time, grade, testcases = None, None, None

        tnorm = (typ or "").strip().lower()
        if tnorm == "test":
            output_type, output_content = _extract_test_output(block)
        elif tnorm in ("submission", "submition", "submit"):
            execution_time, grade, testcases, output_type, output_content = _extract_submission(block)

        rows.append({
            "user":           user,
            "class_number":   class_number,
            "assessment_id":  assessment_id,
            "exercise_id":    exercise_id,
            "type":           typ,
            "timestamp":      ts,
            "code":           code,
            "output_type":    output_type,
            "output_content": output_content,
            "execution_time": execution_time,
            "grade":          grade,            # percent 0..100
            "testcases":      testcases,        # list[dict] or None
            "trace":          block
        })

    return pd.DataFrame(rows)