fivetech commited on
Commit
a68d103
·
verified ·
1 Parent(s): 0dfbe21

Upload test_battery_100.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. test_battery_100.py +233 -0
test_battery_100.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Harbour Test Battery - Fast version with incremental saving
4
+ """
5
+
6
+ import json, time, subprocess, requests, sys
7
+ from pathlib import Path
8
+ from datetime import datetime
9
+
10
+ OLLAMA_URL = "http://localhost:11434/api/generate"
11
+ MODEL = "qwen3.6:35b"
12
+ HARBOUR = "/home/fivetech/harbour/bin/linux/gcc/harbour"
13
+ WORK_DIR = Path("/home/fivetech/finetune/test_output")
14
+ WORK_DIR.mkdir(exist_ok=True)
15
+ RESULTS_FILE = Path("/home/fivetech/finetune/test_baseline_100.json")
16
+
17
+ SYSTEM = """You are an expert Harbour programmer. Write clean, correct, COMPILABLE Harbour code.
18
+ Use Hungarian notation: n=numeric, c=character, l=logical, a=array, o=object, d=date.
19
+ Use 3-space indentation.
20
+ Do NOT include explanations, markdown, or #include. Only raw Harbour code.
21
+ End functions with RETURN and END FUNCTION."""
22
+
23
+ def query(prompt, timeout=180):
24
+ payload = {"model": MODEL, "prompt": prompt, "stream": False,
25
+ "options": {"temperature": 0.2, "num_predict": 1500, "top_p": 0.9}}
26
+ try:
27
+ t0 = time.time()
28
+ r = requests.post(OLLAMA_URL, json=payload, timeout=timeout)
29
+ d = r.json()
30
+ return {"resp": d.get("response",""), "tok": d.get("eval_count",0),
31
+ "dur": time.time()-t0, "tps": d.get("eval_count",0)/max(d.get("eval_duration",1)/1e9,.001)}
32
+ except Exception as e:
33
+ return {"resp":"", "tok":0, "dur":0, "tps":0, "err":str(e)}
34
+
35
+ def compile_hb(code):
36
+ f = WORK_DIR/"test.prg"
37
+ f.write_text(code)
38
+ try:
39
+ r = subprocess.run([HARBOUR, str(f), "-n", "-w"], capture_output=True, text=True, timeout=20)
40
+ return r.returncode == 0, (r.stderr or r.stdout).strip()[:400]
41
+ except:
42
+ return False, "timeout"
43
+
44
+ def clean(resp):
45
+ lines = resp.split('\n')
46
+ in_code = False
47
+ code = []
48
+ for line in lines:
49
+ s = line.strip()
50
+ if s.startswith('```'):
51
+ in_code = not in_code
52
+ continue
53
+ if in_code:
54
+ code.append(line)
55
+ elif not code:
56
+ u = s.upper()
57
+ if any(u.startswith(k) for k in ['FUNCTION','PROCEDURE','LOCAL','STATIC','#DEFINE','CLASS','METHOD','RETURN','SET','REQUEST','MEMVAR','*']):
58
+ code.append(line)
59
+ return '\n'.join(code).strip() if code else resp.strip()
60
+
61
+ def save(results, meta):
62
+ with open(RESULTS_FILE, "w") as f:
63
+ json.dump({"model":MODEL,"ts":datetime.now().isoformat(),**meta,"results":results}, f, indent=2, ensure_ascii=False)
64
+
65
+ # 100 tests - proportional to dataset (48 Arrays, 22 OOP, 9 Other, 8 Func, 7 DB, 4 FileIO, 2 Control)
66
+ TESTS = [
67
+ # ARRAYS (48)
68
+ ("A01","Arrays","Create 2D array","Write a Harbour function that creates a 5x5 multiplication table as 2D array and prints it."),
69
+ ("A02","Arrays","AAdd and resize","Write Harbour code creating empty array, adding 100 elements with AAdd, resizing to 50 with ASize."),
70
+ ("A03","Arrays","ASort custom","Write a Harbour function sorting array of structures by numeric field using ASort with code block."),
71
+ ("A04","Arrays","AScan code block","Write Harbour code using AScan to find first negative number in array. Return index or 0."),
72
+ ("A05","Arrays","AFill pattern","Write Harbour code using AFill to initialize array with alternating 1 and 0 values."),
73
+ ("A06","Arrays","AINS and ADEL","Write Harbour functions: insert element at position and delete element at position with edge cases."),
74
+ ("A07","Arrays","ACopy array","Write Harbour code using ACopy to copy part of one array to another with offset and length."),
75
+ ("A08","Arrays","AEval transform","Write Harbour code using AEval to double every element in array in-place."),
76
+ ("A09","Arrays","Array join","Write Harbour function joining array elements with delimiter using loop."),
77
+ ("A10","Arrays","String split","Write Harbour function splitting CSV string into array handling quoted values."),
78
+ ("A11","Arrays","3D array","Write Harbour code creating and accessing 3D array, filling with sequential numbers."),
79
+ ("A12","Arrays","Array contains","Write Harbour function checking if array contains value, return TRUE/FALSE."),
80
+ ("A13","Arrays","Array unique","Write Harbour function removing duplicates from array returning unique values."),
81
+ ("A14","Arrays","Array flatten","Write Harbour function flattening nested arrays into single array."),
82
+ ("A15","Arrays","Array reverse","Write Harbour function reversing array in-place."),
83
+ ("A16","Arrays","Array sum avg","Write Harbour functions calculating sum and average of numeric array."),
84
+ ("A17","Arrays","Array min max","Write Harbour functions finding min and max in array with single pass."),
85
+ ("A18","Arrays","Array filter","Write Harbour function filtering array keeping elements matching code block condition."),
86
+ ("A19","Arrays","Array map","Write Harbour function mapping array to new array applying code block."),
87
+ ("A20","Arrays","Array reduce","Write Harbour function reducing array to single value with accumulator."),
88
+ ("A21","Arrays","Hash create","Write Harbour code creating hash with :=, adding keys, retrieving values."),
89
+ ("A22","Arrays","Hash iterate","Write Harbour code iterating hash with FOR EACH printing key-value pairs."),
90
+ ("A23","Arrays","Hash keys values","Write Harbour code extracting keys and values from hash into arrays."),
91
+ ("A24","Arrays","Hash merge","Write Harbour function merging two hashes, second overriding on conflicts."),
92
+ ("A25","Arrays","Hash exists","Write Harbour code checking key existence with HB_HHasKey and default value."),
93
+ ("A26","Arrays","Hash delete","Write Harbour code deleting key from hash checking existence first."),
94
+ ("A27","Arrays","Hash array convert","Write Harbour code converting hash to array of pairs and back."),
95
+ ("A28","Arrays","Hash count keys","Write Harbour function counting total keys in hash."),
96
+ ("A29","Arrays","Hash filter","Write Harbour function filtering hash keeping entries where value > threshold."),
97
+ ("A30","Arrays","Nested hash","Write Harbour code working with nested hashes accessing deeply nested values."),
98
+ ("A31","Arrays","FOR EACH array","Write Harbour code using FOR EACH finding longest string in array."),
99
+ ("A32","Arrays","FOR EACH hash","Write Harbour code using FOR EACH on hash building comma-separated string."),
100
+ ("A33","Arrays","Bubble sort","Implement bubble sort in Harbour for array of numbers with nested loops."),
101
+ ("A34","Arrays","Selection sort","Implement selection sort in Harbour finding min and swapping."),
102
+ ("A35","Arrays","Insertion sort","Implement insertion sort in Harbour with element shifting."),
103
+ ("A36","Arrays","Binary search","Implement binary search in Harbour on sorted array returning index."),
104
+ ("A37","Arrays","Array intersection","Write Harbour function returning intersection of two arrays."),
105
+ ("A38","Arrays","Array difference","Write Harbour function returning elements in first not in second array."),
106
+ ("A39","Arrays","Array chunk","Write Harbour function splitting array into chunks of size N."),
107
+ ("A40","Arrays","Array zip","Write Harbour function zipping two arrays into pairs."),
108
+ ("A41","Arrays","Array rotate","Write Harbour function rotating array left by N positions."),
109
+ ("A42","Arrays","Array compact","Write Harbour function removing NIL elements from array."),
110
+ ("A43","Arrays","Array distinct","Write Harbour function returning distinct elements preserving order."),
111
+ ("A44","Arrays","Array deep copy","Write Harbour function creating deep copy of nested array."),
112
+ ("A45","Arrays","Hash frequency","Write Harbour function counting frequency of array elements using hash."),
113
+ ("A46","Arrays","Array group by","Write Harbour function grouping array elements by criterion."),
114
+ ("A47","Arrays","Array windows","Write Harbour function creating sliding windows of size N."),
115
+ ("A48","Arrays","Array cartesian","Write Harbour function computing cartesian product of two arrays."),
116
+ # OOP (22)
117
+ ("O01","OOP","Basic class","Write Harbour class Rectangle with DATA, METHOD New, Area, Perimeter."),
118
+ ("O02","OOP","Inheritance","Write Harbour classes Animal base and Dog derived with Breed DATA and Speak METHOD."),
119
+ ("O03","OOP","Polymorphism","Write Harbour classes Shape Circle Rectangle with area method each."),
120
+ ("O04","OOP","Operator overload","Write Harbour class Complex overloading + and * operators."),
121
+ ("O05","OOP","Singleton","Implement Singleton pattern in Harbour for Logger class GetInstance method."),
122
+ ("O06","OOP","Observer","Implement Observer pattern in Harbour with Subject and Observer classes."),
123
+ ("O07","OOP","Factory","Implement Factory pattern creating different shape objects based on input."),
124
+ ("O08","OOP","Constructor","Write Harbour class with New constructor and Destroy destructor."),
125
+ ("O09","OOP","Stack class","Write Harbour class Stack with Push Pop Peek IsEmpty methods."),
126
+ ("O10","OOP","Dictionary","Write Harbour class Dictionary using hash with Add Get Remove Contains."),
127
+ ("O11","OOP","Inheritance chain","Write 3-level inheritance Vehicle Car ElectricCar with overriding."),
128
+ ("O12","OOP","Abstract class","Write abstract Drawable class with Draw method in Circle Square."),
129
+ ("O13","OOP","ToString","Write Harbour class with ToString returning formatted representation."),
130
+ ("O14","OOP","CompareTo","Write Harbour class with CompareTo for sorting by field."),
131
+ ("O15","OOP","Clone","Write Harbour class with Clone method creating deep copy."),
132
+ ("O16","OOP","Iterator","Write Harbour class implementing iteration over collection."),
133
+ ("O17","OOP","Builder","Implement Builder pattern constructing complex HTML elements."),
134
+ ("O18","OOP","Strategy","Implement Strategy pattern with different sorting strategies."),
135
+ ("O19","OOP","Decorator","Implement Decorator pattern wrapping base component."),
136
+ ("O20","OOP","Properties","Write Harbour class with property getters and setters."),
137
+ ("O21","OOP","Static method","Write Harbour class with CLASSDATA and CLASS factory method."),
138
+ ("O22","OOP","Composition","Write Harbour classes using composition Engine inside Car."),
139
+ # OTHER (9)
140
+ ("X01","Other","Preprocessor defines","Write Harbour preprocessor #define for constants and #ifdef platform detection."),
141
+ ("X02","Other","Custom command","Write #xcommand shorthand for declaring variables with initialization."),
142
+ ("X03","Other","HB_Is functions","Write validation using HB_IsString HB_IsNumeric HB_IsArray HB_IsNil."),
143
+ ("X04","Other","Regex validation","Write Harbour code using HB_RegExCompile HB_RegExMatch to validate emails."),
144
+ ("X05","Other","Serialization","Write Harbour code using HB_Serialize HB_Deserialize to save load hash."),
145
+ ("X06","Other","File path ops","Write Harbour code using hb_DirBuild hb_FileNameGet hb_PathJoin."),
146
+ ("X07","Other","Version check","Write Harbour code using HB_Version to detect version conditionally."),
147
+ ("X08","Other","Translation","Write Harbour #translate directives mapping alternative syntax."),
148
+ ("X09","Other","Conditional defines","Write Harbour code with nested ifdef ifndef else for feature toggling."),
149
+ # FUNCTIONS (8)
150
+ ("F01","Functions","Default params","Write Harbour function with default parameter values."),
151
+ ("F02","Functions","Recursion","Write recursive Harbour function for factorial."),
152
+ ("F03","Functions","Scope demo","Write Harbour code demonstrating LOCAL STATIC PRIVATE PUBLIC scope."),
153
+ ("F04","Functions","Code block eval","Write Harbour code using Eval with code blocks and AEval."),
154
+ ("F05","Functions","Error handling","Write Harbour function with BEGIN SEQUENCE RECOVER for safe reading."),
155
+ ("F06","Functions","Pass by ref","Write Harbour function modifying caller variable with @."),
156
+ ("F07","Functions","Variable args","Write Harbour function accepting variable number of arguments."),
157
+ ("F08","Functions","Nested calls","Write Harbour code with nested function calls and scope isolation."),
158
+ # DATABASE (7)
159
+ ("D01","Database","Create DBF","Write Harbour code creating DBF with DBCreate specifying field types."),
160
+ ("D02","Database","Open append","Write Harbour code opening DBF with DBUseArea appending records."),
161
+ ("D03","Database","Indexing","Write Harbour code creating index with ORDCREATE and DBSeek."),
162
+ ("D04","Database","DBEval sum","Write Harbour code using DBEval to sum numeric field."),
163
+ ("D05","Database","Filter","Write Harbour code using SET FILTER TO processing filtered records."),
164
+ ("D06","Database","Multi-area","Write Harbour code using multiple work areas with SELECT."),
165
+ ("D07","Database","Relations","Write Harbour code setting parent-child relation DBSetRelation."),
166
+ # FILE I/O (4)
167
+ ("I01","File I/O","Text read write","Write Harbour functions for text file R/W using FCreate FOpen FRead FWrite FClose."),
168
+ ("I02","File I/O","Line by line","Write Harbour code reading file line by line with FEof."),
169
+ ("I03","File I/O","Directory list","Write Harbour code using Directory listing files with pattern."),
170
+ ("I04","File I/O","File exists","Write Harbour code checking file existence with File function."),
171
+ # CONTROL (2)
172
+ ("C01","Control","Complex IF","Write Harbour function nested IF ELSEIF ELSE with AND OR conditions."),
173
+ ("C02","Control","Nested loops","Write Harbour code nested FOR loops EXIT LOOP finding combinations."),
174
+ ]
175
+
176
+ print(f"{'='*60}")
177
+ print(f"TEST BATTERY: {len(TESTS)} tests | Model: {MODEL}")
178
+ print(f"Started: {datetime.now():%Y-%m-%d %H:%M:%S}")
179
+ print(f"{'='*60}")
180
+
181
+ results = []
182
+ pass_c = fail_c = 0
183
+
184
+ for i, (tid, cat, name, prompt) in enumerate(TESTS, 1):
185
+ sys.stdout.write(f"\r[{i:3d}/{len(TESTS)}] {tid} {name}...")
186
+ sys.stdout.flush()
187
+
188
+ res = query(prompt)
189
+
190
+ if res.get("err"):
191
+ results.append({"id":tid,"cat":cat,"name":name,"ok":False,"err":res["err"],"code":"","tok":0,"tps":0,"dur":0,"lines":0})
192
+ fail_c += 1
193
+ print(f" ERR: {res['err'][:60]}")
194
+ save(results, {"pass":pass_c,"fail":fail_c,"rate":pass_c/len(results)*100 if results else 0})
195
+ continue
196
+
197
+ code = clean(res["resp"])
198
+ ok, cerr = compile_hb(code)
199
+
200
+ if ok: pass_c += 1
201
+ else: fail_c += 1
202
+
203
+ err_short = cerr.split('\n')[0][:80] if cerr and not ok else ""
204
+ print(f"\r[{i:3d}/{len(TESTS)}] {tid} {name}... {'PASS' if ok else 'FAIL'} | {code.count(chr(10))+1}L | {res['tok']}t | {res['tps']:.0f}tps | {res['dur']:.1f}s" + (f" | {err_short}" if err_short else ""))
205
+
206
+ results.append({"id":tid,"cat":cat,"name":name,"ok":ok,"err":cerr[:400],"code":code[:2500],"tok":res["tok"],"tps":res["tps"],"dur":res["dur"],"lines":code.count('\n')+1})
207
+
208
+ save(results, {"pass":pass_c,"fail":fail_c,"rate":pass_c/len(results)*100})
209
+
210
+ print(f"\n\n{'='*60}")
211
+ print(f"SUMMARY")
212
+ print(f"{'='*60}")
213
+
214
+ cats = {}
215
+ for r in results:
216
+ c = r["cat"]
217
+ if c not in cats: cats[c] = [0,0]
218
+ cats[c][0 if r["ok"] else 1] += 1
219
+
220
+ print(f"\n{'Category':<12} {'Pass':>5} {'Fail':>5} {'Rate':>7}")
221
+ print("-"*32)
222
+ for c in sorted(cats):
223
+ p,f = cats[c]
224
+ print(f"{c:<12} {p:>5} {f:>5} {p/(p+f)*100:>6.0f}%")
225
+ print(f"\n{'TOTAL':<12} {pass_c:>5} {fail_c:>5} {pass_c/len(results)*100:>6.0f}%")
226
+
227
+ total_tok = sum(r["tok"] for r in results)
228
+ total_dur = sum(r["dur"] for r in results)
229
+ print(f"Tokens: {total_tok:,} | Time: {total_dur:.0f}s | TPS: {total_tok/max(total_dur,1):.0f}")
230
+
231
+ save(results, {"pass":pass_c,"fail":fail_c,"rate":pass_c/len(results)*100,"cats":cats,
232
+ "total_tok":total_tok,"total_dur":total_dur})
233
+ print(f"\nSaved: {RESULTS_FILE}")