async def update(self, ctx): try: conn = await aiosqlite.connect('data/rotating/surviv.db') c = await conn.cursor() await c.execute('select * from new') res = await c.fetchall() content = res[0][2] current_title = res[0][0] current_date = res[0][1] embed = discord.Embed( title=f'🆕 {current_title} ~ ({current_date}) 🆕 ', description=f'{content}', color=self.color) embed.set_footer( text=f"{self.name} requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) StreamLogger.log( f'{ctx.message.author} ran {self.name} Command successfully.') await conn.close() except Exception as e: try: await conn.close() except: pass WarningLogger.log( f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {traceback.format_exc()}' ) error_embed = discord.Embed( description= f"**{self.name}** command did not run as expected.\nPlease log an issue with `{ctx.prefix}issue`", color=self.color) await ctx.send(embed=error_embed)
async def help(self, ctx): try: disc = f"\n**NOTE**: You can find the arguments a command supports by typing the command with `args` at the end.\n**Example**: `{ctx.prefix}player ARGS`\n" intro = "Surviv Stat Bot Commands!\nThe Game is playable at https://surviv.io/." info_command_desc = f"ℹ️ `{ctx.prefix}info` - Returns some information on the game surviv.io.\n" melee_command_desc = f"🔪 `{ctx.prefix}melee` - Returns stats for a melee weapon in surviv.io.\n" link_command_desc = f"🔗 `{ctx.prefix}link` - Returns a party link for surviv.io that expires in 7 seconds.\n" ping_command_desc = f"🏓 `{ctx.prefix}ping` - Gets the current latency of the bot.\n" gun_command_desc = f"\U0001F52B `{ctx.prefix}gun` - Returns stats for a gun in surviv.io.\n" player_command_desc = f"⛹ `{ctx.prefix}player` - Returns stats for a player in surviv.io.\n" twitch_command_desc = f"🕹️ `{ctx.prefix}twitch` - Returns the top streamers currently streaming surviv.io.\n" update_command_desc = f"🆕 `{ctx.prefix}update` - Returns the current update in surviv.io.\n" website_command_desc = f"🔗`{ctx.prefix}website` - Link to the website.\n" supportserver_command_desc = f"🔗`{ctx.prefix}support` - Link to the support server.\n" surviv_regions_command_desc = f"🌎 `{ctx.prefix}regions` - All of the surviv.io regions.\n" ad_command_desc = f"Your Server Could be here! Join the support server for more info.\n" embed = discord.Embed( title= "<:survivio:787315420074868768> Surviv.io Commands <:survivio:787315420074868768>", description= f"{disc}\n{intro}\n\n{info_command_desc}{melee_command_desc}{ping_command_desc}{gun_command_desc}{player_command_desc}{twitch_command_desc}{update_command_desc}{ surviv_regions_command_desc}{supportserver_command_desc}", color=self.color) embed.set_footer( text=f"{self.name} Dashboard requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) StreamLogger.log( f'{ctx.message.author} ran {self.name} Command successfully.') except Exception as e: WarningLogger.log( f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {traceback.format_exc()}' )
async def player(self, ctx, player_name): try: player_lowered = player_name.lower() player_payload = { "slug": f"{player_lowered}", "interval": "all", "mapIdFilter": "-1" } async with self._session.post(self.url, headers=self.headers, json=player_payload) as r: player_data = await r.json() if not player_data: # no such player embed = discord.Embed( description= f"**{player_name}** is not a valid player of surviv.io.", color=self.color) embed.set_footer( text=f"{self.name} Stats requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) else: kills = player_data["kills"] wins = player_data["wins"] games = player_data["games"] kg = player_data["kpg"] mostkills = max([i["mostKills"] for i in player_data["modes"]]) maxDamage = max( [i["mostDamage"] for i in player_data["modes"]]) embed = discord.Embed( title=f" **{player_data['username']}'s Stats**", description= f"**Wins**: {wins} \n **Kills**: {kills} \n **Games**: {games} \n **Kill Per Game Avg**: {kg} \n **Max Kills**: {mostkills} \n **Most Damage**: {maxDamage}", color=self.color, ) embed.set_footer( text=f"{self.name} Stats requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) StreamLogger.log( f'{ctx.message.author} ran {self.name} Command successfully.') except Exception as e: WarningLogger.log( f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {traceback.format_exc()}' ) error_embed = discord.Embed( description= f"**{self.name}** command did not run as expected.\nPlease log an issue with `{ctx.prefix}issue`", color=self.color) await ctx.send(embed=error_embed)
async def gun(self, ctx, *args): gun = ' '.join(args).strip() if gun == '': gun = "''" try: conn = await aiosqlite.connect('data/rotating/surviv.db') c = await conn.cursor() await c.execute('select * from guns') res = await c.fetchall() for t in res: if gun.lower() == t[0].lower(): break if t[0].lower() != gun.lower(): guns = [i for i in list(zip(*res))[0]] embed = discord.Embed( description= f"\"**{gun}**\" is not a valid gun in **surviv.io**\n\n**Valid Guns**: {', '.join(guns)}", color=self.color, ) embed.set_footer( text=f"{self.name} Stats requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) else: embed = discord.Embed( title=f"{t[0]} Stats", description= f"**Bullet Damage**: {t[1]} \n **Shot Spread**: {t[2]} \n **Reload Time**: {t[3]} \n **Firing Delay**: {t[4]}", color=self.color, ) embed.set_footer( text=f"{self.name} Stats requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) StreamLogger.log( f'{ctx.message.author} ran {self.name} Command successfully.') await conn.close() except Exception as e: try: await conn.close() except: pass WarningLogger.log( f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {traceback.format_exc()}' )
async def help(self, ctx): try: disc = f"\n**NOTE**: You can find the arguments a command supports by typing the command with `args` at the end.\n**Example**: `{ctx.prefix}player`\n" intro = "The Riptide Bot supports commands for the game **surviv.io**.\nThe Game is playable at https://surviv.io/." info_command_desc = f"ℹ `{ctx.prefix}info` - Returns some information on the game surviv.io.\n" melee_command_desc = f"🔪 `{ctx.prefix}melee` - Returns stats for a melee weapon in surviv.io.\n" link_command_desc = f"🔗 `{ctx.prefix}link` - Returns a party link for surviv.io that expires in 7 seconds.\n" gun_command_desc = f"\U0001F52B `{ctx.prefix}gun` - Returns stats for a gun in surviv.io.\n" player_command_desc = f"⛹ `{ctx.prefix}player` - Returns stats for a player in surviv.io.\n" twitch_command_desc = f"🕹️ `{ctx.prefix}twitch` - Returns the top streamers currently streaming surviv.io.\n" update_command_desc = f"🆕 `{ctx.prefix}update` - Returns the current update in surviv.io.\n" embed = discord.Embed(title="<:surviv:743213975889641575> Surviv.io Commands <:surviv:743213975889641575>", description = f"{disc}\n{intro}\n\n{info_command_desc}{melee_command_desc}{link_command_desc}{gun_command_desc}{player_command_desc}{twitch_command_desc}{update_command_desc}", color=self.color) embed.set_footer(text=f"{self.name} Dashboard requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) StreamLogger.log(f'{ctx.message.author} ran {self.name} Command successfully.') except Exception as e: WarningLogger.log(f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {traceback.format_exc()}')
async def twitch(self, ctx): try: async with self._session.get(self.url, headers=self.headers) as r: raw_json = await r.json() # parse json embed = discord.Embed( title="Current Surviv Streamers", description= "[Surviv.io on Twitch!](https://www.twitch.tv/directory/game/surviv.io)", color=self.color) for t in raw_json['twitch']: embed.add_field( name=f"Streamer: {t['name']}", value= f"Watch: [{t['title']}]({t['url']})\nViewers: `{t['viewers']}`", inline=True) if not len(raw_json['twitch']): embed = discord.Embed( description= "No Surviv Twitch Streamers are **currently streaming**.", color=self.color) embed.set_footer( text= f"{self.name} Dashboard requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) StreamLogger.log( f'{ctx.message.author} ran {self.name} Command successfully.' ) except Exception as e: WarningLogger.log( f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {traceback.format_exc()}' ) error_embed = discord.Embed( description= f"**{self.name}** command did not run as expected.\nPlease log an issue with `{ctx.prefix}issue`", color=self.color) await ctx.send(embed=error_embed)
async def melee(self, ctx, *args): wep = ' '.join(args).strip() if wep == '': wep = "''" try: conn = await aiosqlite.connect('data/rotating/surviv.db') c = await conn.cursor() await c.execute('select * from melee') res = await c.fetchall() for t in res: if wep.lower() == t[0]: break if t[0] != wep.lower(): weps = [string.capwords(i) for i in list(zip(*res))[0]] embed = discord.Embed( description=f'"**{wep}**" is not a valid melee weapon in **surviv.io**\n\n**Valid Weapons**: {", ".join(weps)}', color=self.color, ) embed.set_footer(text=f"{self.name} Stats requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) else: embed = discord.Embed( title=f"{string.capwords(t[0])} Stats", description=f"**Damage**: {t[2]} \n **Attack Radius**: {t[3]} \n **Equip Speed**: {t[1]} \n **Cooldown Time**: {t[4]} \n **Auto Attack**: {t[5]} \n", color=self.color, ) embed.set_footer(text=f"{self.name} Stats requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await ctx.send(embed=embed) StreamLogger.log(f'{ctx.message.author} ran {self.name} Command successfully.') await conn.close() except Exception as e: WarningLogger.log(f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {traceback.format_exc()}') try: await conn.close() except: pass
def main(config: argparse.Namespace): """Train or evaluate a dictionary learning model.""" np.random.seed(config.seed) # Determine dataset directory if config.dataset == Dataset.ORL: data_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, "data", "ORL") original_shape = (112, 92) elif config.dataset == Dataset.YALEB: data_dir = os.path.join(os.path.dirname(__file__), os.path.pardir, "data", "CroppedYaleB") original_shape = (192, 168) else: raise NotImplementedError() original_shape = tuple([s // config.reduce for s in original_shape]) # Create loggers loggers = [ StreamLogger(), JSONLLogger(Path(config.results_dir) / f"{config.id}.jsonl") ] if config.wandb: loggers.append(WandbLogger()) # Create preprocessor (noise function) print(colored("preprocessor:", attrs=["bold"])) preprocessor_factory = PreprocessorFactory() preprocessor = preprocessor_factory.create(config) print(config.noise) # Load dataset print(colored("dataset:", attrs=["bold"])) noisy_images, clean_images, labels = load_data(root=data_dir, reduce=config.reduce, scale=config.scale, preprocessor=preprocessor) print(config.dataset) print(f"full: {clean_images.shape}") # Generate indices to train and test on np.random.seed(config.seed) indices = np.random.permutation(labels.shape[0]) take = int(config.subset * labels.shape[0]) train_data = noisy_images[:, indices][:, :take] test_data = clean_images[:, indices][:, :take] test_labels = labels[indices][:take] print( f"subset: {train_data.shape} using indices", f"[{', '.join([str(val) for val in indices[:min(10, take)]])}, ...]", ) # Create model print(colored("model:", attrs=["bold"])) model_factory = ModelFactory() model = model_factory.create(train_data, config) print(config.model) # Train and evaluate model print(colored("training:", attrs=["bold"])) model.fit( max_iter=config.iterations, tol=config.tolerance, callback_freq=config.log_step, callbacks=loggers, clean_data=test_data, true_labels=test_labels, ) # Log data samples and model dictionaries if config.wandb: img_count = 8 logger = WandbLogger(commit=False) test_samples = test_data.T[:img_count].reshape( (img_count, *original_shape)) logger({ "original": [ wandb.Image( sample, caption=f"id: {indices[i]}, class: {test_labels[i]}") for i, sample in enumerate(test_samples) ] }) train_samples = train_data.T[:img_count].reshape( (img_count, *original_shape)) logger({ "noisy": [ wandb.Image( sample, caption=f"id: {indices[i]}, class: {test_labels[i]}") for i, sample in enumerate(train_samples) ] }) reconstructed_samples = ( model.reconstructed_data().T[:img_count].reshape( (img_count, *original_shape))) logger({ "reconstructed": [ wandb.Image( sample, caption=f"id: {indices[i]}, class: {test_labels[i]}") for i, sample in enumerate(reconstructed_samples) ] }) w_components = model.W.reshape( (*original_shape, config.components))[:, :, :img_count] logger({ "w": [ wandb.Image(rescale(w_components[:, :, i]), caption=f"component: {i}") for i in range(w_components.shape[2]) ] }) # Plot the response of the images to each component in W as a heatmap h_y, h_x = np.meshgrid(np.arange(model.H.shape[0]), np.arange(img_count)) h_x = list(h_x.T.flatten()) h_y = list(h_y.T.flatten()) h_values = list(model.H[:, :img_count].flatten()) h_labels = list(test_labels[:img_count]) * model.H.shape[0] # Assert matrix reshapes match up for row in range(model.H.shape[0]): for col in range(img_count): assert abs( float(h_values[row * img_count + col]) - float(model.H[row][col])) < 1e-4 assert col == int(h_x[row * img_count + col]) assert row == int(h_y[row * img_count + col]) h = wandb.Table( data=[list(row) for row in zip(h_x, h_y, h_values, h_labels)], columns=["x", "y", "value", "label"], ) logger({"h": h})
async def link(self, ctx): try: embed = discord.Embed(description="(1/5) **Starting Process** ...", color=self.color) status = await ctx.send(embed=embed) arsenic_session = await start_session( services.Geckodriver(), browsers.Firefox(), ) embed = discord.Embed(description="(2/5) **Spawned Instance** ...", color=self.color) await status.edit(embed=embed) await arsenic_session.get(self.url) make_team_btn = await arsenic_session.get_element( '#btn-create-team') embed = discord.Embed(description="(3/5) **Locating target** ...", color=self.color) await status.edit(embed=embed) await make_team_btn.click() embed = discord.Embed( description="(4/5) **Retrieving Party Link** ...", color=self.color) await status.edit(embed=embed) await asyncio.sleep( 2 ) # add a small sleep delay for the party link to load up (a bit risky) party_url = await arsenic_session.get_url() embed = discord.Embed( description= f"**Party Link**: {party_url}\nLink Generator will leave in 7 seconds.", color=self.color) await status.edit(embed=embed) await asyncio.sleep(4) # waits 7 seconds before leaving await status.edit(embed=discord.Embed( description= f"**Party Link**: {party_url}\nLink Generator is leaving soon ...", color=self.color)) await asyncio.sleep(6) # add more than 3 for extra time embed = discord.Embed( description=f"**Link Generator left.**\nOld Link: {party_url}", color=self.color) embed.set_footer( text=f"{self.name} requested by {ctx.message.author}", icon_url=ctx.author.avatar_url) await status.edit(embed=embed) StreamLogger.log( f'{ctx.message.author} ran {self.name} Command successfully.') await stop_session(arsenic_session) except Exception as e: try: await stop_session(arsenic_session) except: pass WarningLogger.log( f'{ctx.message.author} ran {self.name} Command unsuccessfully. Raised {e}' ) error_embed = discord.Embed( description= f"**{self.name}** command did not run as expected.\nPlease log an issue with `{ctx.prefix}issue`", color=self.color) await ctx.send(embed=error_embed)
def main(config: argparse.Namespace): """Train or evaluate a label-noise-robust model.""" # Get environment info print(colored("environment:", attrs=["bold"])) print( f"device: {torch.cuda.get_device_name(config.device) if config.device != 'cpu' else 'cpu'}" ) # Load dataset print(colored("dataset:", attrs=["bold"])) print(config.dataset) # Determine dataset directory train_data, val_data, test_data = load_data( os.path.join(os.path.dirname(__file__), os.path.pardir, "data"), config.dataset, config.subset, config.seed, ) print(f"train: {[tuple(t.shape) for t in train_data.tensors]}") print(f"val: {[tuple(t.shape) for t in val_data.tensors]}") print(f"test: {[tuple(t.shape) for t in test_data.tensors]}") # Create loggers loggers = [ StreamLogger(), JSONLLogger(Path(config.results_dir) / f"{config.id}.jsonl") ] if config.wandb: loggers.append(WandbLogger()) input_size = tuple(train_data.tensors[0].size()[1:]) class_count = len(set(train_data.tensors[1].tolist())) criterion = torch.nn.CrossEntropyLoss() # Create backbone print(colored("backbone:", attrs=["bold"])) backbone_factory = BackboneFactory(input_size, class_count) backbone = backbone_factory.create(config) print(backbone) # Perform pretraining on noisy data without the transition matrix if necessary if config.backbone_pretrain_epochs > 0: print(colored("pretraining backbone:", attrs=["bold"])) backbone = backbone.to(config.device) pretrain_backbone( backbone, train_data, torch.optim.SGD(backbone.parameters(), lr=1e-3), criterion, loggers, config, ) # Estimator could be None if we don't want to use a transition matrix # Create transition matrix print(colored("estimator:", attrs=["bold"])) estimator_factory = EstimatorFactory(class_count) estimator = estimator_factory.create( config, backbone, DataLoader(train_data, batch_size=config.batch_size, shuffle=False, num_workers=0), ) if estimator is not None: print(f"Transition matrix to be usd by the Label Noise Robust Model:\n" f"{estimator.transitions=}") if config.wandb: wandb.run.summary["transitions"] = estimator.transitions.t( ).detach().cpu().numpy() # Create model from backbone and estimator criterion_factory = LossFactory() criterion = criterion_factory.create(estimator, config) # Get a new backbone backbone = backbone_factory.create(config) optimiser = torch.optim.SGD(backbone.parameters(), lr=config.lr) scheduler = torch.optim.lr_scheduler.StepLR(optimiser, step_size=config.schedule_step, gamma=config.schedule_gamma) # Train and evaluate model print(colored("training:", attrs=["bold"])) train( backbone, train_data, val_data, test_data, optimiser, scheduler, criterion, loggers, config, ) test(backbone, test_data, loggers, config)