forked from FRCTeam238/PiScout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
1458 lines (1334 loc) · 53.2 KB
/
server.py
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
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import cherrypy
import sqlite3 as sql
import os
import json
from ast import literal_eval
import requests
import math
import server
from event import CURRENT_EVENT
import gamespecific as game
import serverinfo
import sys
import re
from genshi.template import TemplateLoader
import proprietary as prop
localInstance = False
loader = TemplateLoader(
os.path.join(os.path.dirname(__file__), "web/templates"), auto_reload=True
)
class ScoutServer(object):
# Make sure that database for current event exists on startup
def __init__(self):
self.database_exists()
# Home page
@cherrypy.expose
def index(self, m="", e=""):
# Add auth value to session if not present
sessionCheck()
# Handle event selection. When the event is changed, a POST request is sent here.
if e != "":
cherrypy.session["event"] = e
if "Referer" in cherrypy.request.headers:
raise cherrypy.HTTPRedirect(cherrypy.request.headers["Referer"])
# Handle mode selection. When the mode is changed, a POST request is sent here.
if m != "":
cherrypy.session["mode"] = m
if "Referer" in cherrypy.request.headers:
raise cherrypy.HTTPRedirect(cherrypy.request.headers["Referer"])
data = getAggregateData(Event=getEvent())
if cherrypy.session["mode"] == "Season":
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
teams = (
conn.cursor()
.execute(
"SELECT DISTINCT TeamNumber from Participation WHERE EventCode=?",
(getEvent(),),
)
.fetchall()
)
data = []
for i, team in enumerate(teams):
averages = getAggregateData(Team=str(team[0]), Mode="Averages")
if len(averages):
data.append(averages[0])
# Pass off the normal set of columns or columns with the hidden fields depending on authentication
# if checkAuth(False):
# columns = game.DISPLAY_FIELDS
#else:
columns = {**game.DISPLAY_FIELDS, **game.HIDDEN_DISPLAY_FIELDS}
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
eventName = (
conn.cursor()
.execute("SELECT Name from Events WHERE EventCode=?", (getEvent(),))
.fetchall()
)
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("index.xhtml")
page = tmpl.generate(
columns=columns,
title="Home",
eventName=eventName[0]["Name"],
session=cherrypy.session,
data=data,
events=events,
)
return page.render("html", doctype="html")
# Page for creating picklist
@cherrypy.expose
def picklist(self, list="", dnp="", unassigned=""):
sessionCheck()
if not checkAuth(False):
raise cherrypy.HTTPError(
401, "Not authorized to view picklist. Please log in and try again."
)
if checkAuth(True):
auth = "admin"
else:
auth = "user"
if list:
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
pattern = re.compile("team\[\]=(\d*)")
pickList = pattern.findall(list)
for order, team in enumerate(pickList):
sqlCommand = "UPDATE Picklist SET list=?, rank=? WHERE TeamNumber=? AND EventCode=?"
conn.cursor().execute(sqlCommand, ("Pick", order + 1, team, getEvent()))
conn.commit()
conn.close()
if dnp:
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
pattern = re.compile("team\[\]=(\d*)")
dnpList = pattern.findall(dnp)
for order, team in enumerate(dnpList):
sqlCommand = "UPDATE Picklist SET list=?, rank=? WHERE TeamNumber=? AND EventCode=?"
conn.cursor().execute(sqlCommand, ("DNP", order + 1, team, getEvent()))
conn.commit()
conn.close()
if unassigned:
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
pattern = re.compile("team\[\]=(\d*)")
orderedList = pattern.findall(unassigned)
for order, team in enumerate(orderedList):
sqlCommand = "UPDATE Picklist SET list=?, rank=? WHERE TeamNumber=? AND EventCode=?"
conn.cursor().execute(
sqlCommand, ("Unassigned", order + 1, team, getEvent())
)
conn.commit()
conn.close()
# This section generates the table of averages
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
columns = {**game.DISPLAY_FIELDS, **game.HIDDEN_DISPLAY_FIELDS}
sqlAvgCommandBase = "SELECT "
sqlMaxCommandBase = "SELECT "
for key in columns:
sqlMaxCommandBase += "MAX(" + key + ") AS " + key + ", "
for key in columns:
sqlAvgCommandBase += "round(AVG(" + key + "),2) AS " + key + ", "
sqlMaxCommandBase = sqlMaxCommandBase[:-2]
sqlAvgCommandBase = sqlAvgCommandBase[:-2]
if getMode() == "Variance":
sqlCommandBase = sqlMaxCommandBase
else:
sqlCommandBase = sqlAvgCommandBase
noDefense = " AND Defense=0" if getMode() == "NoDefense" else ""
eventString = " AND ScoutRecords.EventCode='" + getEvent() + "'"
joinString = "ScoutRecords join Picklist on ScoutRecords.Team=Picklist.TeamNumber AND ScoutRecords.EventCode=Picklist.EventCode "
listString = " AND LIST='Pick'"
table = (
" FROM (Select * from (SELECT *, row_number() over (partition by Team order by match desc) as match_rank from "
+ joinString
+ "WHERE Flag=0"
+ eventString
+ listString
+ ") where match_rank <= 3)"
if getMode() == "Trends"
else " FROM " + joinString + "WHERE Flag=0" + eventString + listString
)
sqlCommand = (
sqlCommandBase + table + noDefense + " GROUP BY Team ORDER BY Rank ASC"
)
pickListData = conn.cursor().execute(sqlCommand).fetchall()
if getMode() == "Trends":
avgData = (
conn.cursor()
.execute(
sqlCommandBase
+ " FROM ScoutRecords WHERE Flag=0"
+ eventString
+ " GROUP BY Team ORDER BY Rank ASC",
)
.fetchall()
)
latestData = pickListData.copy()
pickListData = []
for i, row in enumerate(latestData):
rowData = dict(columns)
for key in rowData:
if key == "Team":
rowData[key] = row[key]
else:
rowData[key] = round(row[key] - avgData[i][key], 2)
pickListData.append(rowData)
if getMode() == "Variance":
avgData = (
conn.cursor()
.execute(
sqlAvgCommandBase
+ " FROM ScoutRecords WHERE Flag=0"
+ eventString
+ " GROUP BY Team ORDER BY Rank ASC",
)
.fetchall()
)
maxData = pickListData.copy()
picklistData = []
for i, row in enumerate(maxData):
rowData = dict(columns)
for key in rowData:
if key == "Team":
rowData[key] = row[key]
else:
rowData[key] = round(row[key] - avgData[i][key], 2)
pickListData.append(rowData)
listString = " AND LIST='DNP'"
table = (
" FROM (Select * from (SELECT *, row_number() over (partition by Team order by match desc) as match_rank from "
+ joinString
+ "WHERE Flag=0"
+ eventString
+ listString
+ ") where match_rank <= 3)"
if getMode() == "Trends"
else " FROM " + joinString + "WHERE Flag=0" + eventString + listString
)
sqlCommand = (
sqlCommandBase + table + noDefense + " GROUP BY Team ORDER BY Rank ASC"
)
dnpData = conn.cursor().execute(sqlCommand).fetchall()
if getMode() == "Trends":
avgData = (
conn.cursor()
.execute(
sqlCommandBase
+ " FROM ScoutRecords WHERE Flag=0"
+ eventString
+ " GROUP BY Team ORDER BY Rank ASC",
)
.fetchall()
)
latestData = dnpData.copy()
dnpData = []
for i, row in enumerate(latestData):
rowData = dict(columns)
for key in rowData:
if key == "Team":
rowData[key] = row[key]
else:
rowData[key] = round(row[key] - avgData[i][key], 2)
dnpData.append(rowData)
if getMode() == "Variance":
avgData = (
conn.cursor()
.execute(
sqlAvgCommandBase
+ " FROM ScoutRecords WHERE Flag=0"
+ eventString
+ " GROUP BY Team ORDER BY Rank ASC",
)
.fetchall()
)
maxData = dnpData.copy()
dnpData = []
for i, row in enumerate(maxData):
rowData = dict(columns)
for key in rowData:
if key == "Team":
rowData[key] = row[key]
else:
rowData[key] = round(row[key] - avgData[i][key], 2)
dnpData.append(rowData)
listString = " AND LIST='Unassigned'"
table = (
" FROM (Select * from (SELECT *, row_number() over (partition by Team order by match desc) as match_rank from "
+ joinString
+ "WHERE Flag=0"
+ eventString
+ listString
+ ") where match_rank <= 3)"
if getMode() == "Trends"
else " FROM " + joinString + "WHERE Flag=0" + eventString + listString
)
sqlCommand = (
sqlCommandBase + table + noDefense + " GROUP BY Team ORDER BY Rank ASC"
)
teamData = conn.cursor().execute(sqlCommand).fetchall()
if getMode() == "Trends":
avgData = (
conn.cursor()
.execute(
sqlCommandBase
+ " FROM ScoutRecords WHERE Flag=0"
+ eventString
+ " GROUP BY Team ORDER BY Rank ASC",
)
.fetchall()
)
latestData = teamData.copy()
teamData = []
for i, row in enumerate(latestData):
rowData = dict(columns)
for key in rowData:
if key == "Team":
rowData[key] = row[key]
else:
rowData[key] = round(row[key] - avgData[i][key], 2)
teamData.append(rowData)
if getMode() == "Variance":
avgData = (
conn.cursor()
.execute(
sqlAvgCommandBase
+ " FROM ScoutRecords WHERE Flag=0"
+ eventString
+ " GROUP BY Team ORDER BY Rank ASC",
)
.fetchall()
)
maxData = teamData.copy()
teamData = []
for i, row in enumerate(maxData):
rowData = dict(columns)
for key in rowData:
if key == "Team":
rowData[key] = row[key]
else:
rowData[key] = round(row[key] - avgData[i][key], 2)
teamData.append(rowData)
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("picklist.xhtml")
page = tmpl.generate(
columns=columns,
session=cherrypy.session,
teams=teamData,
dnp=dnpData,
picklist=pickListData,
auth=auth,
events=events,
)
return page.render("html", doctype="html")
# Page to show result of login attempt
@cherrypy.expose()
def login(self, auth=""):
sessionCheck()
loginResult = "Login failed! Please check password"
if auth == serverinfo.AUTH:
cherrypy.session["auth"] = auth
loginResult = "Login successful"
if auth == serverinfo.ADMIN:
cherrypy.session["admin"] = auth
cherrypy.session["auth"] = serverinfo.AUTH
loginResult = "Admin Login successful"
referrer = ""
if "Referer" in cherrypy.request.headers:
referer = cherrypy.request.headers["Referer"]
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("login.xhtml")
page = tmpl.generate(
result=loginResult, session=cherrypy.session, referer=referer, events=events
)
return page.render("html", doctype="html")
# Show a detailed summary for a given team
@cherrypy.expose()
def team(self, n="238"):
sessionCheck()
if not n.isdigit():
raise cherrypy.HTTPRedirect("/")
# Grab team data
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
entries = cursor.execute(
"SELECT rowid,* FROM ScoutRecords WHERE Team=? AND EventCode=? ORDER BY Match ASC",
(n, getEvent()),
).fetchall()
sql_averages = getAggregateData(Team=n, Event=getEvent())
commentsRow = cursor.execute(
"SELECT Comments FROM Teams WHERE TeamNumber=?", (n,)
).fetchone()
if commentsRow[0] is not None:
comments = convertStringToArray(commentsRow[0])
else:
comments = []
sqlCommand = "SELECT "
for key in game.PIT_SCOUT_FIELDS:
sqlCommand += key + ", "
sqlCommand = sqlCommand[:-2]
sqlCommand += " FROM Teams WHERE TeamNumber=?"
sql_pit = cursor.execute(sqlCommand, (n,)).fetchall()
assert len(sql_averages) < 2 # ensure there aren't two entries for one team
assert len(sql_pit) < 2
if len(sql_averages):
averages = sql_averages[0]
else:
averages = dict(game.DISPLAY_FIELDS)
averages.update(game.HIDDEN_DISPLAY_FIELDS)
if len(sql_pit):
pit = sql_pit[0]
else:
pit = 0
# If we have less than 4 entries, see if we can grab data from a previous event
lastEvent = 0
oldAverages = []
if len(entries) < 3:
seasonEntries = cursor.execute(
"SELECT rowid,* FROM ScoutRecords WHERE Team=? ORDER BY Match DESC",
(n,),
).fetchall()
if len(seasonEntries) >= 3:
oldAverages = getAggregateData(Team=n)[0]
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
# Clear out comments if not logged in
if not checkAuth(False):
comments = []
dataset = []
tableData = []
for e in entries:
# Generate chart data and table text for this match entry
dp = game.generateChartData(e)
text = game.generateTeamText(e)
tableEntry = {}
tableEntry["Match"] = e["Match"]
tableEntry["Text"] = text
tableEntry["Flag"] = e["Flag"]
tableEntry["FlagAttr"] = [("style", "color: #B20000")] if e["Flag"] else ""
tableEntry["Key"] = e["ROWID"]
tableData.append(tableEntry)
for key, val in dp.items():
dp[key] = round(val, 2)
if not e["Flag"]:
dataset.append(
dp
) # add it to dataset, which is an array of data that is fed into the graphs
# dataset.reverse() # reverse data so that graph is in the correct order
# Grab the image from the blue alliance
headers = {
"X-TBA-Auth-Key": "n8QdCIF7LROZiZFI7ymlX0fshMBL15uAzEkBgtP1JgUpconm2Wf49pjYgbYMstBF"
}
m = []
try:
# get the picture for a given team
m = self.get(
"http://www.thebluealliance.com/api/v3/team/frc{0}/media/2024".format(
n
),
params=headers,
).json()
if m.status_code == 400:
m = []
except:
pass # swallow the error
image_url = ""
for media in m:
# media['type'] == 'instagram-image' does not currently work correctly on TBA
if media["type"] == "imgur":
image_url = "https://i.imgur.com/" + media["foreign_key"] + "m.jpg"
break
elif media["type"] == "cdphotothread":
image_url = media["direct_url"]
break
if checkAuth(False):
auth = 1
columns = {**game.DISPLAY_FIELDS, **game.HIDDEN_DISPLAY_FIELDS}
else:
auth = 0
columns = game.DISPLAY_FIELDS
tmpl = loader.load("team.xhtml")
page = tmpl.generate(
session=cherrypy.session,
chartData=str(dataset).replace("'", '"'),
image=image_url,
auth=auth,
old_averages=oldAverages,
pitColumns=game.PIT_SCOUT_FIELDS,
pitScout=pit,
columns=columns,
averages=averages,
comments=comments,
chartFields=game.CHART_FIELDS,
matches=tableData,
events=events,
)
return page.render("html", doctype="html")
# Called to toggle flag on a data entry. Also does a recalc to add/remove entry from stats
@cherrypy.expose()
def flag(self, num="", match="", flagval=0):
sessionCheck()
if not checkAuth(True):
raise cherrypy.HTTPError(
401, "Not authorized to flag match data. Please log in and try again"
)
if not (num.isdigit() and match.isdigit()):
raise cherrypy.HTTPError(400, "Team and match must be numeric")
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
cursor.execute(
"UPDATE ScoutRecords SET Flag=? WHERE Team=? AND Match=? AND EventCode=?",
(int(not int(flagval)), num, match, getEvent()),
)
conn.commit()
conn.close()
return ""
# Input interface to choose teams to compare
@cherrypy.expose()
def compareTeams(self):
sessionCheck()
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("compareTeams.xhtml")
page = tmpl.generate(session=cherrypy.session, events=events)
return page.render("html", doctype="html")
# Input interface to choose alliances to compare
@cherrypy.expose
def compareAlliances(self):
sessionCheck()
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("compareAlliances.xhtml")
page = tmpl.generate(session=cherrypy.session, events=events)
return page.render("html", doctype="html")
# Output for team comparison
@cherrypy.expose()
def teams(self, n1="", n2="", n3="", n4="", stat1="", stat2=""):
sessionCheck()
nums = [n1, n2, n3, n4]
nums = [i for i in nums if i != ""]
if stat2 == "none":
stat2 = ""
if not stat1:
stat1 = list(game.CHART_FIELDS)[1]
averages = []
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
output = "<div>"
stats_data = []
# Grab data for each team, and generate a statbox
for index, n in enumerate(nums):
if not n:
continue
if not n.isdigit():
raise cherrypy.HTTPError(400, "You fool! Enter NUMBERS, not letters.")
average = getAggregateData(Team=n, Event=getEvent())
assert len(average) < 2
if len(average):
entry = average[0]
else:
entry = dict(game.DISPLAY_FIELDS)
entry.update(game.HIDDEN_DISPLAY_FIELDS)
stats_data.append(entry)
dataset = []
# For each team, grab each match entry and generate chart data, then add them to the graph
for idx, n in enumerate(nums):
if not n:
continue
entries = cursor.execute(
"SELECT * FROM ScoutRecords WHERE Team=? AND EventCode=? ORDER BY Match ASC",
(n, getEvent()),
).fetchall()
for index, e in enumerate(entries):
if not isinstance(e, tuple):
dp = game.generateChartData(e)
for key, val in dp.items():
dp[key] = round(val, 2)
if not e["Flag"]:
if len(dataset) < (index + 1):
if stat2:
dataPoint = {
"match": (index + 1),
"team" + n + "stat1": dp[stat1],
"team" + n + "stat2": dp[stat2],
}
else:
dataPoint = {
"match": (index + 1),
"team" + n + "stat1": dp[stat1],
}
dataset.append(dataPoint)
else:
dataset[index]["team" + n + "stat1"] = dp[stat1]
if stat2:
dataset[index]["team" + n + "stat2"] = dp[stat2]
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("teams.xhtml")
page = tmpl.generate(
session=cherrypy.session,
chart_data=str(dataset).replace("'", '"'),
columns=game.DISPLAY_FIELDS,
chartColumns=game.CHART_FIELDS,
stat1=stat1,
stat2=stat2,
teams=nums,
stat_data=stats_data,
events=events,
)
return page.render("html", doctype="html")
# Output for alliance comparison
@cherrypy.expose()
def alliances(self, b1="", b2="", b3="", r1="", r2="", r3="", level=""):
sessionCheck()
if level == "":
level = "quals"
numsBlue = [b1, b2, b3]
numsRed = [r1, r2, r3]
averages = []
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
blueData = []
redData = []
# iterate through all six teams and grab data
for i, n in enumerate(numsBlue):
if not n.isdigit():
raise cherrypy.HTTPError(400, "Enter six valid team numbers!")
entries = cursor.execute(
"SELECT * FROM ScoutRecords WHERE Team=? AND EventCode=? ORDER BY Match DESC",
(n, getEvent()),
).fetchall()
prevEvent = 0
teamData = []
teamData.append(getPitDisplayData(n))
if len(entries) < 3:
seasonEntries = cursor.execute(
"SELECT * FROM ScoutRecords WHERE Team=? ORDER BY Match DESC", (n,)
).fetchall()
if len(seasonEntries) >= 3:
oldAverages = getAggregateData(Team=n, Mode="Averages")
assert (
len(oldAverages) < 2
) # ensure there aren't two entries for one team
if len(oldAverages):
teamData.append(oldAverages[0])
prevEvent = 1
if prevEvent == 0:
average = getAggregateData(Team=n, Event=getEvent(), Mode="Averages")
if not len(average):
average = dict(game.SCOUT_FIELDS)
average.update(game.DISPLAY_FIELDS)
average.update(game.HIDDEN_DISPLAY_FIELDS)
average["Team"] = n
teamData.append(average)
else:
teamData.append(average[0])
blueData.append(teamData)
for i, n in enumerate(numsRed):
if not n.isdigit():
raise cherrypy.HTTPError(400, "Enter six valid team numbers!")
entries = cursor.execute(
"SELECT * FROM ScoutRecords WHERE Team=? AND EventCode=? ORDER BY Match DESC",
(n, getEvent()),
).fetchall()
prevEvent = 0
teamData = []
teamData.append(getPitDisplayData(n))
if len(entries) < 3:
seasonEntries = cursor.execute(
"SELECT * FROM ScoutRecords WHERE Team=? ORDER BY Match DESC", (n,)
).fetchall()
if len(seasonEntries) >= 3:
oldAverages = getAggregateData(Team=n, Mode="Averages")
assert (
len(oldAverages) < 2
) # ensure there aren't two entries for one team
if len(oldAverages):
teamData.append(oldAverages[0])
prevEvent = 1
if prevEvent == 0:
average = getAggregateData(Team=n, Event=getEvent(), Mode="Averages")
if not len(average):
average = dict(game.SCOUT_FIELDS)
average.update(game.DISPLAY_FIELDS)
average.update(game.HIDDEN_DISPLAY_FIELDS)
average["Team"] = n
teamData.append(average)
else:
teamData.append(average[0])
redData.append(teamData)
# Predict scores
blue_score = game.predictScore(getEvent(), numsBlue, level)["score"]
red_score = game.predictScore(getEvent(), numsRed, level)["score"]
blue_score = int(blue_score)
red_score = int(red_score)
# Calculate win probability. Currently uses regression from 2016 data, this should be updated
prob_red = 1 / (1 + math.e ** (-0.08099 * (red_score - blue_score)))
red_win=round(prob_red * 100, 1)
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("alliances.xhtml")
page = tmpl.generate(
session=cherrypy.session,
red_win=red_win,
blue_win=round(100-red_win,1),
red_score=red_score,
blue_score=blue_score,
red_data=redData,
blue_data=blueData,
columns=game.DISPLAY_FIELDS,
events=events,
pitColumns=game.PIT_DISPLAY_FIELDS,
)
return page.render("html", doctype="html")
# Lists schedule data from TBA
@cherrypy.expose()
def matches(self, n=""):
sessionCheck()
# Get match data
m = self.getMatches(getEvent())
output = ""
if "feed" in m:
raise cherrypy.HTTPError(503, "Unable to retrieve data about this event.")
# assign weights, so we can sort the matches
for match in m:
match["value"] = match["match_number"]
type = match["comp_level"]
if type == "qf":
match["value"] += 1000
elif type == "sf":
match["value"] += 2000
elif type == "f":
match["value"] += 3000
m = sorted(m, key=lambda k: k["value"])
# For each match, generate a row in the table
for match in m:
level = "quals"
if match["comp_level"] != "qm":
match["num"] = (
match["comp_level"].upper()
+ str(match["set_number"])
+ "_"
+ str(match["match_number"])
)
level = "playoffs"
else:
match["num"] = match["match_number"]
if match["alliances"]["blue"]["score"] == -1:
match["alliances"]["blue"]["score"] = ""
if match["alliances"]["red"]["score"] == -1:
match["alliances"]["red"]["score"] = ""
blueTeams = [
match["alliances"]["blue"]["team_keys"][0][3:],
match["alliances"]["blue"]["team_keys"][1][3:],
match["alliances"]["blue"]["team_keys"][2][3:],
]
match["bluePredict"] = game.predictScore(getEvent(), blueTeams, level)
redTeams = [
match["alliances"]["red"]["team_keys"][0][3:],
match["alliances"]["red"]["team_keys"][1][3:],
match["alliances"]["red"]["team_keys"][2][3:],
]
match["redPredict"] = game.predictScore(getEvent(), redTeams, level)
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
events = conn.cursor().execute("SELECT * from Events").fetchall()
conn.close()
tmpl = loader.load("matches.xhtml")
page = tmpl.generate(session=cherrypy.session, matches=m, events=events)
return page.render("html", doctype="html")
# Used by the scanning program to submit data, and used by comment system to submit data
@cherrypy.expose()
def submit(self, auth="", data="", pitData="", event="", team="", comment=""):
if not (data or team or pitData):
return """
<h1>FATAL ERROR</h1>
<h3>DATA CORRUPTION</h3>"""
if data == "json":
return "[]" # bogus json for local version
if not event:
event = getEvent()
self.database_exists()
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
# If team is defined, this should be a comment
if team:
if not comment:
conn.close()
raise cherrypy.HTTPRedirect("/team?n=" + str(team))
if not checkAuth(False):
conn.close()
raise cherrypy.HTTPError(
401,
"Error: Not authorized to submit comments. Please login and try again",
)
comments = cursor.execute(
"SELECT Comments FROM Teams WHERE TeamNumber=?", (team,)
).fetchone()
if comments[0] is None:
cursor.execute(
"UPDATE Teams SET Comments=? WHERE TeamNumber=?", (comment, team)
)
else:
existing = convertStringToArray(comments[0])
existing.append(comment)
cursor.execute(
"UPDATE Teams SET Comments=? WHERE TeamNumber=?",
(convertArrayToString(existing), team),
)
conn.commit()
conn.close()
raise cherrypy.HTTPRedirect("/team?n=" + str(team))
# If team is not defined, this should be scout data. First check auth key
if auth == serverinfo.AUTH:
if data:
d = literal_eval(data)
# Check if data should be flagged due to conflicting game specific values
flag = game.autoFlag(d)
# If match schedule is available, check if this is a real match and flag if bad
try:
m = self.getMatches(event)
if m:
match = next(
(
item
for item in m
if (item["match_number"] == d["Match"])
and (item["comp_level"] == "qm")
)
)
teams = (
match["alliances"]["blue"]["team_keys"]
+ match["alliances"]["red"]["team_keys"]
)
if not "frc" + str(d["Team"]) in teams:
flag = 1
except:
pass
# If replay is marked, replace previous data
if d["Replay"]: # replay
cursor.execute(
"DELETE from ScoutRecords WHERE Team=? AND Match=? AND EventCode=?",
(str(d["Team"]), str(d["Match"]), event),
)
# Insert data into database
cursor.execute(
"INSERT OR IGNORE INTO Teams(TeamNumber) VALUES(?)", (d["Team"],)
)
cursor.execute(
"INSERT OR IGNORE INTO Participation VALUES (NULL,?,?)",
(d["Team"], event),
)
cursor.execute(
"INSERT OR IGNORE INTO Picklist(EventCode,TeamNumber,List) VALUES(?,?,?)",
(event, (d["Team"]), "Unassigned"),
)
cursor.execute(
"INSERT INTO ScoutRecords VALUES (?,"
+ ",".join([str(a) for a in d.values()])
+ ")",
(event,),
)
conn.commit()
conn.close()
return ""
elif pitData:
d = literal_eval(pitData)
values = ""
for i, key in enumerate(game.PIT_SCOUT_FIELDS):
if key == "TeamNumber":
continue
values += key + "=" + str(d[key]) + ", "
values = values[:-2]
cursor.execute(
"INSERT OR IGNORE INTO Teams(TeamNumber) VALUES(?)", (d["TeamNumber"],)
)
cursor.execute(
"UPDATE Teams SET " + values + " WHERE TeamNumber=?",
(d["TeamNumber"],),
)
conn.commit()
conn.close()
return ""
else:
raise cherrypy.HTTPError(401, "Error: Not authorized to submit match data")
#page fo deleting match data
@cherrypy.expose()
def delete(self, key="", auth="", **params):
sessionCheck()
if not checkAuth(False):
if not auth == serverinfo.AUTH:
raise cherrypy.HTTPError(
401, "Not authorized to delete match data. Please log in and try again"
)
if server.localInstance:
with open("deleteQueue.txt", "a+") as file:
file.write(str(key) + "\n")
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
cursor.execute("DELETE from ScoutRecords WHERE rowid=?",(key,))
conn.commit()
conn.close()
# Page for editing match data
@cherrypy.expose()
def edit(self, key="", auth="", **params):
sessionCheck()
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
if not checkAuth(False):
if not auth == serverinfo.AUTH:
raise cherrypy.HTTPError(
401, "Not authorized to edit match data. Please log in and try again"
)
# If there is data, this is a post and data should be used to update the entry
if len(params) > 1:
sqlCommand = "UPDATE ScoutRecords SET "
for name, value in params.items():
sqlCommand += name + "=" + (value if value else "NULL") + " , "
sqlCommand = sqlCommand[:-2]
sqlCommand += "WHERE rowid=" + str(key)
cursor.execute(sqlCommand)
conn.commit()
conn.close()
if server.localInstance:
with open("editQueue.txt", "a+") as file:
params['key']= key
file.write(str(params) + "\n")
# Grab all match data entries from the event, with flagged entries first, then sorted by team, then match
conn = sql.connect(self.datapath())
conn.row_factory = sql.Row
cursor = conn.cursor()
entries = cursor.execute(
"SELECT rowid,* from ScoutRecords WHERE EventCode=? ORDER BY flag DESC, Team ASC, Match ASC",
(getEvent(),),
).fetchall()
if key == "":
key = entries[0][0]
# Grab the currently selected entry