tpy:
import KS2.client_tools import KS2.ks from KS.ks import API_SERVER, TPY_TOP, DEFAULT_TIMEOUT import urllib,os import PyQL.py_tools import re import glob import pytz import pandas as pd import cPickle from PyQL.dt import DT from PyQL.columns import Column from datetime import datetime, timedelta import requests import time from KS2.security import obscure, unobscure, generate_token import S22.common_methods from KS2.subscriber_tools import beta_testers, query_limits, simpleSearch_limits, save_slots, subscriber_copy_access from KS2.scl import screenshot_link if datetime.now().month in [11, 2, 3, 4, 5]: default = 'NBA' elif datetime.now().month in [9, 10, 11, 12, 1]: default = 'NFL' else: default = 'MLB' ports = { 'NBA': 8001, 'NFL': 8002, 'MLB': 8003, 'NCAAFB': 8004, 'NCAABB': 8005, 'NHL': 8006, 'WNBA': 8007, 'ATP': 8008, 'WTA': 8009 } midnight_et_utc_naive = pytz.utc.localize(datetime.utcnow()).astimezone(pytz.timezone('America/New_York')).replace(hour=0, minute=0, second=0, microsecond=0).astimezone(pytz.utc).replace(tzinfo=None) cb_superusers=['dcupworker', 'csack3', 'ctanner9', 'SBB', 'nfeliccia_x', 'bpotts', 'danfab315'] copy_access = ['firstpitch', 'SBB', 'csack3'] allow_copy = 0 def general_log(x, sport): if x not in [9999, -9999]: e_e = {0: 'success', 1: 'noresult', 2: 'type', -1: 'syntax', 9997: 'utimeout', 9998: 'stimeout'} base = '/home/kscREV1/KS/Log/%s_%s_'%(e_e[x], sport) if glob.glob('%s*'%base): v = int(glob.glob('%s*'%base)[0].split('_')[-1].strip('.pkl')) os.rename(glob.glob('%s*'%base)[0], '%s%s.pkl'%(base,v+1)) else: with open('/home/kscREV1/KS/Log/%s_%s_1.pkl'%(e_e[x], sport), 'wb') as f: cPickle.dump(0, f) return old_link = re.findall('/(nfl|nba|mlb|nhl|ncaafb|ncaabb)/query',__d['uri']) if old_link: __d['filter'] = old_link[0].upper() # redirect = 1 # r_url = __d['__host'] + '?filter=%s&sdql=%s&_qt=%s&init=1'%(old_link[0], __d.setdefault("sdql","season=%s"%cs), __d.setdefault('_qt',"games")) sport = __d.get("filter", default) client = __d.get("client","guest") tweet = __d.get("tweet",0) tsc = __d.get("tsc",0) pkey = __d.get("pkey",0) if pkey == '40CJwfGL8n808P5qRUy2': client = 'dcupworker' if 'theme' in __d: theme = __d.get("theme","") else: theme = KS2.client_tools.info(client).get('theme', 'dark') if theme == "light": theme = "-light" ss_base_color = "color: black" #set simplesearch on/off text color else: theme = "" ss_base_color = "color: white" recaptcha_widget = ''; recaptcha_script = '' # <script src="https://www.google.com/recaptcha/api.js?render=6Lf9IncqAAAAAF6MHooLAzIYtfKCQeA4ZhuQOE55"></script> # <script> # if (window.location.pathname !== '/403') { # grecaptcha.ready(function() { # grecaptcha.execute('6Lf9IncqAAAAAF6MHooLAzIYtfKCQeA4ZhuQOE55', { action: 'view_page' }).then(function(token) { # // Send token to your backend to validate # fetch('/verify_recaptcha', { # method: 'POST', # headers: { 'Content-Type': 'application/json' }, # body: JSON.stringify({ token: token }) # }) # .then(response => response.json()) # .then(data => { # if (!data.success) { # //alert("Access denied! You might be a bot."); # window.location.href = "/403"; // Redirect or block access # } # else { # var TOKEN = token; # console.log(token); # // $('#token').val(token); # } # }) # .catch(error => console.error('Error verifying reCAPTCHA:', error)); # }); # }); # } # </script> season_s = { 'nfl': {6: -1, 12: 0}, 'nba': {9: -1, 12: 0}, 'ncaafb': {6: -1, 12: 0}, 'ncaabb': {9: -1, 12: 0}, 'mlb': {2: -1, 12: 0}, 'nhl': {9: -1, 12: 0}, 'wnba': {3: -1, 12: 0}, 'atp': {0: -1, 12: 0}, 'wta': {0: -1, 12: 0} } limit = build_page("/home/kscREV1/KS/Tpy/limit.tpy",__d) fund = build_page("/home/kscREV1/KS/Tpy/fund.tpy",__d) doi = datetime.now() cs = (doi.year + min([season_s[sport.lower()][s] for s in season_s[sport.lower()] if s >= doi.month])) today = PyQL.py_tools.today() getpost = __d.get("sdql",None) token = __d.setdefault("token",generate_token()) sdql = __d.setdefault("sdql","season=%s"%cs) tokenized = unobscure(token) if client == 'guest': if tokenized == 'decryption failed': sdql = "season=%s"%cs elif '*POSTREQUEST*' in tokenized: pass else: sdql = unobscure(token) token = generate_token() elif client != 'guest': if tokenized == 'decryption failed': pass elif '*POSTREQUEST*' in tokenized: pass else: sdql = unobscure(token) token = generate_token() def get_et_midnight_utc(): import pytz from datetime import datetime utc = pytz.utc eastern = pytz.timezone('America/New_York') now_utc = utc.localize(datetime.utcnow()) now_et = now_utc.astimezone(eastern) # Replace to midnight, then normalize midnight_et = eastern.normalize(now_et.replace(hour=0, minute=0, second=0, microsecond=0)) # Convert back to UTC return midnight_et.astimezone(utc) import KS2.client_tools from KS2.ks import TREND_TOP,TREND_SUP,trend_file_top,current_season client_info = KS2.client_tools.client_info(__d) # to get balance cb = int(__d.setdefault("cb",0)) val1 = {'count': 0, 'ip': [__d['client_ip']]}; tier = -1 LIMIT_PATH = '/home/kscREV1/KS/Limit/' if client == 'guest': identifier = '%s_%s'%(__d['client_ip'], sport) tier = 0 elif (client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM): identifier = '%s_%s'%(client, sport) tier = client_info.tier else: identifier = '%s_%s'%(client, sport) tier = 1 edit1 = -9999 if ('%s.pkl'%identifier in os.listdir('%sTier%s_openai/'%(LIMIT_PATH, tier))): with open('%sTier%s_openai/%s.pkl'%(LIMIT_PATH, tier, identifier), 'rb') as f: val1 = cPickle.load(f) edit1 = val1['stamp'] if edit1 < (datetime.utcnow() - timedelta(1)): val1 = {'count': 0}; sdql_mob = __d.setdefault("sdql-mob",sdql) init = __d.setdefault("init",0) cb_init = __d.setdefault("cb_init",0) _qt = __d.setdefault('_qt',"games") show = min(int(__d.setdefault('show',100)), 250) if sport in ['NFL','NCAAFB']: fancy_future = [-2, 'Week'] else: fancy_future = [-1, 'Day'] future = min(int(__d.setdefault('future',10)), 50) edit_f = datetime.now() if (val1['count'] > simpleSearch_limits[tier]): cb = 2 edit_f = (val1['stamp']+timedelta(hours = 24)).strftime('%b %d, %Y %H:%M:%S') if sport in ['NFL','NBA'] and cb == 1 and _qt == 'games' and not old_link: from AI.ai_tools import callBot, model, save_dict_to_json max_char = 256 sdql = sdql[:max_char] # ensure max char limit not exceeded __d['name'] = sdql sdql = str(callBot(sdql, sport)) cb = 1 sdql = sdql.replace('~', '+') cost = 2 season = current_season(sport) number_of_free_trends = 10 if client == 'guest': number_of_free_trends=20 if client in ['shess40']: number_of_free_trends=50 if client in ['JMSports','MCABLAY1']: number_of_free_trends=100 if client in ['PCG','MrEast','Cajun','shess','sdqlkid']: number_of_free_trends=500 if client in ['socaldegen','socaldegen2','ctanner9']: number_of_free_trends=1000 if client in ['SDQG',"tpmeyer","csack3","SBB","admin"]: number_of_free_trends=50000 if client in ['jayecpa','Charlies_Hustle','jam','NextManUp2017','StreakCoolers']: number_of_free_trends = 20 if ((client in copy_access) or ((client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM) and subscriber_copy_access[client_info.tier])): allow_copy = 1 if client not in beta_testers and not KS2.ks.SUBSCRIBE_SYSTEM: allow_copy = 1 trend_dir = os.path.join(TREND_TOP,sport.upper(),'Trend').replace('kscREV1','jameyer') #temporary patch n_trends = 0 client_trends = [] for file in glob.glob(os.path.join(trend_dir,"%s_%s.trend"%(client,"*"))): for line in map(string.strip,open(file).readlines()): if len(line) and line[0] not in '@#': n_trends += 1 client_trends.append(line) credit_redirect = 0 fund_modal = "" save_action = "saving-trend" if client == 'guest': save_action = " href='plans'" elif ((client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM) and (client_info.tier < 4) and (save_slots[client_info.tier] <= n_trends)): save_action = " onclick='noFunds()'" fund_modal = """ <div class="modal-fund"> %s </div>"""%(fund) elif ((client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM) and (client_info.tier == 4) and (5000 <= n_trends)): save_action = " onclick='noFunds()'" fund_modal = """ <div class="modal-fund"> %s </div>"""%(fund) elif (client not in beta_testers and not KS2.ks.SUBSCRIBE_SYSTEM and client_info.balance < 2 and number_of_free_trends <= n_trends): save_action = " onclick='noFunds()'" fund_modal = """ <div class="modal-fund"> %s </div>"""%(fund) else: save_action = " href='saving-trend?sdql=%s&period=%s&filter=%s'"%(urllib.quote(sdql), __d.get("period", "FG"), sport) sdql_name = __d.setdefault("name", '') sdql_name_disp = 'none' SU = '{0:"W",1:"L",2:"P",3:" "}[(runs<o:runs)+2*(runs==o:runs)+(runs is None)] as "SUr"' ATS = '{0:"W",1:"L",2:"P"}[(runs+run line runs<o:runs)+2*(runs+run line runs==o:runs)] as "RLr"' OU = '{0:"O",1:"U",2:"P"}[(o:runs+runs<total+0)+2*(total==runs+o:runs)] as "OUr"' if sport == 'NFL': control = { "Day": 'day[0:3] as "Day"', "Week": 'week as "Week"', "Opp": 'o:team as "Opp"', "Final": 'str(int(points))+"-"+str(int(o:points)) as "Final"', "ot": 'overtime as "ot"', 'SUr': SU, 'ATSr': ATS, 'OUr': OU } def_f = """date,%s,%s,season,team,%s,site,%s,line,total,dps,dpa,%s,%s,%s,%s"""%( control["Day"],control["Week"],control["Opp"],control["Final"],SU, ATS, OU,control["ot"]) elif sport in ['NBA', 'NCAABB', 'WNBA']: control = { "Day": 'day[0:3] as "Day"', "Opp": 'o:team as "Opp"', "Final": 'str(int(points))+"-"+str(int(o:points)) as "Final"', "Rest": 'str(int(rest))+"&"+str(int(o:rest)) as "Rest"', "ot": 'overtime as "ot"', 'SUr': SU, 'ATSr': ATS, 'OUr': OU } def_f = """date,%s,season,team,%s,site,%s,%s,line,total,dps,dpa,%s,%s,%s,%s"""%( control["Day"],control["Opp"],control["Final"],control["Rest"],SU, ATS, OU,control["ot"]) elif sport == 'MLB': SU = '{0:"W",1:"L",2:"P",3:" "}[(runs<o:runs)+2*(runs==o:runs)+(runs is None)] as "SUr"' ATS = '{0:"W",1:"L",2:"P"}[(runs+run line runs<o:runs)+2*(runs+run line runs==o:runs)] as "RLr"' OU = '{0:"O",1:"U",2:"P"}[(o:runs+runs<total+0)+2*(total==runs+o:runs)] as "OUr"' control = { "Day": 'day[0:3] as "Day"', "Opp": 'o:team as "Opp"', "o:Starter": 'o:starter as "o:Starter"', "Final": 'str(int(runs))+"-"+str(int(o:runs)) as "Final"', "Hits": 'str(int(hits))+"-"+str(int(o:hits)) as "Hits"', "Errors": 'str(int(errors))+"-"+str(int(o:errors)) as "Errors"', "BL": 'str(int(biggest lead))+"-"+str(int(o:biggest lead)) as "BL"', "Innings": 'len(inning runs) as "Innings"', 'SUr': SU, 'OUr': OU } def_f = """date,%s,season,site,team,starter,%s,%s,%s,margin,%s,ou margin,%s,%s,%s,%s,line,total,%s"""%( control["Day"],control["Opp"],control["o:Starter"],control["Final"], SU, OU, control['Hits'], control['Errors'], control['BL'], control["Innings"]) elif sport == 'NCAAFB': control = { "Day": 'day[0:3] as "Day"', "Week": 'week as "Week"', "Opp": 'o:team as "Opp"', "Final": 'str(int(points))+"-"+str(int(o:points)) as "Final"', "ot": 'overtime as "ot"', 'SUr': SU, 'ATSr': ATS, 'OUr': OU } def_f = """date,%s,%s,season,team,%s,site,%s,line,total,dps,dpa,%s,%s,%s,%s"""%( control["Day"],control["Week"],control["Opp"],control["Final"],SU, ATS, OU,control["ot"]) elif sport == 'NHL': SU = '{0:"W",1:"L",2:"P",3:" "}[(goals<o:goals)+2*(goals==o:goals)+(goals is None)] as "SUr"' ATS = '{0:"W",1:"L",2:"P"}[(goals+puck line<o:goals)+2*(goals+puck line==o:goals)] as "ATSr"' OU = '{0:"O",1:"U",2:"P"}[(o:goals+goals<total+0)+2*(total==goals+o:goals)] as "OUr"' control = { "Day": 'day[0:3] as "Day"', "Opp": 'o:team as "Opp"', "Final": 'str(int(goals))+"-"+str(int(o:goals)) as "Final"', "Rest": 'str(int(rest))+"&"+str(int(o:rest)) as "Rest"', "ot": 'overtime as "ot"', 'SUr': SU, 'OUr': OU } def_f = """date,%s,season,team,%s,site,%s,%s,line,total,dps,dpa,%s,%s,%s"""%( control["Day"],control["Opp"],control["Final"],control["Rest"],SU, OU,control["ot"]) elif sport in ['ATP', 'WTA']: SU = '{0:"W",1:"L",2:"P",3:" "}[(sets<o:sets)+2*(sets==o:sets)+(sets is None)] as "SUr"' control = { "Day": 'day[0:3] as "Day"', "Opp": 'o:team as "Opp"', "Final": 'str(int(sets))+"-"+str(int(o:sets)) as "Final"', "Rest": 'str(int(rest))+"&"+str(int(o:rest)) as "Rest"', 'SUr': SU, } def_f = """date,%s,atp,team,%s,%s,%s,line,%s"""%( control["Day"],control["Opp"],control["Final"],control["Rest"],SU) fields = __d.get("fields", 0) if tsc: if sport not in ['MLB','NHL']: fields = 'date%2Cteam%2Co%3Ateam%20as%20%22Opp%22%2Csite%2Cstr%28int%28points%29%29%2B%22-%22%2Bstr%28int%28o%3Apoints%29%29%20as%20%22Final%22%2Cline%2Ctotal%2C%7B0%3A%22W%22%2C1%3A%22L%22%2C2%3A%22P%22%2C3%3A%22%20%22%7D%5B%28points%3Co%3Apoints%29%2B2%2A%28points%3D%3Do%3Apoints%29%2B%28points%20is%20None%29%5D%20as%20%22SUr%22%2C%7B0%3A%22W%22%2C1%3A%22L%22%2C2%3A%22P%22%7D%5B%28points%2Bline%3Co%3Apoints%29%2B2%2A%28points%2Bline%3D%3Do%3Apoints%29%5D%20as%20%22ATSr%22%2C%7B0%3A%22O%22%2C1%3A%22U%22%2C2%3A%22P%22%7D%5B%28o%3Apoints%2Bpoints%3Ctotal%2B0%29%2B2%2A%28total%3D%3Dpoints%2Bo%3Apoints%29%5D%20as%20%22OUr%22' elif sport in ['MLB']: fields = 'date%2Csite%2Cteam%2Co%3Ateam%20as%20%22Opp%22%2Cstr%28int%28runs%29%29%2B%22-%22%2Bstr%28int%28o%3Aruns%29%29%20as%20%22Final%22%2Cmargin%2C%7B0%3A%22W%22%2C1%3A%22L%22%2C2%3A%22P%22%2C3%3A%22%20%22%7D%5B%28runs%3Co%3Aruns%29%2B2%2A%28runs%3D%3Do%3Aruns%29%2B%28runs%20is%20None%29%5D%20as%20%22SUr%22%2Cou%20margin%2C%7B0%3A%22O%22%2C1%3A%22U%22%2C2%3A%22P%22%7D%5B%28o%3Aruns%2Bruns%3Ctotal%2B0%29%2B2%2A%28total%3D%3Druns%2Bo%3Aruns%29%5D%20as%20%22OUr%22%2Cline%2Ctotal' elif sport in ['NHL']: fields = 'date%2Cteam%2Co%3Ateam%20as%20%22Opp%22%2Csite%2Cstr%28int%28goals%29%29%2B%22-%22%2Bstr%28int%28o%3Agoals%29%29%20as%20%22Final%22%2Cline%2Ctotal%2C%7B0%3A%22W%22%2C1%3A%22L%22%2C2%3A%22P%22%2C3%3A%22%20%22%7D%5B%28goals%3Co%3Agoals%29%2B2%2A%28goals%3D%3Do%3Agoals%29%2B%28goals%20is%20None%29%5D%20as%20%22SUr%22%2C%7B0%3A%22O%22%2C1%3A%22U%22%2C2%3A%22P%22%7D%5B%28o%3Agoals%2Bgoals%3Ctotal%2B0%29%2B2%2A%28total%3D%3Dgoals%2Bo%3Agoals%29%5D%20as%20%22OUr%22' period = __d.get("period", "FG") if sport in ['ATP', 'WTA']: tbldr = '<i>Coming Soon</i>' else: tbldr = build_page("/home/kscREV1/KS/Tpy/widget-tbldr.tpy",__d) sc_header_dir = { 'MLB': ['Day','Opp','o:Starter','Final','SUr','OUr','Hits','Errors','BL','Innings'], 'NFL': ['Day','Opp','Final','SUr','ATSr','OUr','ot'], 'NCAAFB': ['Day','Opp','Final','SUr','ATSr','OUr','ot'], 'NBA': ['Day','Opp','Final','Rest','SUr','ATSr','OUr','ot'], 'NCAABB': ['Day','Opp','Final','Rest','SUr','ATSr','OUr','ot'], 'NHL': ['Day','Opp','Final','Rest','SUr','OUr','ot'], 'WNBA': ['Day','Opp','Final','Rest','SUr','ATSr','OUr','ot'], 'ATP': ['Day','Opp','Final','Rest','SUr'], 'WTA': ['Day','Opp','Final','Rest','SUr'] } port = ports[sport] if '%s.pkl'%sport in os.listdir('/home/kscAPI/KS/Source/api_status/'): with open('/home/kscAPI/KS/Source/api_status/%s.pkl'%sport, 'rb') as f: port_list = cPickle.load(f) # if ((len(port_list) > 0) and (sport=='NFL')): # port = port_list[-1] # elif ((len(port_list) > 0) and (sport=='NHL')): # port = port_list[-1] if len(port_list) > 0: port = port_list[0] val = {'count': 0, 'ip': [__d['client_ip']]}; tier = -1 LIMIT_PATH = '/home/kscREV1/KS/Limit/' if client == 'guest': identifier = '%s_%s'%(__d['client_ip'], sport) tier = 0 elif client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM: identifier = '%s_%s'%(client, sport) tier = client_info.tier else: identifier = '%s_%s'%(client, sport) tier = 1 edit = -9999 if ('%s.pkl'%identifier in os.listdir('%sTier%s/'%(LIMIT_PATH, tier))): with open('%sTier%s/%s.pkl'%(LIMIT_PATH, tier, identifier), 'rb') as f: val = cPickle.load(f) edit = val['stamp'] if edit < (datetime.utcnow() - timedelta(1)): val = {'count': 0}; quota = 'Unlimited' record = "" limit_modal = "" e_code = 0 if ((val['count'] >= query_limits[0] and tier == 0) or (val['count'] >= query_limits[1] and tier == 1 and (client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM)) or (val['count'] >= query_limits[2] and tier == 2 and (client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM))): quota = 0 options = []; N = 1 field_list = "" limit_modal = """ <div class="modal-limit"> %s </div>"""%(limit) res = """ <h1 style="padding-top: 100px; text-align: center; color: #e17676">Query Limit Exceeded</h1> <h3 class="help-title-color" style="padding-top: 10px; text-align: center"><a href="/">Click here to return to the homepage</a></h3>""" # elif client == 'guest' and not __d.get('token',None): # quota = 0 # options = []; N = 1 # field_list = "" # res = """ <h1 style="padding-top: 100px; text-align: center; color: #e17676">Access Denied</h1> # <h3 class="help-title-color" style="padding-top: 10px; text-align: center"><a href="/">Click here to return to the homepage</a></h3>""" elif sport in ['NFL','NBA','MLB','NCAAFB','NCAABB','NHL','WNBA','ATP','WTA']: # fields = 'date,team,o:team,points,site,margin,Donovan Mitchell:assists as "puntsA",steals,blocks,score after the first as "S1",ou margin,p:blocks,p:steals,assists,pp:blocks,dps,dpa,fouls,Darius Garland:points' # try: # dt, options, show_headers = query(sdql=sdql, default_fields=fields+supplement_fields, _qt=_qt, output='dt') try: # Y = re.findall('0.0.0.0:(%s)'%'|'.join([str(x) for x in ports[sport]]),P) #check ports # A = [] # if len(Y) > 0: # A = [int(y) for y in Y] # if port in A: if client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM: resp = requests.get('http://127.0.0.1:%s/%s?sdql=%s&_qt=%s&show=%s&future=%s&fields=%s&period=%s&tier=%s'%(port, sport.upper(), urllib.quote(sdql), _qt, show, future, fields, period, tier), verify=False, timeout=55).json() else: resp = requests.get('http://127.0.0.1:%s/%s?sdql=%s&_qt=%s&show=%s&future=%s&fields=%s&period=%s&tier=%s'%(port, sport.upper(), urllib.quote(sdql), _qt, show, future, fields, period, 4), verify=False, timeout=55).json() options = resp['options'] show_headers = resp['show_headers'] show_headers = [str(x) for x in show_headers] fields = str(resp['fields']) dt = None N = resp['N'] e_code = resp['err_code'] if ('name' in resp) and (not sdql_name): sdql_name = resp['name'] # sdql_name = urllib.quote(resp['name']) except requests.exceptions.ConnectionError: e_code = 9999 N = 1 options = [] field_list = "" except requests.exceptions.ReadTimeout: e_code = 9997 N = 1 options = [] field_list = "" if e_code == 9999: res = """ <h1 style="padding-top: 100px; text-align: center; color: #e17676">Server Offline</h1> <h3 class="help-title-color" style="padding-top: 10px; text-align: center">We apologize for the incovenience and are working to restore function</h3>""" elif e_code == -9999: N = 1 options = [] field_list = "" res = """ <h1 class="color-yellow" style="padding-top: 100px; text-align: center">Insufficient Subscriber Access</h1> <h3 class="help-title-color" style="padding-top: 10px; text-align: center">This entry qualifies as a <a href='about-custom-tables' class='color-yellow' target='_blank'>custom query</a> and is a feature that requires a Premium subscription to process.<br>Please click <a href='plans-premium' class='color-yellow' target='_blank'>here</a> to upgrade</h3>""" elif e_code in [9997, 9998]: # -- logging -- # field_list = "" if ('timeout_%s.pkl'%sport not in os.listdir('/home/kscREV1/KS/Log/')): timeout = [[client, __d['client_ip'], sdql, _qt, datetime.utcnow()]] with open('/home/kscREV1/KS/Log/timeout_%s.pkl'%sport, 'wb') as f: cPickle.dump(timeout, f) else: with open('/home/kscREV1/KS/Log/timeout_%s.pkl'%sport, 'rb') as f: timeout = cPickle.load(f) with open('/home/kscREV1/KS/Log/timeout_%s.pkl'%sport, 'wb') as f: timeout += [[client, __d['client_ip'], sdql, _qt, datetime.utcnow()]] cPickle.dump(timeout, f) # -- logging -- # if e_code == 9998: res = """ <h1 style="padding-top: 100px; text-align: center; color: #e17676">Query Timeout</h1>""" else: res = """ <h1 class="color-yellow" style="padding-top: 100px; text-align: center">Query Timeout</h1>""" res += """ <h3 class="help-title-color" style="padding-top: 10px; text-align: center">Too many results have been identified, resulting in a system timeout. </h3> <h3 class="help-title-color" style="padding-top: 10px; text-align: center"> You are welcome to request help at the <a href='https://discord.com/invite/Y5ShG3Rckv' class='color-yellow' target='_blank'>Discord group</a> with a thorough, concise explanation of what you are trying to do.</h3>""" elif e_code > 0: if e_code == 2: res = """ <h1 class="color-yellow" style="padding-top: 100px; text-align: center">Player Query Attempt</h1> <h3 class="help-title-color" style="padding-top: 10px; text-align: center">Please switch to a player view and retry</h3>""" else: res = """ <h1 class="color-yellow" style="padding-top: 100px; text-align: center">No Results Found</h1> <h3 class="help-title-color" style="padding-top: 10px; text-align: center"> Either your query has no matching results or we're having trouble interpreting your SDQL.</h3> <h3 class="help-title-color" style="padding-top: 10px; text-align: center"> You are welcome to post it at the <a href='https://discord.com/invite/Y5ShG3Rckv' class='color-yellow' target='_blank'>Discord group</a> with a thorough, concise explanation of what you are trying to do.</h3>""" record = "" owners = ['Schedule','Box','SDB'] i_fields = re.split("\\,(?![^\\{]*\\})", fields) sc_headers = sc_header_dir[sport] nice_headers = S22.common_methods.clean_parameters(show_headers, owners).split(', ') nice_headers += sc_headers #standard_fields field_list = '<ul id="custom">' for x in i_fields: if ((x not in nice_headers) and (x.split(' as ')[-1].strip('"').strip("'")) not in nice_headers): field_list += '<li onclick="addStandard(event)" style="background-color:#3A475B">%s<span style="float:right" disabled><img src="KS/Images/trend/lock-icon.svg" alt="#" style="width:10px; padding-top: 7px"></span></li>'%x.replace('<','&lt;').replace('>','&gt;') for n in nice_headers: if n in ['date', 'team']: field_list += '<li style="background-color:#3A475B">%s<span style="float:right" disabled><img src="KS/Images/trend/lock-icon.svg" alt="#" style="width:10px; padding-top: 7px"></span></li>'%n elif (n in resp['headers'] and n in sc_headers): field_list += '<li onclick="addStandard(event, '+"'"+urllib.quote(control[n])+"'"+')" style="background-color:#3A475B">%s<span style="float:right">&#x2713;</span></li>'%(n) elif n in resp['headers']: field_list += '<li onclick="addStandard(event)" style="background-color:#3A475B">%s<span style="float:right">&#x2713;</span></li>'%n elif (n in sc_headers): field_list += '<li onclick="addStandard(event, '+"'"+urllib.quote(control[n])+"'"+')">%s<span style="float:right">+</span></li>'%(n) else: field_list += '<li onclick="addStandard(event)">%s<span style="float:right">+</span></li>'%n field_list += '</ul>' elif e_code == -1: res = """ <h1 class="error-h1-minor%s">We're having trouble interpreting your SDQL</h1> <h3 class="help-title-color%s" style="padding-top: 10px; text-align: center"> You are welcome to post it at the <a href='https://discord.com/invite/Y5ShG3Rckv' class='color-yellow' target='_blank'>Discord group</a> with a thorough, concise explanation of what you are trying to do.</h3>"""%(theme, theme) record = "" owners = ['Schedule','Box','SDB'] i_fields = re.split("\\,(?![^\\{]*\\})", fields) sc_headers = sc_header_dir[sport] nice_headers = S22.common_methods.clean_parameters(show_headers, owners).split(', ') nice_headers += sc_headers #standard_fields field_list = '<ul id="custom">' for x in i_fields: if ((x not in nice_headers) and (x.split(' as ')[-1].strip('"').strip("'")) not in nice_headers): field_list += '<li onclick="addStandard(event)" style="background-color:#3A475B">%s<span style="float:right" disabled><img src="KS/Images/trend/lock-icon.svg" alt="#" style="width:10px; padding-top: 7px"></span></li>'%x.replace('<','&lt;').replace('>','&gt;') for n in nice_headers: if n in ['date', 'team']: field_list += '<li style="background-color:#3A475B">%s<span style="float:right" disabled><img src="KS/Images/trend/lock-icon.svg" alt="#" style="width:10px; padding-top: 7px"></span></li>'%n elif (n in resp['headers'] and n in sc_headers): field_list += '<li onclick="addStandard(event, '+"'"+urllib.quote(control[n])+"'"+')" style="background-color:#3A475B">%s<span style="float:right">&#x2713;</span></li>'%(n) elif n in resp['headers']: field_list += '<li onclick="addStandard(event)" style="background-color:#3A475B">%s<span style="float:right">&#x2713;</span></li>'%n elif (n in sc_headers): field_list += '<li onclick="addStandard(event, '+"'"+urllib.quote(control[n])+"'"+')">%s<span style="float:right">+</span></li>'%(n) else: field_list += '<li onclick="addStandard(event)">%s<span style="float:right">+</span></li>'%n field_list += '</ul>' if ('dsyntax_%s.pkl'%sport not in os.listdir('/home/kscREV1/KS/Log/')): syn = [[client, __d['client_ip'], sdql, _qt, datetime.utcnow()]] with open('/home/kscREV1/KS/Log/dsyntax_%s.pkl'%sport, 'wb') as f: cPickle.dump(syn, f) else: with open('/home/kscREV1/KS/Log/dsyntax_%s.pkl'%sport, 'rb') as f: syn = cPickle.load(f) with open('/home/kscREV1/KS/Log/dsyntax_%s.pkl'%sport, 'wb') as f: syn += [[client, __d['client_ip'], sdql, _qt, datetime.utcnow()]] cPickle.dump(syn, f) elif N == 1: # i_fields = re.split("\\,(?![^\\{]*\\})", fields) # cut = len(i_fields) # res = main(dt, show, cut) res = resp['res'] i_fields = re.split("\\,(?![^\\{]*\\})", fields) jqa = '' parameter_text = "" # options = list(dt.player_dts) record = resp['record'] sc_headers = sc_header_dir[sport] # !!!! owners = ['Schedule','Box','SDB'] nice_headers = S22.common_methods.clean_parameters(show_headers, owners).split(', ') nice_headers += sc_headers #standard_fields field_list = '<ul id="custom">' for x in i_fields: if ((x not in nice_headers) and (x.split(' as ')[-1].strip('"').strip("'")) not in nice_headers): field_list += '<li onclick="addStandard(event)" style="background-color:#3A475B">%s<span style="float:right">&#x2713;</span></li>'%x.replace('<','&lt;').replace('>','&gt;') for n in nice_headers: if n in ['date', 'team']: field_list += '<li style="background-color:#3A475B">%s<span style="float:right" disabled><img src="KS/Images/trend/lock-icon.svg" alt="#" style="width:10px; padding-top: 7px"></span></li>'%n elif (n in resp['headers'] and n in sc_headers): field_list += '<li onclick="addStandard(event, '+"'"+urllib.quote(control[n])+"'"+')" style="background-color:#3A475B">%s<span style="float:right">&#x2713;</span></li>'%(n) elif n in resp['headers']: field_list += '<li onclick="addStandard(event)" style="background-color:#3A475B">%s<span style="float:right">&#x2713;</span></li>'%n elif (n in sc_headers): field_list += '<li onclick="addStandard(event, '+"'"+urllib.quote(control[n])+"'"+')">%s<span style="float:right">+</span></li>'%(n) else: field_list += '<li onclick="addStandard(event)">%s<span style="float:right">+</span></li>'%n field_list += '</ul>' else: res = resp['res'] record = resp['record'] field_list = "" general_log(e_code, sport) fields = urllib.quote(fields) # except: # dt = "YOYOYOYO"; options = ""; show_header = "" else: record = "" if sdql_name != '': sdql_name_disp = 'block' sdql_name = str(sdql_name).replace('<','&lt;').replace('>','&gt;') if e_code == 0: if (('%s.pkl'%identifier not in os.listdir('%sTier%s/'%(LIMIT_PATH, tier))) or (edit < (datetime.utcnow() - timedelta(1)))) and getpost: # val = {'count': 1, 'stamp': datetime.utcnow(), 'ip': [__d['client_ip']]} val = {'count': 1, 'stamp': midnight_et_utc_naive, 'ip': [__d['client_ip']]} with open('%sTier%s/%s.pkl'%(LIMIT_PATH, tier, identifier), 'wb') as f: cPickle.dump(val, f) elif getpost: if limit_modal == "": with open('%sTier%s/%s.pkl'%(LIMIT_PATH, tier, identifier), 'rb') as f: val = cPickle.load(f) with open('%sTier%s/%s.pkl'%(LIMIT_PATH, tier, identifier), 'wb') as f: val['count'] += 1 if __d['client_ip'] not in val['ip']: val['ip'] += [__d['client_ip']] cPickle.dump(val, f) if tier == 0: quota = max(0, query_limits[0] - val['count']) elif ((client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM) and (tier == 1)): quota = max(0, query_limits[1] - val['count']) elif ((client in beta_testers or KS2.ks.SUBSCRIBE_SYSTEM) and (tier == 2)): quota = max(0, query_limits[2] - val['count']) if init != 0 and cb == 1: if (('%s.pkl'%identifier not in os.listdir('%sTier%s_openai/'%(LIMIT_PATH, tier))) or (edit1 < (datetime.utcnow() - timedelta(1)))): # val1 = {'count': 1, 'stamp': datetime.utcnow(), 'ip': [__d['client_ip']]} val1 = {'count': 1, 'stamp': midnight_et_utc_naive, 'ip': [__d['client_ip']]} with open('%sTier%s_openai/%s.pkl'%(LIMIT_PATH, tier, identifier), 'wb') as f: cPickle.dump(val1, f) else: if limit_modal == "": with open('%sTier%s_openai/%s.pkl'%(LIMIT_PATH, tier, identifier), 'rb') as f: val1 = cPickle.load(f) with open('%sTier%s_openai/%s.pkl'%(LIMIT_PATH, tier, identifier), 'wb') as f: val1['count'] += 1 if __d['client_ip'] not in val1['ip']: val1['ip'] += [__d['client_ip']] cPickle.dump(val1, f) # record = """ # <div class="investment-record-card w-card item-center" onmouseover="document.getElementById('drop-control').style.opacity = 1" onmouseleave="document.getElementById('drop-control').style.opacity = 0; document.getElementById('record-content').style.height = 0" onclick="document.getElementById('record-content').style.height = document.getElementById('record-content').scrollHeight" style="cursor:pointer"> # <div class="col-12 flex-between"> # <p style="color: rgb(243 213 39);font-size: 22px;font-weight: 600;">Output Controls</p> # <p id="drop-control" class="record-control">+</p> # </div> # <div id="record-content" class="record-content investment-card-content"> # <select> # <option>A</option> # <option>B</option> # <option>C</option> # <option>D</option> # <option>E</option> # </select> # <select id="second" data-placeholder="Choose a field..." class="chosen-select" tabindex="4" style="width:200px" onchange="updateOptions(this.selectedIndex-1, this.value)"><option value=""></option> # <option value='team'>team</option> # <option value='season'>season</option> # <option value='site'>site</option> # <option value='division'>division</option> # <option value='conference'>conference</option> # <option value='points'>points</option> # <option value='ats margin'>ats margin</option> # <option value='ats streak'>ats streak</option> # <option value='attendance'>attendance</option> # <option value='average punt yards'>average punt yards</option> # <option value='biggest lead'>biggest lead</option> # <option value='blocked field goals'>blocked field goals</option> # <option value='blocked punts'>blocked punts</option> # <option value='coach'>coach</option> # <option value='completions'>completions</option> # <option value='date'>date</option> # <option value='day'>day</option> # <option value='defensive touchdowns'>defensive touchdowns</option> # <option value='dpa'>dpa</option> # <option value='dps'>dps</option> # <option value='drives'>drives</option> # </select> # <input placeholder="test it out></input> # </div> # </div> # """ # try: # res, jqa = query(sdql=sdql,output='html',_qt=_qt,short_cuts=['KS'],sport=sport,show_metacode=0) # # res = ''; jqa ='' # except Exception: # res = traceback.format_exc() # jqa = '' # res = res.replace('src="/Images/ks_banner_yellow.jpg"', 'id="watermark" src="KS/Images/logo/logo.svg"') # parameter_text = "" # parameters = re.findall('y>(.*?) Parameters:</a> (.*?)<', res) # parameter_text += """<p class="border-bottom pb-16">%s</p>"""%parameters[0][1] # for i in range(1, len(parameters)): # parameter_text += """<p class="pt-16 pb-16 color-yellow">%s Parameters</p>"""%parameters[i][0] # parameter_text += """<p class="pb-16">%s</p>"""%parameters[i][1] # res = res.replace(re.findall('(<HR>.*?)<HR>', res)[0],'') # res = res.replace('&output=summary','&output=summary&filter=%s'%sport) # options = re.findall("<option value='(.*?)'>(.*?)</option>", res) flash_url = "" if (tweet == 1 and client != 'guest'): url = 'https://%s/query?sdql=%s&filter=%s&_qt=%s&theme=%sinit=1&tsc=1'%(__d['host'], sdql, sport, _qt, theme.strip('-')) screenshot = screenshot_link(url, client) flash_url = 'https://twitter.com/intent/tweet?text='+sdql+'&url='+screenshot qt_dropdown = """ <div class="dropdown"> <button onclick="myFunction(0)" class="dropdown-btn%s dropdown-toggle query-dropdown" data-toggle="dropdown" id="qt-sel">Game <span class="caret"></span></button> <div id="myDropdown_0" class="dropdown-content"> <div class="option-bord" onclick="setQT(event)" style="cursor:pointer"> <a class="drop-option" name="games">Game</a> </div> """%theme options.sort() for i in options: qt_dropdown += '<div class="option-bord" onclick="setQT(event)" style="cursor:pointer"><a class="drop-option%s" name="%s">%s</a></div>'%(theme, i, i.title()) qt_dropdown += "</div></div>" sw_dropdown = """ <div class="dropdown"> <button onclick="myFunction(1)" class="dropdown-btn%s dropdown-toggle query-dropdown" data-toggle="dropdown" id="sw-sel">100 <span class="caret"></span></button> <div id="myDropdown_1" class="dropdown-content"> <div class="option-bord" onclick="setShow(event)" style="cursor:pointer" name="10"><a class="drop-option">10</a></div> <div class="option-bord" onclick="setShow(event)" style="cursor:pointer" name="50"><a class="drop-option">50</a></div> <div class="option-bord" onclick="setShow(event)" style="cursor:pointer" name="100"><a class="drop-option">100</a></div> <div class="option-bord" onclick="setShow(event)" style="cursor:pointer" name="250"><a class="drop-option">250</a></div> </div> </div> """%(theme) su_dropdown = """ <div class="dropdown"> <button onclick="myFunction(2)" class="dropdown-btn%s dropdown-toggle query-dropdown" data-toggle="dropdown" id="su-sel">10 <span class="caret"></span></button> <div id="myDropdown_2" class="dropdown-content"> <div class="option-bord" onclick="setFuture(event)" style="cursor:pointer" name="10"><a class="drop-option">10</a></div> <div class="option-bord" onclick="setFuture(event)" style="cursor:pointer" name="20"><a class="drop-option">20</a></div> <div class="option-bord" onclick="setFuture(event)" style="cursor:pointer" name="50"><a class="drop-option">50</a></div> <div class="option-bord" onclick="setFuture(event)" style="cursor:pointer" name="%s"><a class="drop-option">%s</a></div> </div> </div> """%(theme, fancy_future[0], fancy_future[1]) nonspec = 0 view_controls = """<div class="flex align-items-center"><div class="panel-title%s query-dropdown">Query Type -</div>%s</div> """%(theme, qt_dropdown) main_controls = "" if N == 1: nonspec = 1 view_controls = """ <div class="flex align-items-center"> <div class="panel-title%s query-dropdown">Query Type -</div> %s <div class="panel-title%s query-dropdown">Show Last -</div> %s <div class="panel-title%s query-dropdown">Show Upcoming -</div> %s </div> """%(theme, qt_dropdown, theme, sw_dropdown, theme, su_dropdown) main_controls = """ <div onclick="openModal('modal5');isoModal('modal5')" class="flex align-items-center pointer"> <img class="pr-11" src="KS/Images/trend/custom-icon.svg" alt="#" style="width:26px"> <p class="chat-content help-title-color%s">Customize Fields <p> </div> <div onclick="resetFields()" class="flex align-items-center pointer"> <img class="pr-11" src="KS/Images/trend/help-reset.svg" alt="#" style="width:26px"> <p class="chat-content help-title-color%s">Reset Fields <p> </div> <!--<div onclick="openModal('modal3');isoModal('modal4')" class="flex align-items-center pointer"> <img class="pr-11" src="KS/Images/trend/help-icon.svg" alt="#"> <p class="chat-content help-title-color%s">Plot Results</p> </div>--> """%(theme, theme, theme) combinations = "t, o, p, P, n, N, s, S (for team, opponent, previous game, previous matchup, next game, next matchup, starter's last start, and starter's last matchup respectively)" examples = [ ['query?sdql=100%20%3C%20t%3Arushing%20yards%20and%20to%3Arushing%20yards%20%3C%20100', 'tA(rushing yards) &lt; 50', 'how teams do when rushing for more than 100 yards while holding their opponent to few than 100 yards'], ['query?sdql=100%20%3C%20t%3Arushing%20yards%20and%20to%3Arushing%20yards%20%3C%20100', 'tA(rushing yards) &lt; 50', 'how teams do after scoring more than 40 points their last four games'], ['query?sdql=400%20%3C%20top%3Apassing%20yards%20and%20top%3Apoints%20%3C%20topo%3Apoints', 'tA(rushing yards) &lt; 50', 'how teams do after their opponent passed for more than 400 yards and lost'], ['query?sdql=400%20%3C%20top%3Apassing%20yards%20and%20top%3Apoints%20%3C%20topo%3Apoints', 'tA(rushing yards) &lt; 50', 'how teams do when they have a season-to-date average of less that 50 rushing yards']] qf_sdql = [ ['50 &lt; Kobe Bryant : points', 'site = away'], ['120 &lt; Bulls : points', 'site = home'], ['points &lt; 60'], ['points &lt; 90,100,110'], ['70,80,90,100 &lt; points &lt; 90,100,110'] ] qf_expl = [ 'returns home games where Kobe Bryant scored more than 50 points on the road', 'returns games in which the Bulls scored more than 120 points at home', 'returns games when the team scored fewer than 60 points', 'gives results grouped by points &lt; 90, points &lt; 100, and points &lt; 110', '' ] gm_refs = { 'p': "team's previous game", 'op':"opponent's previous game", 'P': "previous match up", 'n': "team's next game", 'on':"opponent's next game", 'N': "next match up", 's': "starter's previous start", 'S': "starter's previous match up start"} gm_ref_html = "" for gm_ref in gm_refs: gm_ref_html += """ <div class="flex align-items-center gap-32 pb-16"> <div class="align-items-center small-card"> <p>%s :</p> </div> <p class="">%s</p> </div>"""%(gm_ref, gm_refs[gm_ref]) gm_ref_sdql = [ ['100 &lt; t:rushing yards', 'to:rushing yards &lt; 100'], ['40 &lt; p:points', '40 &lt; p2:points', '40 &lt; p3:points', '40 &lt; p4:points'], ['2*P:points in the paint &lt; Po:points in the paint', 'P:season = season'], ['0.25*p:points&lt;=p:fast break points','po:points']] gm_ref_expl = [ 'how teams do when rushing for more than 100 yards while holding their opponent to few than 100 yards', 'Use this SDQL to see how teams do after scoring more than 40 points their last four games', 'return games in which the team was outscored in the paint by a factor of 2 in their previous match up', 'return games with a team off a win in which they scored at least 25% of their points from fast breaks'] shortcuts = {'nfl': { 'ATSL':'ats loss','ATSW':'ats win','AWP':'Away Winning Percentage','3DM':'third downs made','3DA':'third downs attempts', '3DF':'third down failures','3DP':'third down conversion percentage','4DM':'fourth downs made','4DA':'fourth downs attempts', '4DF':'fourth down failures','4DP':'fourth down conversion percentage','COMP':'completions','CP':'completion percentage', 'DAY': 'day game (start time<1700)', 'DIV':'divisional game','DTD':'defensive touchdowns','FD':'first downs','FDP':'first down percentage','FG':'number of field goals', 'FGA': 'field goals attempted', 'FUM':'fumbles','FUML':'fumbles lost','GTGA':'goal to go attempted','GTGF':'goal to go failed','GTGM':'goal to go made', 'HWP':'Home Winning Percentage','INC':'incomplete passes','INT':'interceptions','M1':'margin after the first','M2':'margin at the half', 'M3':'margin after the third','NDIV':'non-divisional game', 'NGT': 'night game (start time>=1700)','NOTD':'non-offensive TDs','OFPL':'offensive plays','OT':'overtime', 'P1':'points in the first','P2':'points in the second','P3':'points in the third','P4':'points in the fourth','PEN':'penalties', 'PENY':'penalty yards','PFD':'passing first downs','PENFD':'penalty first downs','PO':'playoffs','PTD':'passing touchdowns', 'PY':'passing yards','RFD':'rushing first downs','RTD':'rushing touchdowns','REG':'regular season','RTD':'rushing touchdowns', 'RY':'rushing yards','RZA':'red zone attempts','RZM':'red zones made','RZF':'red zone failures','S1':'points in the first', 'S2':'total points after the second','S3':'total points after the third','SIQ':'scored in quarters - the team scored in this many quarters', 'SY':'sack yards','TD':'number of touchdowns','TO':'turnovers','TOM':'turnover margin','TOP':'time of possession','TY':'total yards', 'WP':'winning percentage','YPC':'yards per completion','YPPL':'yards per play','YPPT':'yards per point','YPPA':'yards per pass', 'YPPP':'yards per pass play (includes sacks)','YPRA':'yards per rushing attempt', }, 'nba': { 'AASB':'after the all star break','ATSL':'against the spread loss','ATSW':'against the spread win','AST':'assists','ATR':'assist to turnover ratio', 'AWP':'Away Winning Percentage','BAP':'Baskets Assisted percentage','BASB':'before the all star break','BL':'biggest lead','DAY': 'day game (start time<1700)','DDS':'Double Digit Scorers', 'DRB':'Defensive Rebounds','FBP':'fast break points','FGA':'field goals attempted','FGM':'field goals made','FGP':'field goal percentage', 'FTA':'free throws attempted','FTM':'free throws made','FTP':'free throw percentage','HWP':'Home Winning Percentage','LC': 'lead changes', 'LSP':'Leading Scorers Points', 'M1':'margin after the first','M2':'margin at the half','M3':'margin after the third','NGT': 'night game (start time>=1700)','ORB':'Offensive Rebounds','P1':'points in the first', 'OT':'overtime', 'P2':'points in the second','P3':'points in the third','P4':'points in the fourth','PIP':'points in the paint','PM':'plus / minus (player level parameter)', 'PFT':'percentage of points from free throws','PTP':'percentage of points from three pointers','RB':'Rebounds', 'REG':'regular season', 'S1':'points in the first','S2':'total points after the second','S3':'total points after the third','SG':'series game','TO':'turnovers','TOM':'turnover margin','TPA':'three pointers attempted', 'TPM':'three pointers made','TPP':'three point percentage','TT':'Times Tied','WP':'team winning percentage' }, 'mlb': { 'AASB':'After All-Star Break','AWP':'Away Winning Percentage','BASB':'Before All-Star Break','BL':'Biggest Lead','BPRA':'Bull Pen Runs Allowed', 'BS':'Bad Start (4 or fewer innings and 5 or more earned runs)','DAY':'Day (start time<1800)','DDP':'Defensive Double Plays','DIV':'Divisional Game', 'FGS':'First Game of a Series','HR':'Home Runs','HPR':'Hits Per Run','HPU':'Home Plate Umpire','HWP':'Home Winning Percentage','IL':'Innings Led', 'IT':'Innings Tied','LGS':'Last Game of a Series','LOB':'Left on Base','MRI':'Multiple Run Innings','NDIV':'Not a Divisional Game', 'NGT':'Night (start time>=1800)','NQS':'Non Quality Start','ODP':'Offensive Double Plays (hit into double plays)','PBRS':'Percent Base Runners Scored', 'PO':'During the Playoffs','PU':'Pitchers Used','QS':'Quality Start (at least 6 innings and 3 or fewer earned runs)','REG':'During the Regular Season', 'RG3':'Rubber Game 3 (3rd game of a 3 game series and they split the first 2)','RMAX':'The maximum runs the team scored in any one inning', 'SERA':'Starter Earned Run Average in the Referenced Game','SF':'Scored First: How many runs a team scored before their opponent scored', 'SG':'Series Game','SGS':'Series Games','SHA':'Starter Hits Allowed','SHF':'Starter Hitters Faced','SHRA':'Starter Home Runs Allowed', 'SII':'Scored In Innings','SIP':'Starter Innings Pitched','SO':'Strikeouts','SOPW':'Strikeouts Per Walk','SPPH':'Starter Pitch Per Hitter', 'SPB':'Strike Per Ball','SPT':'Starter Pitches Thrown','SRA':'Starter Runs Allowed','SSO':'Starter Strike Outs','SSPB':'Starter Strike Per Ball', 'STDHPR':'Season To Date Hits Per Run','STDSERA':'Starter Season To Date ERA','STDSOPW':'Season To Date Stike Outs Per Walk', 'STDSSOPW':'Starter Season To Date Stike Outs Per Walk','STDSPB':'Season To Date Stikes Per Ball','STDSSPB':'Starter Season To Date Stikes Per Ball', 'STDSWHIP':'Starter Season To Date WHIP','STR':'Starter Throws Right','STL':'Starter Throws Left','SWA':'Starter Walks Allowed', 'SWHIP':'Starter Walks Plus Hits Per Inning Pitched','TLOB':'Team Left On Base','TT':'Times Tied','WOW':'Walk Off Win', 'WP':'Winning Percentage','XBH':'eXtra Base Hits (doubles + triples)' }, 'nhl': { 'AASB':'after the all star break','BASB': 'before the all star break', 'BL':'biggest lead', 'DAY': 'day game (start time<1700)', 'DIV':'divisional game', 'M1': 'margin after the first period', 'M2': 'margin after the second period', 'M3': 'margin after the third period', 'NDIV':'Non-Divisional Game', 'NGT': 'night game (start time>=1700)', 'OT': 'game went to overtime', 'P1': 'goals in the first period', 'P2': 'goals in the second period', 'P3': 'goals in the third period', 'PEN': 'penalties', 'PENM': 'penalty minutes','REG':'regular season', 'S1': 'goals in the first period', 'S2': 'goals in the second period', 'S3': 'goals in the third period', 'SOG': 'shots on goal' }} def cln_fields(headers): cln_headers = [] noshow = ['srslg'] for h in headers: if ((h.replace('Box.','')[0] != '_') and ('Covers.' not in h) and ('Schedule.' not in h) and ('B2.' not in h) and ('_' not in h) and (h not in noshow)): cln_headers += [h.replace('Box.','')] return cln_headers queryable = "" if 'show_headers' in locals(): qfields = {} qfields['games'] = list(set(cln_fields(show_headers))) qfields['games'].sort() # for opt in list(dataset.player_dts): # fields[opt] = cln_fields(dataset.player_dts[opt].headers) for x in list(qfields): queryable += '<label style="color:white">Game Fields</label>' queryable += '<p>' #queryable += '<p>%s</p>'%', '.join(qfields[x]) #List fields in paragraph form for y in list(qfields[x]): queryable += '&#183; %s<br>'%(y) queryable += '</p>' shortcuts['ncaafb'] = shortcuts['nfl'] shortcuts['ncaabb'] = shortcuts['nba'] shortcuts['wnba'] = shortcuts['nba'] shortcuts['nhl'] = shortcuts['nhl'] shortcuts['atp'] = {} shortcuts['wta'] = {} shortcuts_list = [x for x in shortcuts[sport.lower()]] shortcuts_list.sort() scuts = "" for s in shortcuts_list: scuts += '&#183; %s - %s<br>'%(s, shortcuts[sport.lower()][s]) qglow = '' if init == 0: sdql = "" qglow = ' sdql-glow' record = record.replace('radiobtn', 'radiobtn'+theme) record = record.replace('avg-line-total', 'avg-line-total'+theme) res = res.replace('table-striped', 'table-striped'+theme) res = res.replace('future-divide', 'future-divide'+theme) if theme == '-light': res = res.replace('a-dark', '') if sport in ['NFL','NBA'] and _qt == 'games': chat_history = '' if cb == 2: if client == 'guest': chat_history = '<p style="padding: 10px;color: #007bff;font-weight: 600;font-size: 16px;">SimpleSearch usage is limited to %s per day for guests. Your access will reset in <span id="demo" class="limit-countdown"></span></p>'%simpleSearch_limits[tier] else: chat_history = '<p style="padding: 10px;color: #007bff;font-weight: 600;font-size: 16px;">SimpleSearch usage is limited to %s per day for registered users. Your access will reset in <span id="demo" class="limit-countdown"></span></p>'%simpleSearch_limits[tier] elif cb == 1 and not e_code: chat_history += '<div class="message user">%s</div>'%__d['name'] chat_history += '<p style="padding: 10px;color: black;padding-bottom: 18px;">translated to:</p>' chat_history += '<div class="message bot">%s</div>'%sdql.replace('<','&lt;').replace('>','&gt;') chat_history += """ <div class="cb-radio-container tooltip-ksc" style="position: absolute; bottom: 18; right: 0;"> <span class="rating-text">Rate this translation:</span> <input type="radio" id="thumbs-up" name="feedback" value="up" onclick="handleButtonClick('up', '%s', '%s');"> <label for="thumbs-up"><i class="fas fa-thumbs-up"></i></label> <input type="radio" id="thumbs-down" name="feedback" value="down" onclick="handleButtonClick('down', '%s', '%s');"> <label for="thumbs-down"><i class="fas fa-thumbs-down"></i></label> <div id="cb-thanks-message"> Thanks <i class="fas fa-check"></i> </div> </div> <span class="tooltiptext">Did you get the results you were expecting? Provide us with feedback to help better train the search bot.</span> """%(__d['name'], sdql, __d['name'], sdql) elif e_code and e_code not in [1, -9999, 9999] and not old_link and cb==1: save_dict_to_json('/home/kscREV1/KS/AI/%s_log_failure.json'%sport.lower(), model, {'origin': sdql, 'translation': 'Search did not yield a valid query', 'stamp': time.time()}) chat_history = '<p style="padding: 10px;color: #007bff;font-weight: 600;font-size: 16px;">Search did not yield a valid query</p>' sdql = '' sdql_name = '' sdql_name_disp = 'none' else: chat_history = '<p style="padding: 10px;color: #007bff;font-weight: 600;font-size: 16px;">&darr;&nbsp;&nbsp;SimpleSearch is Activated, you may now use plain English in the search bar below.&nbsp;&nbsp;&darr;</p>' qb_color = '' if theme == '-light': qb_color = ' color-black' chatbot = """ <div class="cb-container"> <button title="Toggle on/off to switch from conversational English questions to SDQL queries." class="cb-collapsible"> <span class="cb-qb-line%s"></span> <span class="chatbot%s" id="ss_message">Type plain English - SimpleSearch Mode</span> <span id="cb-status" class="cb-status%s"><span id="on-text" class="status-on">ON</span> / <span id="off-text" class="status-off">OFF</span></span> <span class="cb-qb-line%s"></span> </button> <div class="cb-qb-content" style="transition: max-height 0.6s ease-out;max-height: 0px;display: flex;justify-content: center;align-items: center;"> <div id="chat-window" class="flex align-items-end pb-16" style="position: relative; margin-right:0px;"> %s </div> </div> </div> """%(theme, qb_color, theme, theme, chat_history) else: chatbot = "" cb_help_header = "" if sport in ['NFL','NBA'] and _qt == 'games': cb_help_header = """ <div onclick="openModal('modal8');isoModal('modal8')" class="flex align-items-center pointer"> <img class="pr-11" src="KS/Images/trend/help-icon.svg" alt="#" style="filter:invert(58%) sepia(99%) saturate(394%) hue-rotate(72deg) brightness(130%) contrast(100%);"> <p class="chat-content" style="color:#31e939 !important;">SimpleSearch Tips <p> </div>""" cb_help_content = """ <p class="color-yellow pt-8 pb-8">Tips on Asking Questions:</p> <p>1.) Commas save lives: Lets eat, grandma. Lets eat grandma. Two very different things. Use of commas:</p> <div class="flex align-items-center small-card"> <div class=""> <p class="help-title-color">Houston when not a dog coming off a home game</p> </div> </div><br> This means Houston is neither a dog nor coming off a home game. <br><br> <div class="flex align-items-center small-card"> <div class=""> <p class="help-title-color">Houston when not a dog, coming off a home game</p> </div> </div><br> This means Houston is not a dog and is coming off a home game. <br><br> <p>2.) Be precise, literal, and don't assume.</p> <div class="flex align-items-center small-card"> <div class=""> <p class="help-title-color">How have the Bengals have done after having won 4 of their last 5 games?</p> </div> </div><br> This means how have the Bengals done after having won exactly 4 of their last 5 games. If they won 5 of their last 5 those instances would not appear in your results. If you want know how the Bengals have done after having won AT LEAST 4 of their last 5 games, specify it. <br><br> <p>3.) Try to write proper English in a tangible complete sentence.</p>If you misspell words or don't articulate yourself clearly you're increasing the chances that you won't be understood or get the answer you're looking for. Don't hesitate to ask a question in our Discord Community if you're unsure. <p class="color-yellow pt-8 pb-8">Notes:</p> <p><b>1.)</b> We've tested the language learning model to be over 95% accurate at translating English, especially for simpler inquiries, and with its machine learning algorithms it will only continue to improve. Be aware that SimpleSearch may not understand you or properly translate 100% of the time dependent upon how articulate and concise your question is. Give your search results a Thumbs Up or Thumbs Down to help it learn. If you don't think it gave you the right answer, let it know. Conversely, if it looks correct, also let it know.</p> <br> <p><b>2.)</b> SimpleSearch is not trained on player specific queries, yet.</p> <br> <p><b>3.)</b> SDQL itself currently still provides more versatility for detailed searches like open ended queries, list searches, and custom table queries.</p> <br> <p><b>4.)</b> SimpleSearch is currently available for NFL and NBA and we are actively working to expand its availability to all other sports.</p> """ cb_examples = '<div class="cb-dropdown" id="cb-dropdown">' qry_examples = {'NFL': [ 'Teams after a 21+ point win', 'After a game in which they had at least 20 penalty yards', 'Display all games where the Panthers allowed under 20 points.', 'Find all games where Houston had at least 4 sacks.', 'List all Falcons home games following a victory of 6 or more points', 'List all games played on Septmeber 26, 2021', 'Patriots playing against a team with the same record', 'Rams had fewer than 197 passing yards in their last game which was on the road', 'Show all games in which the Texans had at least 40 rush attempts.', 'When the Browns are two games below .500', 'Show me games where the Cowboys played against a non-division opponent.', 'Teams with a losing streak of at least 4.', 'The Cardinals as a road dog on grass vs a non-divisional opponent', 'When Chiefs had more than 300 passing yards in a game' ], 'NBA': [ 'How do the Knicks do when coming off back to back losses?', 'How do road teams do when they are unrested?', 'After a game with more than 30 assists', 'Teams after having allowed more than 130 points.', 'Find all games where a team is off an upset win.', 'Teams with a losing streak of at least 4.', 'When the Celtics are coming off a home loss.', 'Show all games where the Heat scored more than 130 points.', 'Display all games where a team is unrested and lost yesterday.', 'Losing teams at home?' ], 'MLB': [], 'NHL': [], 'WNBA': [], 'NCAAFB': [], 'NCAABB': [], 'ATP': [], 'WTA': [] } for x in qry_examples[sport]: cb_examples += '<div>%s</div>'%x cb_examples += '</div>' if theme == '-light': help_pane_text = """color: black""" else: help_pane_text = ""
error:
exception:
message: invalid syntax (, line 3)
traceback:


error:
exception:
message:
traceback: