File size: 11,323 Bytes
ad9b99b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81b9a71
ad9b99b
 
 
 
 
 
 
 
 
 
 
 
 
 
81b9a71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f1d918
 
 
 
 
 
 
 
 
 
 
81b9a71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ad9b99b
 
 
 
 
 
 
81b9a71
 
 
ad9b99b
 
 
 
 
 
 
 
81b9a71
 
 
ad9b99b
 
 
 
 
 
 
81b9a71
f2083e8
ad9b99b
 
 
b130354
 
ad9b99b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b130354
 
 
 
ad9b99b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2db9e9b
ad9b99b
 
 
 
 
9b39335
b130354
ad9b99b
 
81b9a71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bd506e7
81b9a71
bd506e7
81b9a71
 
 
 
 
 
 
 
 
 
ad9b99b
 
 
 
 
 
 
 
 
 
 
 
 
 
81b9a71
ad9b99b
81b9a71
ad9b99b
 
 
 
 
81b9a71
a55fb9d
81b9a71
 
 
44e479d
 
81b9a71
 
 
 
d4c0be5
 
 
 
81b9a71
 
 
 
ad9b99b
 
 
 
3ec62b4
 
 
 
 
ad9b99b
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
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 get_pokemon_info(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 get_evolution_chain(dex):
    # Fetch the Pokémon species data for Ivysaur
    pokemon = pypokedex.get(dex=dex)
    name = pokemon.name
    species_url = f"https://pokeapi.co/api/v2/pokemon-species/{name}"
    species_response = requests.get(species_url)
    species_data = json.loads(species_response.text)

    # Extract the evolution chain URL
    evolution_chain_url = species_data['evolution_chain']['url']

    # Fetch the evolution chain data
    evolution_chain_response = requests.get(evolution_chain_url)
    evolution_chain_data = json.loads(evolution_chain_response.text)

    # Parse the evolution chain data and get the full list of evolutions
    evolution_list = []
    chain = evolution_chain_data['chain']
    try:
        while chain:
            species_name = chain['species']['name']
            evolution_list.append(pypokedex.get(name=species_name).dex)
            if chain.get('evolves_to') != []:
                chain = chain.get('evolves_to')[0]
            else:
                break
    except Exception as e:
        evolution_list = [name]
        print(str(e))
    return evolution_list

def can_evolve(dex, energy):
    metadata = read_metadata()
    if metadata["pokemon"][dex]["max_energy"] <= energy:
        return True
    else:
        return False

def evolve_to(dex):
    evolution_chain = get_evolution_chain(dex)
    print(evolution_chain)
    # If fully evolved
    if dex == evolution_chain[-1]:
        return None
    else:
        evolve_dex = evolution_chain[evolution_chain.index(dex) + 1]
        name, description, image, sprite = get_pokemon_info(evolve_dex)
        return {
            evolve_dex: {
                "name": name,
                "image": image,
                "sprite": sprite,
                "description": description,
                "energy": 0,
                "max_energy": 100 + 20*(evolution_chain.index(dex) + 1),
                "visible": True
            }
        }

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 not in the team and the first level
        if (dex not in all_dex) and (dex == get_evolution_chain(dex)[0]):
            name, description, image, sprite = get_pokemon_info(dex)
            break

    random_pokemon = {
        dex: {
            "name": name,
            "image": image,
            "sprite": sprite,
            "description": description,
            "energy": 0,
            "max_energy": 100,
            "visible": True
        }
    }

    return random_pokemon

def add_new_pokemon(new_pokemon):
    metadata = read_metadata()
    metadata["pokemon"].update(new_pokemon)
    save_metadata(metadata)
    return metadata

def is_lucky(streak):
    if (streak == 2) or (streak == 3):
        return True
    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']
    if (metadata["streak"] == 2) or (metadata["streak"] == 3):
        random_number = 1
    else:
        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*2)

def new_streak(intensity):
    metadata = read_metadata()
    metadata["streak"] += 1
    streak = metadata["streak"]
    save_metadata(metadata)
    
    reward = ""

    date1 = datetime.datetime.today()
    date2 = datetime.datetime.strptime(metadata["last_streak_day"], "%d/%m/%Y")
    delta = date1 - date2
    distance = delta.days

    if (distance >= 2):
        metadata = {
            "streak": 0,
            "total_minifigure": 0,
            "donation": [
                {
                    "wildact": {
                        "donation_link": "https://www.wildact-vn.org/en/support-us/donate/",
                        "image": "https://a-us.storyblok.com/f/1014782/567x567/7338612d04/wa_logo-2023-vn.png"
                    }
                }
            ],
            "last_streak_day": datetime.datetime.today().strftime("%d/%m/%Y"),
            "money": 0,
            "pokemon": {
                "4": {
                    "name": "Charmander",
                    "image": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/4.png",
                    "sprite": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/4.png",
                    "description": "Obviously prefers hot places. When it rains, steam is said to spout from the tip of its tail.",
                    "energy": 0,
                    "max_energy": 100,
                    "visible": True
                }
            },
            "wishlist": [
                "https://u6wdnj9wggobj.vcdn.cloud/media/catalog/product/cache/a237138a07ed0dd2cc8a6fa440635ea6/7/6/76414_copy_0.jpg",
                "https://u6wdnj9wggobj.vcdn.cloud/media/catalog/product/cache/a237138a07ed0dd2cc8a6fa440635ea6/6/0/60302_7_.jpg"
            ]
        }
        save_metadata(metadata)
        return "# 🔥🔥🔥 YOU SKIP 1 DAYYYYYY. EVERYTHING IS BURNTTTTTT. ALL YOUR FRIENDS ARE VANISHINGGGGG 🔥🔥🔥"

    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 awarded {gift_str} 🎁.\n\n \n\n"

        # Update new reward
        metadata = read_metadata()
    
    all_dex = get_all_pokemon_dex()
    while True:
        random_dex = all_dex[random.randint(0, len(all_dex) - 1)]
        if metadata["pokemon"][random_dex]["visible"] == True:
            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 \n\n"

            if can_evolve(random_dex, metadata["pokemon"][random_dex]["energy"]):
                metadata["pokemon"][random_dex]["visible"] = False
                evolve_pokemon = evolve_to(int(random_dex))
                if evolve_pokemon: # if not None, aka get max level
                    evolve_dex = list(evolve_pokemon.keys())[0]
                    metadata["pokemon"].update(evolve_pokemon)
                    reward += f"Your **{metadata['pokemon'][random_dex]['name']}** has just evolved into **{metadata['pokemon'][evolve_dex]['name']}**. Hoorayyyyy!!! 🥳.\n\n \n\n"

            break
    
    metadata["last_streak_day"] = datetime.datetime.today().strftime("%d/%m/%Y")
    save_metadata(metadata)

    is_first_day_of_week = datetime.date.today().weekday() == 0
    if is_first_day_of_week:
        while True: # Random pokemon not in the list
            new_pokemon = random_pokemon()
            dex = list(new_pokemon.keys())[0]
            if str(dex) not in get_all_pokemon_dex():
                break
        add_new_pokemon(new_pokemon)
        reward += f"**{new_pokemon[dex]['name']}** has joined with your family!!!"

    return reward