feat: Add pokemon cries

Add pokemon cries resource field to pokemon endpoint
This commit is contained in:
FallenDeity 2024-02-03 00:15:39 +05:30
parent 4c346c45d6
commit 02baf0b3ef
5 changed files with 104 additions and 1 deletions

View file

@ -36,8 +36,16 @@ MEDIA_DIR = "{prefix}{{file_name}}".format(
"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/", "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/",
) )
) )
SOUND_DIR = "{prefix}{{file_name}}".format(
prefix=os.environ.get(
"POKEAPI_CRIES_PREFIX",
"https://raw.githubusercontent.com/PokeAPI/cries/main/cries/",
)
)
IMAGE_DIR = os.getcwd() + "/data/v2/sprites/sprites/" IMAGE_DIR = os.getcwd() + "/data/v2/sprites/sprites/"
CRIES_DIR = os.getcwd() + "/data/v2/cries/cries/"
RESOURCE_IMAGES = [] RESOURCE_IMAGES = []
RESOURCE_CRIES = []
for root, dirs, files in os.walk(IMAGE_DIR): for root, dirs, files in os.walk(IMAGE_DIR):
for file in files: for file in files:
@ -45,8 +53,18 @@ for root, dirs, files in os.walk(IMAGE_DIR):
image_path = image_path.replace("\\", "/") # convert Windows-style path to Unix image_path = image_path.replace("\\", "/") # convert Windows-style path to Unix
RESOURCE_IMAGES.append(image_path) RESOURCE_IMAGES.append(image_path)
for root, dirs, files in os.walk(CRIES_DIR):
for file in files:
cry_path = os.path.join(root.replace(CRIES_DIR, ""), file)
cry_path = cry_path.replace("\\", "/") # convert Windows-style path to Unix
RESOURCE_CRIES.append(cry_path)
def file_path_or_none(file_name):
def file_path_or_none(file_name, image_file=True):
if not image_file:
return (
SOUND_DIR.format(file_name=file_name) if file_name in RESOURCE_CRIES else None
)
return ( return (
MEDIA_DIR.format(file_name=file_name) if file_name in RESOURCE_IMAGES else None MEDIA_DIR.format(file_name=file_name) if file_name in RESOURCE_IMAGES else None
) )
@ -1931,6 +1949,26 @@ def _build_pokemons():
build_generic((PokemonSprites,), "pokemon.csv", csv_record_to_objects) build_generic((PokemonSprites,), "pokemon.csv", csv_record_to_objects)
def try_cry_names(path, info, extension):
file_name = "%s.%s" % (info[0], extension)
return file_path_or_none(path + file_name, image_file=False)
def csv_record_to_objects(info):
poke_cries = "pokemon"
latest = f"{poke_cries}/latest/"
legacy = f"{poke_cries}/legacy/"
cries = {
"latest": try_cry_names(latest, info, "ogg"),
"legacy": try_cry_names(legacy, info, "ogg"),
}
yield PokemonCries(
id=int(info[0]),
pokemon=Pokemon.objects.get(pk=int(info[0])),
cries=cries,
)
build_generic((PokemonCries,), "pokemon.csv", csv_record_to_objects)
def csv_record_to_objects(info): def csv_record_to_objects(info):
yield PokemonAbility( yield PokemonAbility(
pokemon_id=int(info[0]), pokemon_id=int(info[0]),

View file

@ -0,0 +1,25 @@
# Generated by Django 3.2.23 on 2024-02-02 18:02
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pokemon_v2', '0014_auto_20231121_1209'),
]
operations = [
migrations.CreateModel(
name='PokemonCries',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('cries', models.JSONField()),
('pokemon', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='pokemoncries', to='pokemon_v2.pokemon')),
],
options={
'abstract': False,
},
),
]

View file

@ -1796,3 +1796,8 @@ class PokemonTypePast(HasPokemon, HasType, HasGeneration):
class PokemonSprites(HasPokemon): class PokemonSprites(HasPokemon):
sprites = models.JSONField() sprites = models.JSONField()
class PokemonCries(HasPokemon):
cries = models.JSONField()

View file

