File size: 31,771 Bytes
4be750a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
4be750a
 
 
 
 
 
 
 
 
32c1934
 
 
4be750a
 
 
 
 
9f2b199
 
4be750a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
4be750a
9f2b199
4be750a
 
 
 
 
 
 
 
 
9f2b199
 
4be750a
 
 
 
 
 
 
 
 
 
 
32c1934
4be750a
 
 
ce9fc6c
 
4be750a
ce9fc6c
 
 
 
 
 
 
 
 
 
 
4be750a
ce9fc6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4be750a
ce9fc6c
7f1de95
ce9fc6c
7f1de95
ce9fc6c
 
 
 
 
 
 
 
7f1de95
ce9fc6c
 
7f1de95
ce9fc6c
 
 
7f1de95
ce9fc6c
 
 
 
 
7f1de95
ce9fc6c
 
 
4be750a
ce9fc6c
f2c9e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9fc6c
7f1de95
ce9fc6c
 
 
7f1de95
ce9fc6c
 
 
 
 
 
4be750a
 
 
 
 
ce9fc6c
7f1de95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4be750a
 
 
 
 
 
 
 
 
 
 
32c1934
4be750a
 
 
 
 
 
 
32c1934
 
 
4be750a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
4be750a
 
 
 
 
 
32c1934
4be750a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9f2b199
 
 
 
 
 
 
 
4be750a
 
 
 
 
 
 
 
 
 
 
32c1934
4be750a
 
 
 
 
 
32c1934
 
 
ce9fc6c
32c1934
 
 
4be750a
32c1934
50a9093
32c1934
4be750a
 
 
 
50a9093
 
4be750a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce9fc6c
 
 
 
 
50a9093
 
 
 
4be750a
7dc8863
9f2b199
50a9093
7dc8863
 
 
 
 
 
50a9093
ce9fc6c
 
50a9093
 
ce9fc6c
 
 
50a9093
 
 
 
 
 
 
 
 
7dc8863
 
 
50a9093
 
 
 
4be750a
9f2b199
ce9fc6c
50a9093
ce9fc6c
 
50a9093
506f5a9
50a9093
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4be750a
 
50a9093
4be750a
50a9093
4be750a
ce9fc6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4be750a
50a9093
 
 
4be750a
9f2b199
 
 
 
 
 
 
 
 
 
32c1934
9f2b199
a30f35d
9f2b199
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a30f35d
9f2b199
 
a30f35d
 
 
 
 
 
 
 
 
 
 
 
32c1934
a30f35d
 
 
 
 
 
 
32c1934
 
 
a30f35d
 
32c1934
 
 
a30f35d
 
 
 
 
9f2b199
32c1934
a30f35d
9f2b199
 
 
 
 
 
a30f35d
 
 
 
 
32c1934
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
 
 
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
a30f35d
 
 
 
 
 
 
 
 
 
 
32c1934
 
 
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
a30f35d
 
 
 
 
 
 
 
 
32c1934
 
 
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
a30f35d
 
 
 
 
 
 
 
 
 
 
32c1934
a30f35d
32c1934
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
 
 
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
a30f35d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32c1934
 
