async def seasonal(ctx,rank=9999): jk = Jikan() anime = jk.season(year=2020,season='summer')['anime'] if rank != 9999: rank = rank -1 if rank > len(anime): await ctx.send('baka, Only {} new anime this summer'.format(len(anime))) else: data = "{} \n\nName: {}\nScore: {}\nEpisodes: TBA\n".format(anime[rank]['image_url'],anime[rank]['title'],anime[rank]['score']) await ctx.send(data) else: for i in range(10): if anime[i]['episodes'] == None: data = "{} \n\nName: {}\nScore: {}\nEpisodes: TBA\n".format(anime[i]['image_url'],anime[i]['title'],anime[i]['score']) else: data = "{} \n\nName: {}\nScore: {}\nEpisodes: {}\n".format(anime[i]['image_url'],anime[i]['title'],anime[i]['score'],anime[i]['episodes']) await ctx.send(data)
def get_json(self, req_anime_list, season, year): jikan = Jikan() animes_this_season = jikan.season(year=year, season=season) animes = [] for anime in animes_this_season['anime']: for req_anime in req_anime_list: if anime['title'] == req_anime['name']: anime_details = jikan.anime(anime['mal_id']) ani = copy.deepcopy(anime) ani['torrentname'] = req_anime['torrentname'] ani['quality'] = req_anime['quality'] ani['search_queries'] = self.create_search_queries( req_anime, anime_details) ani['have_prequel'] = self.check_new_anime(anime_details) ani['folder_name'] = req_anime['folder_name'] animes.append(ani) return animes
def get_series(season: str, year: int) -> Dict[int, str]: """Retrieve a list of (anime_id, anime_title) from the season info. Arguments: season: season to get series from year: year to get series from Returns: A dict from anime_id to anime_title. For example: {25879: 'Working!!!'} """ jikan = Jikan() # Get list of anime in the season season_info = jikan.season(year=year, season=season) assert season_info["season_name"].lower() == season assert season_info["season_year"] == year tv_anime = dict() for anime in season_info["anime"]: if anime["type"] == "TV": tv_anime[anime["mal_id"]] = anime["title"] return tv_anime
from jikanpy import Jikan jikan = Jikan() mushishi = jikan.anime(39617) mushishi_with_eps = jikan.anime(21, extension='episodes', page=10) search_result = jikan.search('anime', 'One Piece', page=1) winter_2018_anime = jikan.season(year=2021, season='winter') archive = jikan.season_archive() for anime in winter_2018_anime['anime']: if anime['title'] == 'One Piece': print(anime) print(archive) print(winter_2018_anime) print(search_result)
from jikanpy import Jikan jikan = Jikan() winter = jikan.season(year = 2015, season='winter') print(winter)
class Recomender: def __init__(self, user_name): self.user_name: str = user_name # MAL username self.jikan = Jikan() # API object self.anime_dic = {} # dic of anime id and it's score self.genre_dic = defaultdict( list) # dic of genres and a list of user scores for them self.studio_dic = defaultdict( list) # dic of studios and a list of user scores for them self.source_material_dic = defaultdict( list) # dic of source materials and a list of user scores for them self.type_dic = defaultdict( list) # dic of types and a list of user scores for them self.episodes_amount_dic = defaultdict( list ) # dic of episode amount enums and a list of user scores for them self.staff_dic = defaultdict( list) # dic of staff people and a list of user scores for them self.analyzed_anime_dic = { } # dic of analyzed seasonal anime and their scores self.anime_name_dic = {} # dic of MAL anime ids and names self.staff_name_dic = {} # dic of MAL staff ids and names """ Fills the anime_dic with the users rated anime """ def fill_anime_dic(self): print("Started filling anime dic.") last_page: bool = False page_num: int = 1 while not last_page: # the API only returns 300 anime so we may need to request multiple pages animelist = self.jikan.user(username=self.user_name, request='animelist', argument="all", page=page_num) if animelist["request_cached"] is False: time.sleep( SLEEP_TIME ) # if the request was uncached we need to add a delay or we get a 429 for anime in animelist["anime"]: if anime["score"] > 0: # only add the anime if the user set a score self.anime_dic[anime["mal_id"]] = anime["score"] if len(animelist["anime"] ) < 300: # each page contains max 300 anime last_page = True page_num += 1 """ Gathers data like genre or studio scores based upon the anime in the anime dic """ def gather_anime_data_from_anime_dic(self): print("Started gathering anime data from anime dic.") progress_counter = 1 for animeID in self.anime_dic.keys(): # go though every anime if progress_counter % 10 == 1: print("Gathered " + str(progress_counter) + " anime.") progress_counter += 1 anime = self.jikan.anime(animeID) if anime["request_cached"] is False: time.sleep(SLEEP_TIME) # sleep to prevent 429 anime_staff_full = self.jikan.anime( animeID, extension='characters_staff') # get staff data anime_staff = anime_staff_full["staff"] if anime_staff_full["request_cached"] is False: time.sleep(SLEEP_TIME) score = self.anime_dic[animeID] for genre in anime["genres"]: # add score for every genre self.genre_dic[genre["mal_id"]].append(score) for studio in anime["studios"]: # add score for every studio self.studio_dic[studio["mal_id"]].append(score) self.source_material_dic[anime["source"]].append( score) # add score for source material self.type_dic[anime["type"]].append(score) # add score for type episodes = anime["episodes"] if episodes is None: # if episodes are unset set the to zero episodes = 0 if episodes > 0: # only add score if episodes are set episodes_enum = self.get_episode_amount_enum(episodes) self.episodes_amount_dic[episodes_enum].append(score) for staff_member in anime_staff: for position in staff_member["positions"]: # only add the staff member if their position is relevant according to my own decision if position in POSITION_SET: self.staff_dic[staff_member["mal_id"]].append(score) self.staff_name_dic[ staff_member["mal_id"]] = staff_member["name"] """ analyzes the anime of a specific season with the data gathered from the user year = int, year of the season season = string, season of the year (either winter, spring, summer or fall) kids = boolean, if you want to analyze kids shows r18 = if you want to analyze r18 (hentai) shows """ def analyze_seasonal_anime(self, year, season, kids, r18): seasonal_anime_full = self.jikan.season(year=year, season=season) if seasonal_anime_full["request_cached"] is False: time.sleep(SLEEP_TIME) seasonal_anime = seasonal_anime_full["anime"] print("Started analyzing seasonal anime.") progress_counter = 1 for anime in seasonal_anime: if progress_counter % 10 == 1: print("Analyzed " + str(progress_counter) + " anime.") progress_counter += 1 if anime[ "continuing"]: # if the anime is actually from a previous season, don't analyze it continue if not r18 and anime["r18"]: continue if not kids and anime["kids"]: continue self.analyze_anime(anime) """ analyzes an anime and puts it and the score to the analyzed anime dic anime = either an anime object or the MAL ID as an int """ def analyze_anime(self, anime): if isinstance(anime, int): # if anime is an int get the anime object of it anime = self.jikan.anime(anime) score_divisor = 0 # variable through which the score in the end will be divided so that we get one that goes from 1 to 10 by adding the FACTOR of a value anime_staff_full = self.jikan.anime(anime["mal_id"], extension='characters_staff') if anime_staff_full["request_cached"] is False: time.sleep(SLEEP_TIME) anime_staff = anime_staff_full["staff"] score = 0.0 score_addition_counter = 0 # count how many scores were actually added to the score genre_amount = 0 genre_score = 0.0 for genre in anime["genres"]: if genre["mal_id"] in self.genre_dic.keys(): genre_amount += 1 # get the average of the scores in the list genre_score += sum(self.genre_dic[genre["mal_id"]]) / len( self.genre_dic[genre["mal_id"]]) if genre_amount > 0: # only add if there was atleast one genre score += genre_score / genre_amount * GENRE_FACTOR score_addition_counter += 1 score_divisor += GENRE_FACTOR studio_amount = 0 studio_score = 0.0 for studio in anime["producers"]: if studio["mal_id"] in self.studio_dic.keys(): studio_amount += 1 studio_score += sum(self.studio_dic[studio["mal_id"]]) / len( self.studio_dic[studio["mal_id"]]) if studio_amount > 0: score += studio_score / studio_amount * STUDIO_FACTOR score_addition_counter += 1 score_divisor += STUDIO_FACTOR if anime["source"] in self.source_material_dic: source_score = sum( self.source_material_dic[anime["source"]]) / len( self.source_material_dic[anime["source"]]) if source_score > 0: score += source_score * SOURCE_MATERIAL_FACTOR score_addition_counter += 1 score_divisor += SOURCE_MATERIAL_FACTOR if anime["type"] in self.type_dic: type_score = sum(self.type_dic[anime["type"]]) / len( self.type_dic[anime["type"]]) if type_score > 0: score += type_score * TYPE_FACTOR score_addition_counter += 1 score_divisor += TYPE_FACTOR episode_amount = anime["episodes"] if episode_amount is None: # check if episodes are set and if they are not set them to 0 episode_amount = 0 if episode_amount > 0: episode_enum = self.get_episode_amount_enum(episode_amount) if episode_enum in self.episodes_amount_dic: episode_amount_score = sum( self.episodes_amount_dic[episode_enum]) / len( self.episodes_amount_dic[episode_enum]) if episode_amount_score > 0: score += episode_amount_score * EPISODE_AMOUNT_FACTOR score_addition_counter += 1 score_divisor += EPISODE_AMOUNT_FACTOR staff_score = 0.0 staff_amount = 0 for staff_member in anime_staff: if staff_member["mal_id"] in self.staff_dic: staff_amount += 1 staff_score += sum( self.staff_dic[staff_member["mal_id"]]) / len( self.staff_dic[staff_member["mal_id"]]) if staff_amount > 0: staff_score /= staff_amount score += staff_score * STAFF_FACTOR score_addition_counter += 1 score_divisor += STAFF_FACTOR if score_addition_counter > 0: self.anime_name_dic[anime["mal_id"]] = anime["title"] self.analyzed_anime_dic[anime["mal_id"]] = ( (score / score_addition_counter) * (0.4 + 0.1 * score_addition_counter)) / ( score_divisor / score_addition_counter ) # calculate the score and add the anime to the dic """ writes a comma seperated value file with the result of the analyzed seasonal anime """ def write_analyzed_anime_to_file(self): with open("analyzed_anime.txt", mode="w", encoding="utf8") as text_file: text_file.write("Name^MAL ID^Score\n") for anime in self.analyzed_anime_dic.keys(): text_file.write( str(self.anime_name_dic[anime]) + "^" + str(anime) + "^" + str(self.analyzed_anime_dic[anime]) + "\n") print("Done writing anime file!") """ writes a comma seperated value file with staff members and their score """ def write_analyzed_staff_to_file(self): with open("analyzed_staff.txt", mode="w", encoding="utf8") as text_file: text_file.write("Name^MAL ID^Average^Amount^Score\n") max_len = -1 for staff in self.staff_dic.keys(): if len(self.staff_dic[staff]) > max_len: max_len = len(self.staff_dic[staff]) for staff in self.staff_dic.keys(): FACTOR = 0.866 length = len(self.staff_dic[staff]) scores_list = self.staff_dic[staff] average = sum(scores_list) / length text_file.write( str(self.staff_name_dic[staff]) + "^" + str(staff) + "^" + str(average) + "^" + str(length) + "^" + str(average * FACTOR + ((length / max_len) * (1.0 - FACTOR) * 10.0)) + "\n") print("Done writing staff file!") """ A Function that returns an Enum for summarizing episode amounts """ @staticmethod def get_episode_amount_enum(amount) -> EpisodesAmount: if amount < 1: return None elif amount == 1: return EpisodesAmount.One elif 2 <= amount <= 8: return EpisodesAmount.TwoEight elif 9 <= amount <= 19: return EpisodesAmount.NineNineteen elif 20 <= amount <= 30: return EpisodesAmount.TwentyThirty elif 31 <= amount <= 50: return EpisodesAmount.ThirtyoneFifty elif 51 <= amount <= 100: return EpisodesAmount.FiftyoneOnehundred else: return EpisodesAmount.OnehundredonePlus
def fetchAllAnimes(): #jikan.season_later() #jikan.schedule() #top_anime = jikan.top(type='anime') #winter_2018 = jikan.season(year=2018, season='winter') animes = [] jikan = Jikan() archive = jikan.season_archive() year = int(archive['archive'][0]['year']) d = enchant.Dict("en_US") while year >= 1975: for seasonname in archive['archive'][0]['seasons']: while True: try: season = jikan.season(year=year, season=seasonname) break except Exception as error: if '429' in str(error): print('[DetectAnime] Rate limited. Sleeping for 30secs...') time.sleep(30) else: print(error) pass for animesmall in season['anime']: id = animesmall['mal_id'] while True: try: anime = jikan.anime(int(id)) break except Exception as error: if '429' in str(error): print('[DetectAnime] Rate limited. Sleeping for 30secs...') time.sleep(30) else: logging.error(error) pass title = anime['title'] engtitle = anime['title_english'] japtitle = anime['title_japanese'] synonym = anime['title_synonyms'] try: isValidTitle = len(title) > 4 and not d.check(title) and not d.check(re.sub('[^A-Za-z ]+', '', title)) except Exception as e: print('[DetectAnime] Error determining validity of title: ' + str(e) + '. Defaulting to False.') isValidTitle = False if isValidTitle: print(f'[DetectAnime] Appending "{title}" with id {id}. List size is now {len(animes)}.') animes.append(title) spacedreg = re.sub(r'[^\w]|[ ]', ' ', title) if len(spacedreg) > 4: animes.append(spacedreg) blankedreg = re.sub(r'[^\w]|[ ]', '', title) if len(blankedreg) > 4: animes.append(spacedreg) try: isValidTitle = len(engtitle) > 4 and not d.check(engtitle) and not d.check(re.sub('[^A-Za-z ]+', '', engtitle)) except Exception as e: print('[DetectAnime] Error determining validity of title: ' + str(e) + '. Defaulting to False.') isValidTitle = False if isValidTitle: print(f'[DetectAnime] Appending "{engtitle}" with id {id}. List size is now {len(animes)}.') animes.append(engtitle) spacedreg = re.sub(r'[^\w]|[ ]', ' ', engtitle) if len(spacedreg) > 4: animes.append(spacedreg) blankedreg = re.sub(r'[^\w]|[ ]', '', engtitle) if len(blankedreg) > 4: animes.append(spacedreg) if not japtitle == None and len(japtitle) > 5: print(f'[DetectAnime] Appending "{japtitle}" with id {id}. List size is now {len(animes)}.') animes.append(japtitle) for syn in synonym: if len(syn) > 4: print(f'[DetectAnime] Appending synonym "{syn}" for "{title}". List size is now {len(animes)}.') animes.append(syn) spacedreg = re.sub(r'[^\w]|[ ]', ' ', syn) if len(spacedreg) > 4: animes.append(spacedreg) blankedreg = re.sub(r'[^\w]|[ ]', '', syn) if len(blankedreg) > 4: animes.append(spacedreg) year -= 1 animes = list(dict.fromkeys(animes)) animes = removeDupStrings(animes) return animes
jikan = Jikan() years = [year for year in range(2000, 2023)] seasons = ['winter', 'spring', 'summer', 'fall'] myanimelist = [] # In[12]: """ Skip running this block if the session "my_anime_list.db" has been loaded """ # Retrieve anime data through Jikan for year in years: for season in seasons: myanimelist.append(jikan.season(year=year, season=season)) # PHASE 1: Store and retrieve anime data in dataframes for search and sort # In[47]: # Collect all necessary attributes: Title, Score, Members, Genre, Producers, Year, Season and Synopsis animedata = [] for animeseason in myanimelist: for show in animeseason['anime']: animedata.append([ show['title'], show['score'], show['members'], ', '.join(genre['name'] for genre in show['genres']), ', '.join(producer['name'] for producer in show['producers']), animeseason["season_year"], animeseason["season_name"], show['synopsis']
mushishi = jikan.anime(457) pprint(mushishi) fma = jikan.manga(25) pprint(fma) ginko = jikan.character(425) pprint(ginko) kana_hanazawa = jikan.person(189) pprint(kana_hanazawa) naruto = jikan.search(search_type='anime', query='naruto') pprint(naruto) winter_2018 = jikan.season(year=2018, season='winter') pprint(winter_2018) archive = jikan.season_archive() pprint(archive) later = jikan.season_later() pprint(later) monday = jikan.schedule(day='monday') pprint(monday) top_anime = jikan.top(type='anime') pprint(top_anime) action = jikan.genre(type='anime', genre_id=1)
print(colored('Genres: ', 'green'), end='') for items in genres: print(colored(items + ' ', 'red'), end='') print('') print(colored('MAL link:', 'green'), colored(each['url'], 'blue')) print('') print(colored('Description: ', 'green'), each['synopsis']) print('-' * 80) if arg == 'upcoming': upcoming = jikan.season_later() search(upcoming) else: split = arg.split('-') try: year = int(split[0]) except ValueError: print('The given argument is not valid!\nEXP: 2016-winter') exit() seasons = ['winter', 'spring', 'fall', 'summer'] if split[1] not in seasons: print('No such a season!!') exit() search = jikan.season(year=year, season=split[1]) pprint(search)
mushishi = jikan.anime(457) pprint(mushishi) fma = jikan.manga(25) pprint(fma) ginko = jikan.character(425) pprint(ginko) kana_hanazawa = jikan.person(189) pprint(kana_hanazawa) naruto = jikan.search(search_type="anime", query="naruto") pprint(naruto) winter_2018 = jikan.season(year=2018, season="winter") pprint(winter_2018) archive = jikan.season_archive() pprint(archive) later = jikan.season_later() pprint(later) monday = jikan.schedule(day="monday") pprint(monday) top_anime = jikan.top(type="anime") pprint(top_anime) action = jikan.genre(type="anime", genre_id=1)
class MALHandler(object): def __init__(self): self.jikan = Jikan() self.fileHandler = FileHandler() self.dataPath = './data/meta' self.labelPath = './label/meta' self.allSeoson = ['spring', 'summer', 'fall', 'winter'] def getDetailSynopsisAndScore(self, id): detail_anime = self.jikan.anime(id) return detail_anime['score'] def getAnimeData(self, year, season): print('Getting all anime in {} {}'.format(year, season)) animeData = self.jikan.season(year=year, season=season) input = [] label = [] for anime in animeData['anime']: print('total:{}, processed:{}'.format(len(animeData['anime']), len(input))) synopsis = anime['synopsis'] synopsis = ' '.join(synopsis.splitlines()) synopsis = synopsis.replace(' ', ' ') if anime['score'] is None: while True: try: score = self.getDetailSynopsisAndScore(anime['mal_id']) except: time.sleep(10) else: break else: score = anime['score'] label.append(str(score)) input.append(synopsis) return input, label def saveAnimeData(self, year, season): input, label = self.getAnimeData(year, season) self.fileHandler.saveFileHandler( '{}/{}_{}_data.txt'.format(self.dataPath, year, season), input) self.fileHandler.saveFileHandler( '{}/{}_{}_label.txt'.format(self.labelPath, year, season), label) def loadData(self, year, season): data = self.fileHandler.loadFileHandler('{}/{}_{}_data.txt'.format( self.dataPath, year, season)) label = self.fileHandler.loadFileHandler('{}/{}_{}_label.txt'.format( self.labelPath, year, season)) if len(data) != len(label): raise RuntimeError('Input and label numbers not match!') return data, label def savaAllSeasonAnimeData(self, year): for season in self.allSeason: self.saveAnimeData(year, season) def run(self, formYear, toYear): for year in range(formYear, toYear): for season in self.allSeoson: self.saveAnimeData(year, season)
from jikanpy import Jikan import pandas as pd import time import pickle jikan = Jikan() winter = list() spring = list() summer = list() fall = list() years = range(1980, 2019) for Y in years: time.sleep(4) winter.append(jikan.season(year=2008, season='winter')) for Y in years: try: spring.append(jikan.season(year=2006, season='spring')) except: pass time.sleep(4) for Y in years: time.sleep(4) try: summer.append(jikan.season(year=1993, season='summer')) except: pass for Y in years: time.sleep(4) try: fall.append(jikan.season(year=2005, season='fall')) except:
# same as above, but with extra info # (see Jikan docs for information about which endpoints have which extensions) mushishi_with_eps = jikan.anime(457, extension='episodes') mushishi_with_eps_2 = jikan.anime(457, extension='episodes', page=2) mushishi_with_characters_and_staff = jikan.anime(457, extension='characters_staff') # pprint.pprint(mushishi_with_characters_and_staff) overlord = jikan.anime(37675) # pprint.pprint(overlord) pic_test = jikan.character(extension='pictures', id=11) pprint(pic_test['image']) # pprint.pprint(pic_test) season_sum_2018 = jikan.season(year=2018, season='summer') # pprint.pprint(season_sum_2018) # you can also query characters # ginko = jikan.character(425) # # and manga # mushishi_manga = jikan.manga(418) # # search # search_result = jikan.search('anime', 'Mushishi') # # add a page number to the search request # search_result = jikan.search('anime', 'Mushishi', page=2) # # add a filter to the search (see Jikan docs about what filters are legal) # search_result = jikan.search('anime', 'Mushishi', key='type', value='tv') # search_result = jikan.search('anime', 'Mushishi', key='genre', value=37) # # use it all!