@ -2722,6 +2722,7 @@ class PokemonDetailSerializer(serializers.ModelSerializer):
held_items = serializers.SerializerMethodField("get_pokemon_held_items") held_items = serializers.SerializerMethodField("get_pokemon_held_items")
location_area_encounters = serializers.SerializerMethodField("get_encounters") location_area_encounters = serializers.SerializerMethodField("get_encounters")
sprites = serializers.SerializerMethodField("get_pokemon_sprites") sprites = serializers.SerializerMethodField("get_pokemon_sprites")
cries = serializers.SerializerMethodField("get_pokemon_cries")
class Meta: class Meta:
model = Pokemon model = Pokemon
@ -2742,6 +2743,7 @@ class PokemonDetailSerializer(serializers.ModelSerializer):
"moves", "moves",
"species", "species",
"sprites", "sprites",
"cries",
"stats", "stats",
"types", "types",
"past_types", "past_types",
@ -2751,6 +2753,10 @@ class PokemonDetailSerializer(serializers.ModelSerializer):
sprites_object = PokemonSprites.objects.get(pokemon_id=obj) sprites_object = PokemonSprites.objects.get(pokemon_id=obj)
return sprites_object.sprites return sprites_object.sprites
def get_pokemon_cries(self, obj):
cries_object = PokemonCries.objects.get(pokemon_id=obj)
return cries_object.cries
def get_pokemon_moves(self, obj): def get_pokemon_moves(self, obj):
version_objects = VersionGroup.objects.all() version_objects = VersionGroup.objects.all()
version_data = VersionGroupSummarySerializer( version_data = VersionGroupSummarySerializer(

View file

@ -1725,6 +1725,20 @@ class APIData:
return pokemon_sprites return pokemon_sprites
@classmethod
def setup_pokemon_cries_data(cls, pokemon, latest=True, legacy=False):
cries_path = "https://raw.githubusercontent.com/PokeAPI/cries/main/cries/pokemon/%s.ogg"
cries = {
"latest": cries_path % f"latest/{pokemon.id}" if latest else None,
"legacy": cries_path % f"legacy/{pokemon.id}" if legacy else None,
}
pokemon_cries = PokemonCries.objects.create(
pokemon=pokemon,
cries=json.dumps(cries)
)
pokemon_cries.save()
return pokemon_cries
# Evolution Data # Evolution Data
@classmethod @classmethod
def setup_evolution_trigger_data(cls, name="evltn trgr"): def setup_evolution_trigger_data(cls, name="evltn trgr"):
@ -4596,6 +4610,7 @@ class APITests(APIData, APITestCase):
pokemon_species=pokemon_species, name="pkm for base pkmn spcs" pokemon_species=pokemon_species, name="pkm for base pkmn spcs"
) )
self.setup_pokemon_sprites_data(pokemon) self.setup_pokemon_sprites_data(pokemon)
self.setup_pokemon_cries_data(pokemon)
response = self.client.get( response = self.client.get(
"{}/pokemon-species/{}/".format(API_V2, pokemon_species.pk), "{}/pokemon-species/{}/".format(API_V2, pokemon_species.pk),
@ -4816,6 +4831,7 @@ class APITests(APIData, APITestCase):
) )
pokemon_item = self.setup_pokemon_item_data(pokemon=pokemon) pokemon_item = self.setup_pokemon_item_data(pokemon=pokemon)
pokemon_sprites = self.setup_pokemon_sprites_data(pokemon=pokemon) pokemon_sprites = self.setup_pokemon_sprites_data(pokemon=pokemon)
pokemon_cries = self.setup_pokemon_cries_data(pokemon, latest=True, legacy=True)
pokemon_game_index = self.setup_pokemon_game_index_data( pokemon_game_index = self.setup_pokemon_game_index_data(
pokemon=pokemon, game_index=10 pokemon=pokemon, game_index=10
) )
@ -5052,7 +5068,9 @@ class APITests(APIData, APITestCase):
) )
sprites_data = json.loads(pokemon_sprites.sprites) sprites_data = json.loads(pokemon_sprites.sprites)
cries_data = json.loads(pokemon_cries.cries)
response_sprites_data = json.loads(response.data["sprites"]) response_sprites_data = json.loads(response.data["sprites"])
response_cries_data = json.loads(response.data["cries"])
# sprite params # sprite params
self.assertEqual( self.assertEqual(
@ -5070,6 +5088,17 @@ class APITests(APIData, APITestCase):
response_sprites_data["other"]["showdown"]["back_default"], response_sprites_data["other"]["showdown"]["back_default"],
) )
# cries params
self.assertEqual(
cries_data["latest"],
"{}".format(cries_data["latest"]),
)
self.assertEqual(
cries_data["legacy"],
"{}".format(cries_data["legacy"]),
)
def test_pokemon_form_api(self): def test_pokemon_form_api(self):
pokemon_species = self.setup_pokemon_species_data() pokemon_species = self.setup_pokemon_species_data()
pokemon = self.setup_pokemon_data(pokemon_species=pokemon_species) pokemon = self.setup_pokemon_data(pokemon_species=pokemon_species)