pokemon-habit / utils.py
panda1835's picture
Upload 2 files
ad9b99b
raw
history blame
6.22 kB
import random
import json
import pypokedex
import json
import datetime
import requests
from huggingface_hub import login, HfApi
import os
hf_token = os.environ["HF_TOKEN"]
login(hf_token)
hfapi = HfApi()
metadata_url = "https://huggingface.co/spaces/panda1835/pokemon-data/raw/main/metadata.json"
def read_json_from_url(url):
try:
response = requests.get(url)
response.raise_for_status() # Will raise an HTTPError if the HTTP request returned an unsuccessful status code
json_data = response.json()
return json_data
except requests.RequestException as e:
print(f"Error occurred: {e}")
return None
def read_metadata():
# Open the JSON file and read its contents
# with open("metadata.json", "r") as json_file:
# metadata = json.load(json_file)
metadata = read_json_from_url(metadata_url)
# Access the JSON data
return metadata
def save_metadata(metadata):
with open("metadata.json", "w") as json_file:
json.dump(metadata, json_file, indent=4)
try:
hfapi.upload_file(
path_or_fileobj="metadata.json",
path_in_repo="metadata.json",
repo_id="panda1835/pokemon-data",
repo_type="space",
)
return "### Data updated ✅"
except Exception as e:
return "❌ " + str(e)
def get_all_pokemon_dex():
metadata = read_metadata()
return list(metadata["pokemon"].keys())
def get_streak():
metadata = read_metadata()
return metadata["streak"]
def get_total_minifigure():
metadata = read_metadata()
return metadata["total_minifigure"]
def get_money():
metadata = read_metadata()
return metadata["money"]
def get_pokemon():
metadata = read_metadata()
return metadata["pokemon"]
def get_pokemon_by_dex(dex):
metadata = read_metadata()
return metadata["pokemon"][dex]
def get_donation():
metadata = read_metadata()
return metadata["donation"]
def get_wishlist():
metadata = read_metadata()
return metadata["wishlist"]
def get_poke_energy(dex):
metadata = read_metadata()
return metadata["pokemon"][dex]["energy"]
def pokemon(dex):
pokemon = pypokedex.get(dex=dex)
description = pokemon.get_descriptions()
try:
description = description[list(description.keys())[0]].replace('\n', ' ')
except:
description = "Not yet understood"
name = pokemon.name.capitalize()
image = list(pokemon.other_sprites.values())[2].front['default']
try:
sprite = pokemon.sprites.front['default']
except:
sprite = None
return name, description, image, sprite
def random_pokemon():
min_dex = 1
max_dex = 1017
all_dex = get_all_pokemon_dex()
while True:
dex = random.randint(min_dex, max_dex)
if dex not in all_dex:
name, description, image, sprite = pokemon(dex)
break
random_pokemon = {
dex: {
"name": name,
"image": image,
"sprite": sprite,
"description": description,
"energy": 0
}
}
return random_pokemon
def add_new_pokemon(new_pokemon):
metadata = read_metadata()
dex = list(new_pokemon.keys())[0]
metadata["pokemon"][dex] = new_pokemon[dex]
return metadata
def is_lucky(streak):
p = (-0.0274 * streak + 30) / 100
# Generate a random number from the Bernoulli distribution
random_number = random.choices([0, 1], weights=[1-p, p])[0]
return random_number == 1
def lucky_draw():
"""Placeholder
0 = 50 energy
1 = a new pokemon
2 = money
3 = minifigure
"""
metadata = read_metadata()
gifts = ['energy', 'pokemon', 'money', 'minifigure']
random_number = random.choices([0, 1, 2, 3], weights=[0.3, 0.3, 0.3, 0.1])[0]
gift = gifts[random_number]
if gift == 'money':
money = random.choices([20000, 50000, 100000], weights=[0.4, 0.4, 0.4])[0]
metadata["money"] += money
save_metadata(metadata)
return ('money', money)
elif gift == 'pokemon':
new_pokemon = random_pokemon()
metadata = add_new_pokemon(new_pokemon)
save_metadata(metadata)
return ("pokemon", new_pokemon)
elif gift == 'energy':
all_dex = get_all_pokemon_dex()
random_dex = random.choice(all_dex)
metadata["pokemon"][random_dex]["energy"] += 50
save_metadata(metadata)
return ('energy', random_dex, 50)
else:
metadata["total_minifigure"] += 1
save_metadata(metadata)
return ('minifigure', 'https://u6wdnj9wggobj.vcdn.cloud/media/catalog/product/cache/a237138a07ed0dd2cc8a6fa440635ea6/7/1/71034_3_.jpg')
def poke_energy(streak, intensity):
return round(7 + streak/60 + intensity)
def new_streak(intensity):
metadata = read_metadata()
metadata["streak"] += 1
streak = metadata["streak"]
reward = ""
if is_lucky(streak):
gift = lucky_draw()
if gift[0] == 'money':
gift_str = f"{gift[1]} VND"
if gift[0] == 'pokemon':
new_pokemon = gift[1]
dex = list(new_pokemon.keys())[0]
gift_str = f"**{new_pokemon[dex]['name']}**"
if gift[0] == 'minifigure':
gift_str = "a minifigure"
if gift[0] == 'energy':
gift_str = f"{gift[2]} energy point to {get_pokemon_by_dex(gift[1])['name']}"
reward += f"**Lucky*!!!* You are rewarded {gift_str}.\n\n"
# Update new reward
metadata = read_metadata()
all_dex = get_all_pokemon_dex()
random_dex = random.choice(all_dex)
energy = poke_energy(streak, intensity)
metadata["pokemon"][random_dex]["energy"] += energy
reward += f"Your **{metadata['pokemon'][random_dex]['name']}** has just got **{energy} EXP**.\n\n"
save_metadata(metadata)
is_first_day_of_week = datetime.date.today().weekday() == 0
if is_first_day_of_week:
new_pokemon = random_pokemon()
add_new_pokemon(new_pokemon)
dex = list(new_pokemon.keys())[0]
reward += f"**{new_pokemon[dex]['name']}** has joined with your family!!!"
return reward