a30f35d
 
 
 
 
 
 
 
 
9f2b199
4be750a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Run pre-trained DeepSeek Coder 1.3B Model on Chat-GPT 4o generated dataset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## First load dataset into pandas dataframe"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total dataset examples: 1044\n",
      "\n",
      "\n",
      "Which team committed the fewest total turnovers in an away game that resulted in a win?\n",
      "SELECT team_abbreviation_away FROM other_stats WHERE game_id IN (SELECT game_id FROM game WHERE wl_away = 'W') ORDER BY total_turnovers_away ASC LIMIT 1;\n",
      "PHX\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd \n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "\n",
    "# Load dataset and check length\n",
    "df = pd.read_csv(\"./train-data/sql_train.tsv\", sep='\\t')\n",
    "print(\"Total dataset examples: \" + str(len(df)))\n",
    "print(\"\\n\")\n",
    "\n",
    "# Test sampling\n",
    "sample = df.sample(n=1)\n",
    "print(sample[\"natural_query\"].values[0])\n",
    "print(sample[\"sql_query\"].values[0])\n",
    "print(sample[\"result\"].values[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load pre-trained DeepSeek model using transformers and pytorch packages"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
    "import torch\n",
    "\n",
    "# Set device to cuda if available, otherwise CPU\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "\n",
    "# Load model and tokenizer\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"./deepseek-coder-1.3b-instruct\")\n",
    "model = AutoModelForCausalLM.from_pretrained(\"./deepseek-coder-1.3b-instruct\", torch_dtype=torch.bfloat16, device_map=device) \n",
    "model.generation_config.pad_token_id = tokenizer.pad_token_id"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create prompt to setup the model for better performance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_text = \"\"\"You are an AI assistant that converts natural language queries into valid SQLite queries.\n",
    "Database Schema and Explanations\n",
    "\n",
    "team Table\n",
    "Stores information about NBA teams.\n",
    "CREATE TABLE IF NOT EXISTS \"team\" (\n",
    "  \"id\" TEXT PRIMARY KEY,      -- Unique identifier for the team\n",
    "  \"full_name\" TEXT,           -- Full official name of the team (e.g., \"Los Angeles Lakers\")\n",
    "  \"abbreviation\" TEXT,        -- Shortened team name (e.g., \"LAL\")\n",
    "  \"nickname\" TEXT,            -- Commonly used nickname for the team (e.g., \"Lakers\")\n",
    "  \"city\" TEXT,                -- City where the team is based\n",
    "  \"state\" TEXT,               -- State where the team is located\n",
    "  \"year_founded\" REAL         -- Year the team was established\n",
    ");\n",
    "\n",
    "game Table\n",
    "Contains detailed statistics for each NBA game, including home and away team performance.\n",
    "CREATE TABLE IF NOT EXISTS \"game\" (\n",
    "  \"season_id\" TEXT,            -- Season identifier, formatted as \"2YYYY\" (e.g., \"21970\" for the 1970 season)\n",
    "  \"team_id_home\" TEXT,         -- ID of the home team (matches \"id\" in team table)\n",
    "  \"team_abbreviation_home\" TEXT, -- Abbreviation of the home team\n",
    "  \"team_name_home\" TEXT,       -- Full name of the home team\n",
    "  \"game_id\" TEXT PRIMARY KEY,  -- Unique identifier for the game\n",
    "  \"game_date\" TIMESTAMP,       -- Date the game was played (YYYY-MM-DD format)\n",
    "  \"matchup_home\" TEXT,         -- Matchup details including opponent (e.g., \"LAL vs. BOS\")\n",
    "  \"wl_home\" TEXT,              -- \"W\" if the home team won, \"L\" if they lost\n",
    "  \"min\" INTEGER,               -- Total minutes played in the game\n",
    "  \"fgm_home\" REAL,             -- Field goals made by the home team\n",
    "  \"fga_home\" REAL,             -- Field goals attempted by the home team\n",
    "  \"fg_pct_home\" REAL,          -- Field goal percentage of the home team\n",
    "  \"fg3m_home\" REAL,            -- Three-point field goals made by the home team\n",
    "  \"fg3a_home\" REAL,            -- Three-point attempts by the home team\n",
    "  \"fg3_pct_home\" REAL,         -- Three-point field goal percentage of the home team\n",
    "  \"ftm_home\" REAL,             -- Free throws made by the home team\n",
    "  \"fta_home\" REAL,             -- Free throws attempted by the home team\n",
    "  \"ft_pct_home\" REAL,          -- Free throw percentage of the home team\n",
    "  \"oreb_home\" REAL,            -- Offensive rebounds by the home team\n",
    "  \"dreb_home\" REAL,            -- Defensive rebounds by the home team\n",
    "  \"reb_home\" REAL,             -- Total rebounds by the home team\n",
    "  \"ast_home\" REAL,             -- Assists by the home team\n",
    "  \"stl_home\" REAL,             -- Steals by the home team\n",
    "  \"blk_home\" REAL,             -- Blocks by the home team\n",
    "  \"tov_home\" REAL,             -- Turnovers by the home team\n",
    "  \"pf_home\" REAL,              -- Personal fouls by the home team\n",
    "  \"pts_home\" REAL,             -- Total points scored by the home team\n",
    "  \"plus_minus_home\" INTEGER,   -- Plus/minus rating for the home team\n",
    "  \"video_available_home\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
    "  \"team_id_away\" TEXT,         -- ID of the away team\n",
    "  \"team_abbreviation_away\" TEXT, -- Abbreviation of the away team\n",
    "  \"team_name_away\" TEXT,       -- Full name of the away team\n",
    "  \"matchup_away\" TEXT,         -- Matchup details from the away team’s perspective\n",
    "  \"wl_away\" TEXT,              -- \"W\" if the away team won, \"L\" if they lost\n",
    "  \"fgm_away\" REAL,             -- Field goals made by the away team\n",
    "  \"fga_away\" REAL,             -- Field goals attempted by the away team\n",
    "  \"fg_pct_away\" REAL,          -- Field goal percentage of the away team\n",
    "  \"fg3m_away\" REAL,            -- Three-point field goals made by the away team\n",
    "  \"fg3a_away\" REAL,            -- Three-point attempts by the away team\n",
    "  \"fg3_pct_away\" REAL,         -- Three-point field goal percentage of the away team\n",
    "  \"ftm_away\" REAL,             -- Free throws made by the away team\n",
    "  \"fta_away\" REAL,             -- Free throws attempted by the away team\n",
    "  \"ft_pct_away\" REAL,          -- Free throw percentage of the away team\n",
    "  \"oreb_away\" REAL,            -- Offensive rebounds by the away team\n",
    "  \"dreb_away\" REAL,            -- Defensive rebounds by the away team\n",
    "  \"reb_away\" REAL,             -- Total rebounds by the away team\n",
    "  \"ast_away\" REAL,             -- Assists by the away team\n",
    "  \"stl_away\" REAL,             -- Steals by the away team\n",
    "  \"blk_away\" REAL,             -- Blocks by the away team\n",
    "  \"tov_away\" REAL,             -- Turnovers by the away team\n",
    "  \"pf_away\" REAL,              -- Personal fouls by the away team\n",
    "  \"pts_away\" REAL,             -- Total points scored by the away team\n",
    "  \"plus_minus_away\" INTEGER,   -- Plus/minus rating for the away team\n",
    "  \"video_available_away\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
    "  \"season_type\" TEXT           -- Regular season or playoffs\n",
    ");\n",
    "\n",
    "other_stats Table\n",
    "Stores additional statistics, linked to the game table via game_id.\n",
    "CREATE TABLE IF NOT EXISTS \"other_stats\" (\n",
    "  \"game_id\" TEXT,             -- Unique game identifier, matches id column from game table\n",
    "  \"league_id\" TEXT,           -- League identifier\n",
    "  \"team_id_home\" TEXT,        -- Home team identifier\n",
    "  \"team_abbreviation_home\" TEXT, -- Home team abbreviation\n",
    "  \"team_city_home\" TEXT,      -- Home team city\n",
    "  \"pts_paint_home\" INTEGER,   -- Points in the paint by the home team\n",
    "  \"pts_2nd_chance_home\" INTEGER, -- Second chance points by the home team\n",
    "  \"pts_fb_home\" INTEGER,      -- Fast break points by the home team\n",
    "  \"largest_lead_home\" INTEGER,-- Largest lead by the home team\n",
    "  \"lead_changes\" INTEGER,     -- Number of lead changes \n",
    "  \"times_tied\" INTEGER,       -- Number of times the score was tied\n",
    "  \"team_turnovers_home\" INTEGER, -- Home team turnovers\n",
    "  \"total_turnovers_home\" INTEGER, -- Total turnovers by the home team\n",
    "  \"team_rebounds_home\" INTEGER, -- Home team rebounds\n",
    "  \"pts_off_to_home\" INTEGER,  -- Points off turnovers by the home team\n",
    "  \"team_id_away\" TEXT,        -- Away team identifier\n",
    "  \"team_abbreviation_away\" TEXT,  -- Away team abbreviation\n",
    "  \"pts_paint_away\" INTEGER,   -- Points in the paint by the away team\n",
    "  \"pts_2nd_chance_away\" INTEGER, -- Second chance points by the away team\n",
    "  \"pts_fb_away\" INTEGER,      -- Fast break points by the away team\n",
    "  \"largest_lead_away\" INTEGER,-- Largest lead by the away team\n",
    "  \"team_turnovers_away\" INTEGER, -- Away team turnovers\n",
    "  \"total_turnovers_away\" INTEGER, -- Total turnovers by the away team\n",
    "  \"team_rebounds_away\" INTEGER, -- Away team rebounds\n",
    "  \"pts_off_to_away\" INTEGER   -- Points off turnovers by the away team\n",
    ");\n",
    "\n",
    "\n",
    "Team Name Information\n",
    "In the plaintext user questions, only the full team names will be used, but in the queries you may use the full team names or the abbreviations. \n",
    "The full team names can be used with the game table, while the abbreviations should be used with the other_stats table.\n",
    "Notice they are separated by the | character in the following list:\n",
    "\n",
    "Atlanta Hawks|ATL\n",
    "Boston Celtics|BOS\n",
    "Cleveland Cavaliers|CLE\n",
    "New Orleans Pelicans|NOP\n",
    "Chicago Bulls|CHI\n",
    "Dallas Mavericks|DAL\n",
    "Denver Nuggets|DEN\n",
    "Golden State Warriors|GSW\n",
    "Houston Rockets|HOU\n",
    "Los Angeles Clippers|LAC\n",
    "Los Angeles Lakers|LAL\n",
    "Miami Heat|MIA\n",
    "Milwaukee Bucks|MIL\n",
    "Minnesota Timberwolves|MIN\n",
    "Brooklyn Nets|BKN\n",
    "New York Knicks|NYK\n",
    "Orlando Magic|ORL\n",
    "Indiana Pacers|IND\n",
    "Philadelphia 76ers|PHI\n",
    "Phoenix Suns|PHX\n",
    "Portland Trail Blazers|POR\n",
    "Sacramento Kings|SAC\n",
    "San Antonio Spurs|SAS\n",
    "Oklahoma City Thunder|OKC\n",
    "Toronto Raptors|TOR\n",
    "Utah Jazz|UTA\n",
    "Memphis Grizzlies|MEM\n",
    "Washington Wizards|WAS\n",
    "Detroit Pistons|DET\n",
    "Charlotte Hornets|CHA\n",
    "\n",
    "Query Guidelines\n",
    "Use team_name_home and team_name_away to match teams to the game table. Use team_abbreviation_home and team_abbreviation away to match teams to the other_stats table.\n",
    "\n",
    "To filter by season, use season_id = '2YYYY'.\n",
    "\n",
    "Example: To get statistics from 2005, use a statement like: season_id = '22005'. To get statistics from 1972, use a statement like: season_id = \"21972\". To get statistics from 2015, use a statement like: season_id = \"22015\".\n",
    "\n",
    "Ensure queries return relevant columns and avoid unnecessary joins.\n",
    "\n",
    "Example User Requests and SQLite Queries\n",
    "Request:\n",
    "\"What is the most points the Los Angeles Lakers have ever scored at home?\"\n",
    "SQLite:\n",
    "SELECT MAX(pts_home) \n",
    "FROM game \n",
    "WHERE team_name_home = 'Los Angeles Lakers';\n",
    "\n",
    "Request:\n",
    "\"Which teams are located in the state of California?\"\n",
    "SQLite:\n",
    "SELECT full_name FROM team WHERE state = 'California';\n",
    "\n",
    "Request:\n",
    "\"Which team had the highest number of team turnovers in an away game?\"\n",
    "SQLite:\n",
    "SELECT team_abbreviation_away FROM other_stats ORDER BY team_turnovers_away DESC LIMIT 1;\n",
    "\n",
    "Request:\n",
    "\"Which teams were founded before 1979?\"\n",
    "SQLite:\n",
    "SELECT full_name FROM team WHERE year_founded < 1979;\n",
    "\n",
    "Request:\n",
    "\"Find the Boston Celtics largest home victory margin in the 2008 season.\"\n",
    "SQLite:\n",
    "SELECT MAX(pts_home - pts_away) AS biggest_win\n",
    "FROM game\n",
    "WHERE team_name_home = 'Boston Celtics' AND season_id = '22008';\n",
    "\n",
    "Generate only the SQLite query prefaced by SQLite: and no other text, do not output an explanation of the query. Now generate an SQLite query for the following user request. Request:\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Test model performance on a single example"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SQLite:\n",
      "SELECT team_abbreviation_away \n",
      "FROM other_stats \n",
      "WHERE wl_away = 'W' AND total_turnovers_away < (SELECT MIN(total_turnovers_away) FROM other_stats WHERE wl_away = 'L');\n",
      "\n"
     ]
    }
   ],
   "source": [
    "# Create message with sample query and run model\n",
    "message=[{ 'role': 'user', 'content': input_text + sample[\"natural_query\"].values[0]}]\n",
    "inputs = tokenizer.apply_chat_template(message, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n",
    "outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)\n",
    "\n",
    "# Print output\n",
    "query_output = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)\n",
    "print(query_output)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Test sample output on sqlite3 database"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cleaned\n"
     ]
    }
   ],
   "source": [
    "import sqlite3 as sql\n",
    "\n",
    "# Create connection to sqlite3 database\n",
    "connection = sql.connect('./nba-data/nba.sqlite')\n",
    "cursor = connection.cursor()\n",
    "\n",
    "# Execute query from model output and print result\n",
    "if query_output[0:7] == \"SQLite:\":\n",
    "    print(\"cleaned\")\n",
    "    query = query_output[7:]\n",
    "elif query_output[0:4] == \"SQL:\":\n",
    "    query = query_output[4:]\n",
    "else:\n",
    "    query = query_output\n",
    "\n",
    "try:\n",
    "    cursor.execute(query)\n",
    "    rows = cursor.fetchall()\n",
    "    for row in rows:\n",
    "        print(row)\n",
    "except:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create function to compare output to ground truth result from examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "What is the largest lead the Minnesota Timberwolves had at home?\n",
      "SELECT MAX(largest_lead_home) as max_lead  FROM other_stats  WHERE team_abbreviation_home = 'MIN';\n",
      "48.0\n",
      "SQLite:\n",
      "SELECT MAX(largest_lead_home) \n",
      "FROM other_stats \n",
      "WHERE team_name_home = 'Minnesota Timberwolves';\n",
      "\n",
      "Statement valid? False\n",
      "SQLite matched? False\n",
      "Result matched? False\n"
     ]
    }
   ],
   "source": [
    "import math\n",
    "\n",
    "def compare_result(sample_query, sample_result, query_output):\n",
    "    # Clean model output to only have the query output\n",
    "    if query_output[0:7] == \"SQLite:\":\n",
    "        query = query_output[7:]\n",
    "    elif query_output[0:4] == \"SQL:\":\n",
    "        query = query_output[4:]\n",
    "    else:\n",
    "        query = query_output\n",
    "    \n",
    "    # Try to execute query, if it fails, then this is a failure of the model\n",
    "    try:\n",
    "        # Execute query and obtain result\n",
    "        cursor.execute(query)\n",
    "        rows = cursor.fetchall()\n",
    "\n",
    "        # Strip all whitespace before comparing queries since there may be differences in spacing, newlines, tabs, etc.\n",
    "        query = query.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n",
    "        sample_query = sample_query.replace(\" \", \"\").replace(\"\\n\", \"\").replace(\"\\t\", \"\")\n",
    "        query_match = (query == sample_query)\n",
    "\n",
    "        # If the queries match, the results clearly also match\n",
    "        if query_match:\n",
    "            return True, True, True\n",
    "\n",
    "        # Check if this is a multi-line query\n",
    "        if \"|\" in sample_result or \"(\" in sample_result:\n",
    "            #print(rows)\n",
    "            # Create list of results by stripping separators and splitting on them\n",
    "            if \"(\" in sample_result:\n",
    "                sample_result = sample_result.replace(\"(\", \"\").replace(\")\", \"\")\n",
    "                result_list = sample_result.split(\",\") \n",
    "            else:\n",
    "                result_list = sample_result.split(\"|\") \n",
    "\n",
    "            # Strip all results in list\n",
    "            for i in range(len(result_list)):\n",
    "                result_list[i] = str(result_list[i]).strip()\n",
    "            \n",
    "            # Loop through model result and see if it matches training example\n",
    "            result = False\n",
    "            for row in rows:\n",
    "                for r in row:\n",
    "                    for res in result_list:\n",
    "                        try:\n",
    "                            if math.isclose(float(r), float(res), abs_tol=0.5):\n",
    "                                return True, query_match, True\n",
    "                        except:\n",
    "                            if r in res or res in r:\n",
    "                                return True, query_match, True\n",
    "                    \n",
    "            # Check if the model returned a sum of examples as opposed to the whole thing\n",
    "            if len(rows) == 1:\n",
    "                for r in rows[0]:\n",
    "                    if r == str(len(result_list)):\n",
    "                        return True, query_match, True\n",
    "                    \n",
    "            return True, query_match, result\n",
    "        # Else the sample result is a single value or string\n",
    "        else:\n",
    "            #print(rows)\n",
    "            result = False\n",
    "            # Loop through model result and see if it contains the sample result\n",
    "            for row in rows:\n",
    "                for r in row:\n",
    "                    # Check by string\n",
    "                    if str(r) in str(sample_result):\n",
    "                        try:\n",
    "                            if math.isclose(float(r), float(sample_result), abs_tol=0.5):\n",
    "                                return True, query_match, True\n",
    "                        except:\n",
    "                            return True, query_match, True\n",
    "                    # Check by number, using try incase the cast as float fails\n",
    "                    try:\n",
    "                        if math.isclose(float(r), float(sample_result), abs_tol=0.5):\n",
    "                            return True, query_match, True\n",
    "                    except:\n",
    "                        pass\n",
    "\n",
    "            # Check if the model returned a list of examples instead of a total sum (both acceptable)\n",
    "            try:\n",
    "                if len(rows) > 1 and len(rows) == int(sample_result):\n",
    "                    return True, query_match, True\n",
    "                if len(rows[0]) > 1 and rows[0][1] is not None and  len(rows[0]) == int(sample_result):\n",
    "                    return True, query_match, True\n",
    "            except:\n",
    "                pass\n",
    "\n",
    "            # Compare results and return\n",
    "            return True, query_match, result\n",
    "    except:\n",
    "        return False, False, False\n",
    "\n",
    "# Obtain sample\n",
    "sample = df.sample(n=1)\n",
    "print(sample[\"natural_query\"].values[0])\n",
    "print(sample[\"sql_query\"].values[0])\n",
    "print(sample[\"result\"].values[0])\n",
    "\n",
    "# Create message with sample query and run model\n",
    "message=[{ 'role': 'user', 'content': input_text + sample[\"natural_query\"].values[0]}]\n",
    "inputs = tokenizer.apply_chat_template(message, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n",
    "outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)\n",
    "\n",
    "# Print output\n",
    "query_output = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)\n",
    "print(query_output)\n",
    "\n",
    "result = compare_result(sample[\"sql_query\"].values[0], sample[\"result\"].values[0], query_output)\n",
    "print(\"Statement valid? \" + str(result[0]))\n",
    "print(\"SQLite matched? \" + str(result[1]))\n",
    "print(\"Result matched? \" + str(result[2]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Create function to evaluate pretrained model on full datasets"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "def run_evaluation(nba_df, title):\n",
    "    counter = 0\n",
    "    num_valid = 0\n",
    "    num_sql_matched = 0\n",
    "    num_result_matched = 0\n",
    "    for index, row in nba_df.iterrows():\n",
    "        # Create message with sample query and run model\n",
    "        message=[{ 'role': 'user', 'content': input_text + row[\"natural_query\"]}]\n",
    "        inputs = tokenizer.apply_chat_template(message, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n",
    "        outputs = model.generate(inputs, max_new_tokens=512, do_sample=False, top_k=50, top_p=0.95, num_return_sequences=1, eos_token_id=tokenizer.eos_token_id)\n",
    "\n",
    "        # Obtain output\n",
    "        query_output = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)\n",
    "\n",
    "        # Evaluate model result\n",
    "        valid, sql_matched, result_matched = compare_result(row[\"sql_query\"], row[\"result\"], query_output)\n",
    "        if valid:\n",
    "            num_valid += 1\n",
    "        if sql_matched:\n",
    "            num_sql_matched += 1\n",
    "        if result_matched:\n",
    "            num_result_matched += 1\n",
    "\n",
    "        # Break after predefined number of examples\n",
    "        counter += 1\n",
    "        if counter % 50 == 0:\n",
    "            print(\"Completed \" + str(counter))\n",
    "\n",
    "    # Print evaluation results\n",
    "    print(\"\\n\" + title + \" results:\")\n",
    "    print(\"Percent valid: \" + str(num_valid / len(nba_df)))\n",
    "    print(\"Percent SQLite matched: \" + str(num_sql_matched / len(nba_df)))\n",
    "    print(\"Percent result matched: \" + str(num_result_matched / len(nba_df)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Evaluate on less than 90 dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Completed 50\n",
      "Completed 100\n",
      "Completed 150\n",
      "Completed 200\n",
      "\n",
      "Less than 90 results:\n",
      "Percent valid: 0.8448979591836735\n",
      "Percent SQLite matched: 0.43673469387755104\n",
      "Percent result matched: 0.6530612244897959\n",
      "Dataset length: 245\n"
     ]
    }
   ],
   "source": [
    "less_than_90_df = pd.read_csv(\"./train-data/less_than_90.tsv\", sep='\\t')\n",
    "run_evaluation(less_than_90_df, \"Less than 90\")\n",
    "print(\"Dataset length: \" + str(len(less_than_90_df)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Evaluate on game table queries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Completed 50\n",
      "Completed 100\n",
      "Completed 150\n",
      "Completed 200\n",
      "Completed 250\n",
      "Completed 300\n",
      "Completed 350\n",
      "Completed 400\n",
      "Completed 450\n",
      "Completed 500\n",
      "Completed 550\n",
      "Completed 600\n",
      "Completed 650\n",
      "Completed 700\n",
      "Completed 750\n",
      "Completed 800\n",
      "\n",
      "Queries from game results:\n",
      "Percent valid: 0.7613365155131265\n",
      "Percent SQLite matched: 0.13842482100238662\n",
      "Percent result matched: 0.383054892601432\n",
      "Dataset length: 838\n"
     ]
    }
   ],
   "source": [
    "game_queries = pd.read_csv(\"./train-data/queries_from_game.tsv\", sep='\\t')\n",
    "run_evaluation(game_queries, \"Queries from game\")\n",
    "print(\"Dataset length: \" + str(len(game_queries)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate on other stats queries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Completed 50\n",
      "Completed 100\n",
      "Completed 150\n",
      "\n",
      "Queries from other stats results:\n",
      "Percent valid: 0.21428571428571427\n",
      "Percent SQLite matched: 0.01948051948051948\n",
      "Percent result matched: 0.07142857142857142\n",
      "Dataset length: 154\n"
     ]
    }
   ],
   "source": [
    "other_stats_queries = pd.read_csv(\"./train-data/queries_from_other_stats.tsv\", sep='\\t')\n",
    "run_evaluation(other_stats_queries, \"Queries from other stats\")\n",
    "print(\"Dataset length: \" + str(len(other_stats_queries)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate on team queries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Completed 50\n",
      "\n",
      "Queries from team results:\n",
      "Percent valid: 0.8653846153846154\n",
      "Percent SQLite matched: 0.5961538461538461\n",
      "Percent result matched: 0.7884615384615384\n",
      "Dataset length: 52\n"
     ]
    }
   ],
   "source": [
    "team_queries = pd.read_csv(\"./train-data/queries_from_team.tsv\", sep='\\t')\n",
    "run_evaluation(team_queries, \"Queries from team\")\n",
    "print(\"Dataset length: \" + str(len(team_queries)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate on queries requiring join statements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Completed 50\n",
      "Completed 100\n",
      "Completed 150\n",
      "\n",
      "Queries with join results:\n",
      "Percent valid: 0.1945945945945946\n",
      "Percent SQLite matched: 0.0\n",
      "Percent result matched: 0.04864864864864865\n",
      "Dataset length: 185\n"
     ]
    }
   ],
   "source": [
    "join_queries = pd.read_csv(\"./train-data/with_join.tsv\", sep='\\t')\n",
    "run_evaluation(join_queries, \"Queries with join\")\n",
    "print(\"Dataset length: \" + str(len(join_queries)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate on queries not requiring join statements"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Completed 50\n",
      "Completed 100\n",
      "Completed 150\n",
      "Completed 200\n",
      "Completed 250\n",
      "Completed 300\n",
      "Completed 350\n",
      "Completed 400\n",
      "Completed 450\n",
      "Completed 500\n",
      "Completed 550\n",
      "Completed 600\n",
      "Completed 650\n",
      "Completed 700\n",
      "Completed 750\n",
      "Completed 800\n",
      "Completed 850\n",
      "\n",
      "Queries without join results:\n",
      "Percent valid: 0.7916181606519208\n",
      "Percent SQLite matched: 0.17462165308498254\n",
      "Percent result matched: 0.42374854481955765\n",
      "Dataset length: 859\n"
     ]
    }
   ],
   "source": [
    "no_join_queries = pd.read_csv(\"./train-data/without_join.tsv\", sep='\\t')\n",
    "run_evaluation(no_join_queries, \"Queries without join\")\n",
    "print(\"Dataset length: \" + str(len(no_join_queries)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Evaluate on full training dataset"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Completed 50\n",
      "Completed 100\n",
      "Completed 150\n",
      "Completed 200\n",
      "Completed 250\n",
      "Completed 300\n",
      "Completed 350\n",
      "Completed 400\n",
      "Completed 450\n",
      "Completed 500\n",
      "Completed 550\n",
      "Completed 600\n",
      "Completed 650\n",
      "Completed 700\n",
      "Completed 750\n",
      "Completed 800\n",
      "Completed 850\n",
      "Completed 900\n",
      "Completed 950\n",
      "Completed 1000\n",
      "\n",
      "All training data results:\n",
      "Percent valid: 0.685823754789272\n",
      "Percent SQLite matched: 0.14367816091954022\n",
      "Percent result matched: 0.35823754789272033\n",
      "Dataset length: 1044\n"
     ]
    }
   ],
   "source": [
    "# Run evaluation on all training data\n",
    "run_evaluation(df, \"All training data\")\n",
    "print(\"Dataset length: \" + str(len(df)))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}