| import gradio as gr |
| import json |
| import random |
| import tempfile |
| from datetime import datetime |
| from typing import Dict, Tuple, Optional |
| from PIL import Image |
| import io |
|
|
| from google import genai |
| from google.genai import types |
| import os |
| import gtts |
|
|
| API_KEY = os.environ.get("GOOGLE_API_KEY") |
| client = genai.Client(api_key=API_KEY) |
|
|
| |
| pet_state = { |
| "name": "", |
| "species": "", |
| "personality": "", |
| "appearance": "", |
| "mood": "ๅฟซๆจ", |
| "hunger": 80, |
| "energy": 90, |
| "experience": 0, |
| "level": 1, |
| "interaction_history": [], |
| "battle_stats": {"wins": 0, "losses": 0} |
| } |
|
|
| def generate_pet_description(custom_input: str = "") -> Dict: |
| """Generate pet basic settings using Gemini 2.0 Flash""" |
| try: |
| if custom_input.strip(): |
| prompt = f""" |
| ่ซๆ นๆไฝฟ็จ่
ๆ่ฟฐๅตๅปบไธ้ปๅฏถๅฏๅคข้ขจๆ ผ็ๅฏต็ฉ๏ผ{custom_input} |
| |
| ่ซไปฅ JSON ๆ ผๅผ่ฟๅ๏ผ |
| {{ |
| "name": "ๅฏต็ฉๅ็จฑ", |
| "species": "็ฉ็จฎ้กๅ", |
| "personality": "ๆงๆ ผๆ่ฟฐ", |
| "appearance": "ๅค่ง็นๅพตๆ่ฟฐ" |
| }} |
| """ |
| else: |
| prompt = """ |
| ่ซ้จๆฉๅตๅปบไธ้ปๅฏๆ็ๅฏถๅฏๅคข้ขจๆ ผๅฏต็ฉใ |
| |
| ่ซไปฅ JSON ๆ ผๅผ่ฟๅ๏ผ |
| { |
| "name": "ๅฏต็ฉๅ็จฑ", |
| "species": "็ฉ็จฎ้กๅ", |
| "personality": "ๆงๆ ผๆ่ฟฐ", |
| "appearance": "ๅค่ง็นๅพตๆ่ฟฐ" |
| } |
| |
| ่ฆๆฑ๏ผๅ็จฑ่ฆๅฏๆ๏ผๆงๆ ผ่ฆๆ่ถฃ๏ผๅค่ง่ฆ็ๅๅฝข่ฑกใ |
| """ |
|
|
| response = client.models.generate_content( |
| model="gemini-2.5-flash-preview-04-17", |
| contents=prompt |
| ) |
|
|
| response_text = response.text.strip() |
| if response_text.startswith('```json'): |
| response_text = response_text[7:-3] |
| elif response_text.startswith('```'): |
| response_text = response_text[3:-3] |
|
|
| pet_data = json.loads(response_text) |
| return pet_data |
|
|
| except Exception as e: |
| print(f"Error generating pet description: {e}") |
| return { |
| "name": "็ฎๅกไธ", |
| "species": "้ปๆฐฃ้ผ ๅฏถๅฏๅคข", |
| "personality": "ๆดปๆฝๅฅฝๅ๏ผๅๆญกไบคๆๅ", |
| "appearance": "้ป่ฒๆฏ้ซฎ๏ผ็ด
่ฒ่้ ฐ๏ผ้ท้ทๅฐพๅทด" |
| } |
|
|
| def generate_pet_image(description: str, mood: str = "ๅฟซๆจ", context_desc: str = "") -> Optional[Image.Image]: |
| """Generate pet image using Gemini 2.0 Flash, including context""" |
| try: |
| mood_map = { |
| "ๅฟซๆจ": "happy and cheerful", |
| "้ฃข้ค": "hungry and tired", |
| "่ๅฅฎ": "excited and energetic", |
| "็ฒๆ": "sleepy and tired", |
| "็ๆฐฃ": "angry and upset", |
| "ๆปฟ่ถณ": "satisfied and content" |
| } |
|
|
| mood_desc = mood_map.get(mood, "happy") |
|
|
| full_description = f"{description}" |
| if context_desc: |
| full_description += f", {context_desc}" |
|
|
| image_prompt = f""" |
| ่ซ็นช่ฃฝไธๅผตๅฏๆ็ๅฏถๅฏๅคข้ขจๆ ผๅฏต็ฉๆๅ๏ผ็ดฐ็ฏๅฆไธ๏ผ |
| - ๆ่ฟฐ๏ผ {full_description} |
| - ๆ
็ท๏ผ {mood_desc} |
| - ้ขจๆ ผ๏ผ ่ฒๅฝฉ้ฎฎ่ฑใๅฏๆๅๅ็ๅๆผซ้ขจๆ ผ๏ผๅ็พๅฏต็ฉๅ
จ่บซ |
| - ่ๆฏ๏ผ ็ฐกๅฎใๆๅ็่ฒๅฝฉใๅชๅ
่ๆ
ฎ้ๆ่ๆฏ๏ผ่ฅไธๅฏ่กๅไฝฟ็จ็ฐกๅฎ่ๆฏ |
| - ๅ่ณช๏ผ ้ซ่งฃๆๅบฆใ็ดฐ็ฏ่ฑๅฏ |
| - ้ทๅฏฌๆฏ๏ผๆญฃๆนๅฝข (1:1) |
| - **่ซๅฟ**ๅจๅ็ไธญๅ ๅ
ฅไปปไฝๆๅญใ |
| """ |
|
|
| print(f"Generating image with prompt: {image_prompt}") |
|
|
| image_response = client.models.generate_content( |
| model="gemini-2.0-flash-preview-image-generation", |
| |
| contents=image_prompt, |
| config=types.GenerateContentConfig( |
| response_modalities=['TEXT', 'IMAGE'] |
| ) |
| ) |
|
|
| if image_response and image_response.candidates and image_response.candidates[0].content.parts: |
| for part in image_response.candidates[0].content.parts: |
| if part.inline_data and part.inline_data.mime_type.startswith('image/'): |
| image_data_base64 = part.inline_data.data |
| img = Image.open(io.BytesIO(image_data_base64)) |
|
|
| img = img.resize((512, 512), Image.Resampling.LANCZOS) |
| print("Image generated successfully.") |
| return img |
|
|
| print("Image data not found in any response parts or not an image.") |
| return None |
| else: |
| print("Image generation response is empty or malformed.") |
| return None |
|
|
| except Exception as e: |
| print(f"Error generating pet image: {e}") |
| return None |
|
|
| def generate_tts_audio(text: str, lang: str = "zh-TW") -> Optional[str]: |
| """Generate text-to-speech audio file""" |
| try: |
| tts = gtts.gTTS(text=text, lang=lang, slow=False) |
| temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".mp3") |
| tts.save(temp_file.name) |
| return temp_file.name |
| except Exception as e: |
| print(f"TTS generation failed: {e}") |
| return None |
|
|
| def chat_with_pet(user_message: str) -> Tuple[str, Optional[str], None, Optional[Image.Image]]: |
| """Chat with the pet""" |
| global pet_state |
|
|
| try: |
| if not pet_state["name"]: |
| return "่ซๅ
ๅตๅปบไฝ ็ๅฏต็ฉ๏ผ", None, None, None |
|
|
| context = f""" |
| ไฝ ๆฏไธ้ปๅๅซ {pet_state['name']} ็ {pet_state['species']}๏ผๆๆ {pet_state['personality']} ็็จ็นๅๆงใ |
| ไฝ ็พๅจ็ๅฟๆ
ๆฏ {pet_state['mood']}๏ผๆ่ฆบ {pet_state['hunger']}/100 ้ฃข้ค๏ผ็ฒพๅๅๆ {pet_state['energy']}/100ใ |
| |
| ่ซไฝ ๅฎๅ
จ่ๅ
ฅ้ๅ่ง่ฒ๏ผไปฅๆ็ฌฆๅไฝ ็ถๅ็ๆ
๏ผๅฟๆ
ใ้ฃข้คใ็ฒพๅ๏ผๅๅๆง็ๅฏๆใๅๅๅฃๅป๏ผๅๆไธปไบบๅฐไฝ ่ชช็่ฉฑ๏ผ"{user_message}"ใ |
| |
| ๅๆ่ฆๆฑ๏ผ |
| 1. ไฟๆ่ง่ฒ่จญๅฎไธฆ่ๅ
ฅ็ถๅ็ๆ
(ๅฟๆ
ใ้ฃข้คใ็ฒพๅ)ใ |
| 2. ไปฅๅฏๆใๅๅ็ๅฏต็ฉๅฃๅปๅๆใ |
| 3. ๅๆ้ทๅบฆ็ดๅจ 20 ่ณ 50 ๅญไน้ใ |
| 4. ๅฏไปฅ่กจ้ไฝ ็ๆ
ๆๅ้ๆฑใ |
| 5. ไฝฟ็จ็น้ซไธญๆใ |
| """ |
|
|
| response = client.models.generate_content( |
| model="gemini-2.5-flash-preview-04-17", |
| contents=context |
| ) |
|
|
| pet_response = response.text.strip() |
|
|
| pet_state["interaction_history"].append({ |
| "timestamp": datetime.now().strftime("%H:%M:%S"), |
| "user": user_message, |
| "pet": pet_response, |
| "type": "chat" |
| }) |
|
|
| audio_file = generate_tts_audio(pet_response) |
|
|
| image_description = f"{pet_state['species']} - {pet_state.get('appearance', '')}" if pet_state['appearance'] else pet_state['species'] |
| new_image = generate_pet_image( |
| image_description, |
| pet_state["mood"], |
| context_desc=f"chatting with the user, response: {pet_response}" |
| ) |
|
|
| return pet_response, audio_file, None, new_image |
|
|
| except Exception as e: |
| error_msg = f"Chat function error: {e}" |
| print(error_msg) |
| return "ๅ... ๆ็พๅจ่ชชไธๅบ่ฉฑไพ...", None, None, None |
|
|
| def feed_pet(food_type: str) -> Tuple[str, str, Optional[str], Optional[Image.Image]]: |
| """Feed the pet""" |
| global pet_state |
|
|
| try: |
| if not pet_state["name"]: |
| return "่ซๅ
ๅตๅปบไฝ ็ๅฏต็ฉ๏ผ", "่ซๅ
ๅตๅปบไฝ ็ๅฏต็ฉ๏ผ", None, None |
|
|
| if not food_type: |
| foods = ["ๆจนๆ", "ๅฏถๅฏๅคข้ฃ็ฉ", "่ๆ", "้ค
ไนพ", "็ณๆ"] |
| food_type = random.choice(foods) |
|
|
| hunger_increase = random.randint(15, 25) |
| pet_state["hunger"] = min(100, pet_state["hunger"] + hunger_increase) |
|
|
| if pet_state["hunger"] > 80: |
| pet_state["mood"] = "ๅฟซๆจ" |
| elif pet_state["hunger"] > 50: |
| pet_state["mood"] = "ๆปฟ่ถณ" |
|
|
| context = f""" |
| {pet_state['name']} ๅๅๅไบ {food_type}๏ผ้ฃข้ค็จๅบฆๅพไนๅๆๅๅฐ {pet_state['hunger']}/100ใ |
| ่ซไปฅๅฏต็ฉ็่งๅบฆๆ่ฟฐไบซ็จ้ฃ็ฉ็ๆๅๅๅๆใ |
| |
| ่ฆๆฑ๏ผ |
| 1. 50-80ๅญ็ๅฏๆๅๆ |
| 2. ่กจ้ๅฐ้ฃ็ฉ็ๅๆ |
| 3. ็จ็น้ซไธญๆ |
| 4. ็ฌฆๅ {pet_state['personality']} ็ๆงๆ ผ |
| """ |
|
|
| response = client.models.generate_content( |
| model="gemini-2.5-flash-preview-04-17", |
| contents=context |
| ) |
|
|
| pet_response = response.text.strip() |
|
|
| pet_state["interaction_history"].append({ |
| "timestamp": datetime.now().strftime("%H:%M:%S"), |
| "action": f"้คต้ฃ {food_type}", |
| "result": pet_response, |
| "type": "feed" |
| }) |
|
|
| image_description = f"{pet_state['species']} - {pet_state.get('appearance', '')}" if pet_state['appearance'] else pet_state['species'] |
| new_image = generate_pet_image( |
| image_description, |
| pet_state["mood"], |
| context_desc=f"eating {food_type}, reaction: {pet_response}" |
| ) |
|
|
| status_update = f"็ญ็ด: {pet_state['level']} | ้ฃข้ค: {pet_state['hunger']}/100 | ็ฒพๅ: {pet_state['energy']}/100 | ๅฟๆ
: {pet_state['mood']}" |
|
|
| audio_file = generate_tts_audio(pet_response) |
|
|
| return pet_response, status_update, audio_file, new_image |
|
|
| except Exception as e: |
| error_msg = f"Feed function error: {e}" |
| print(error_msg) |
| status_update = f"็ญ็ด: {pet_state['level']} | ้ฃข้ค: {pet_state['hunger']}/100 | ็ฒพๅ: {pet_state['energy']}/100 | ๅฟๆ
: {pet_state['mood']}" |
| return f"ๅ... ้คต้ฃๆๅบไบ้ปๅ้กใ({error_msg})", status_update, None, None |
|
|
| def adventure_with_pet() -> Tuple[str, str, Optional[str], Optional[Image.Image]]: |
| """Go on an adventure with the pet""" |
| global pet_state |
|
|
| try: |
| if not pet_state["name"]: |
| return "่ซๅ
ๅตๅปบไฝ ็ๅฏต็ฉ๏ผ", "่ซๅ
ๅตๅปบไฝ ็ๅฏต็ฉ๏ผ", None, None |
|
|
| energy_cost = random.randint(10, 20) |
| pet_state["energy"] = max(0, pet_state["energy"] - energy_cost) |
|
|
| exp_gain = random.randint(5, 15) |
| pet_state["experience"] += exp_gain |
|
|
| level_up_msg = "" |
| while pet_state["experience"] >= pet_state["level"] * 100: |
| pet_state["experience"] -= pet_state["level"] * 100 |
| pet_state["level"] += 1 |
| level_up_msg += f"ๆญๅ๏ผ{pet_state['name']} ๅๅฐไบ {pet_state['level']} ็ด๏ผ\n" |
| level_up_msg = level_up_msg.strip() |
|
|
| context = f""" |
| {pet_state['name']} ๆญฃๅจ้ฒ่กไธๆฌกๆข้ชๅ้ชใ่ซๅต้ ไธๅๆ่ถฃ็ๆข้ชๅ ดๆฏ๏ผ |
| |
| ๅฏต็ฉ่ณ่จ๏ผ |
| - ็จฎๆ๏ผ{pet_state['species']} |
| - ๆงๆ ผ๏ผ{pet_state['personality']} |
| - ็ญ็ด๏ผ{pet_state['level']} |
| - ็ฎๅ็ฒพๅ๏ผ{pet_state['energy']}/100 |
| |
| ่ซๆ่ฟฐไธๅ็ญๅฐ็ฒพๅฝฉ็ๆข้ชๆ
ไบ๏ผ80-100ๅญ๏ผ๏ผๅ
ๅซ๏ผ |
| 1. ๆข้ชๅ ดๆฏ |
| 2. ้ๅฐ็ไบไปถๆ็ผ็พ |
| 3. ๅฏต็ฉ็ๅๆๅๆถ็ฒ |
| 4. ็จ็น้ซไธญๆๆฐๅฏซ |
| """ |
|
|
| response = client.models.generate_content( |
| model="gemini-2.5-flash-preview-04-17", |
| contents=context |
| ) |
|
|
| adventure_story = response.text.strip() |
|
|
| image_description = f"{pet_state['species']} - {pet_state.get('appearance', '')}" if pet_state['appearance'] else pet_state['species'] |
| new_image = generate_pet_image( |
| image_description, |
| pet_state["mood"], |
| context_desc=f"on an adventure: {adventure_story}" |
| ) |
|
|
| if level_up_msg: |
| adventure_story += f"\n\n๐ {level_up_msg}" |
| adventure_story += f"\n\n๐ ็ฒๅพ็ถ้ฉๅผ: +{exp_gain}" |
|
|
| record_result = adventure_story |
| pet_state["interaction_history"].append({ |
| "timestamp": datetime.now().strftime("%H:%M:%S"), |
| "action": "ๆข้ช", |
| "result": record_result, |
| "type": "adventure", |
| "exp_gained": exp_gain |
| }) |
|
|
| if pet_state["energy"] > 60: |
| pet_state["mood"] = "่ๅฅฎ" |
| elif pet_state["energy"] > 30: |
| pet_state["mood"] = "ๆปฟ่ถณ" |
| else: |
| pet_state["mood"] = "็ฒๆ" |
|
|
| audio_file = generate_tts_audio(adventure_story) |
|
|
| status_update = f"็ญ็ด: {pet_state['level']} | ็ถ้ฉ: {pet_state['experience']}/{pet_state['level']*100} | ็ฒพๅ: {pet_state['energy']}/100 | ๅฟๆ
: {pet_state['mood']}" |
|
|
| return adventure_story, status_update, audio_file, new_image |
|
|
| except Exception as e: |
| error_msg = f"Adventure function error: {e}" |
| print(error_msg) |
| status_update = f"็ญ็ด: {pet_state['level']} | ็ถ้ฉ: {pet_state['experience']}/{pet_state['level']*100} | ็ฒพๅ: {pet_state['energy']}/100 | ๅฟๆ
: {pet_state['mood']}" |
| return "ๅ... ๆข้ชๆๅบไบ้ปๅ้กใ", status_update, None, None |
|
|
| def battle_with_pet() -> Tuple[str, str, Optional[str], Optional[Image.Image]]: |
| """Battle with the pet""" |
| global pet_state |
|
|
| try: |
| if not pet_state["name"]: |
| return "่ซๅ
ๅตๅปบไฝ ็ๅฏต็ฉ๏ผ", "่ซๅ
ๅตๅปบไฝ ็ๅฏต็ฉ๏ผ", None, None |
|
|
| opponents = ["้็็ฎๅกไธ", "ๅฐ็ซ้พ", "ๅๅฐผ้พ", "ๅฆ่็จฎๅญ", "ๅฐๆ้", "ๆณขๆณข"] |
| opponent = random.choice(opponents) |
|
|
| pet_power = pet_state["level"] * 10 + random.randint(1, 20) |
| opponent_power = random.randint(10, 50) |
|
|
| win = pet_power > opponent_power |
|
|
| if win: |
| pet_state["battle_stats"]["wins"] += 1 |
| result = "ๅๅฉ" |
| exp_gain = random.randint(10, 20) |
| pet_state["experience"] += exp_gain |
| pet_state["mood"] = "่ๅฅฎ" |
| else: |
| pet_state["battle_stats"]["losses"] += 1 |
| result = "ๅคฑๆ" |
| exp_gain = random.randint(3, 8) |
| pet_state["experience"] += exp_gain |
| pet_state["mood"] = "็ฒๆ" |
|
|
| level_up_msg = "" |
| while pet_state["experience"] >= pet_state["level"] * 100: |
| pet_state["experience"] -= pet_state["level"] * 100 |
| pet_state["level"] += 1 |
| level_up_msg += f"ๆญๅ๏ผ{pet_state['name']} ๅๅฐไบ {pet_state['level']} ็ด๏ผ\n" |
| level_up_msg = level_up_msg.strip() |
|
|
| energy_cost = random.randint(15, 25) |
| pet_state["energy"] = max(0, pet_state["energy"] - energy_cost) |
|
|
| context = f""" |
| {pet_state['name']} ๅๅๅ {opponent} ้ฒ่กไบไธๅ ดๅฐๆฐ๏ผ็ตๆๆฏ{result}ใ |
| |
| ่ซๆ่ฟฐ้ๅ ดๆฐ้ฌฅ็้็จๅ็ตๆ๏ผ80-120ๅญ๏ผ๏ผ |
| 1. ๆฐ้ฌฅๅ ด้ขๆ่ฟฐ |
| 2. ไฝฟ็จ็ๆๅผ (ๅฏถๅฏๅคข้ขจๆ ผ) |
| 3. ๆฐ้ฌฅ็ตๆ |
| 4. {pet_state['name']} ็ๅๆ |
| 5. ็จ็น้ซไธญๆๆฐๅฏซ |
| 6. ็ฌฆๅ {pet_state['personality']} ็ๆงๆ ผ |
| """ |
|
|
| response = client.models.generate_content( |
| model="gemini-2.5-flash-preview-04-17", |
| contents=context |
| ) |
|
|
| battle_story = response.text.strip() |
|
|
| image_description = f"{pet_state['species']} - {pet_state.get('appearance', '')}" if pet_state['appearance'] else pet_state['species'] |
| new_image = generate_pet_image( |
| image_description, |
| pet_state["mood"], |
| context_desc=f"in a battle against {opponent}, based on the story: {battle_story}" |
| ) |
|
|
| battle_story += f"\n\n๐ ็ฒๅพ็ถ้ฉๅผ: +{exp_gain}" |
| if level_up_msg: |
| battle_story += f"\n\n๐ {level_up_msg}" |
|
|
| record_result = f"{result} - {battle_story}" |
| pet_state["interaction_history"].append({ |
| "timestamp": datetime.now().strftime("%H:%M:%S"), |
| "action": f"ๅฐๆฐ vs {opponent}", |
| "result": record_result, |
| "type": "battle" |
| }) |
|
|
| audio_file = generate_tts_audio(battle_story) |
|
|
| status_update = f"็ญ็ด: {pet_state['level']} | ็ถ้ฉ: {pet_state['experience']}/{pet_state['level']*100} | ๅๅ ด: {pet_state['battle_stats']['wins']} | ๆๅ ด: {pet_state['battle_stats']['losses']} | ็ฒพๅ: {pet_state['energy']}/100 | ๅฟๆ
: {pet_state['mood']}" |
|
|
| return battle_story, status_update, audio_file, new_image |
|
|
| except Exception as e: |
| error_msg = f"Battle function error: {e}" |
| print(error_msg) |
| status_update = f"็ญ็ด: {pet_state['level']} | ็ถ้ฉ: {pet_state['experience']}/{pet_state['level']*100} | ๅๅ ด: {pet_state['battle_stats']['wins']} | ๆๅ ด: {pet_state['battle_stats']['losses']} | ็ฒพๅ: {pet_state['energy']}/100 | ๅฟๆ
: {pet_state['mood']}" |
| return f"ๅ... ๅฐๆฐๆๅบไบ้ปๅ้กใ", status_update, None, None |
|
|
| def initialize_pet(custom_input: str) -> Tuple[Optional[Image.Image], str, str, str, Optional[str]]: |
| """Initialize the pet""" |
| global pet_state |
|
|
| pet_data = generate_pet_description(custom_input) |
|
|
| pet_state.update({ |
| "name": pet_data.get("name", "ๆช็ฅๅฏต็ฉ"), |
| "species": pet_data.get("species", "ๆช็ฅ็ฉ็จฎ"), |
| "personality": pet_data.get("personality", "ๆบซๅ"), |
| "appearance": pet_data.get("appearance", ""), |
| "mood": "ๅฟซๆจ", |
| "hunger": 80, |
| "energy": 90, |
| "experience": 0, |
| "level": 1, |
| "interaction_history": [], |
| "battle_stats": {"wins": 0, "losses": 0} |
| }) |
|
|
| image_description = f"{pet_state['species']} - {pet_state['appearance']}" if pet_state['appearance'] else pet_state['species'] |
| pet_image = generate_pet_image(image_description, pet_state["mood"]) |
|
|
| welcome_msg = f"๐ ๆญก่ฟไพๅฐๅฏถๅฏๅคขไธ็๏ผ\n\n" \ |
| f"โจ ๅ็จฑ๏ผ{pet_state['name']}\n" \ |
| f"๐พ ็จฎๆ๏ผ{pet_state['species']}\n" \ |
| f"๐ญ ๆงๆ ผ๏ผ{pet_state['personality']}\n" \ |
| f"๐ ๅฟๆ
๏ผ{pet_state['mood']}\n\n" \ |
| f"็พๅจไฝ ๅฏไปฅๅ {pet_state['name']} ไบๅไบ๏ผ" |
|
|
| status_info = f"็ญ็ด: {pet_state['level']} | ้ฃข้ค: {pet_state['hunger']}/100 | ็ฒพๅ: {pet_state['energy']}/100 | ๅฟๆ
: {pet_state['mood']}" |
|
|
| audio_file = generate_tts_audio(f"ไฝ ๅฅฝ๏ผๆๆฏ{pet_state['name']}๏ผๅพ้ซ่่ช่ญไฝ ๏ผ") |
|
|
| return pet_image, welcome_msg, status_info, "", audio_file |
|
|
| def get_interaction_history() -> str: |
| """Get interaction history""" |
| if not pet_state["interaction_history"]: |
| return "้ๆฒๆไบๅ่จ้ๅข๏ผๅฟซๅไฝ ็ๅฏต็ฉไบๅๅง๏ผ" |
|
|
| history_text = f"๐ {pet_state['name']} ็ไบๅๆฅ่ช\n" + "="*50 + "\n\n" |
|
|
| for record in pet_state["interaction_history"][-20:]: |
| time_stamp = record["timestamp"] |
| if record["type"] == "chat": |
| history_text += f"๐ {time_stamp} [่ๅคฉ]\n" |
| history_text += f"๐ค ไฝ : {record['user']}\n" |
| history_text += f"๐พ {pet_state['name']}: {record['pet']}\n\n" |
| else: |
| action_desc = record.get('action', record['type']) |
| result_desc = record.get('result', '็ก็ตๆๆ่ฟฐ') |
| history_text += f"๐ {time_stamp} [{action_desc}]\n" |
| history_text += f"๐ {result_desc}\n\n" |
|
|
| return history_text |
|
|
| def create_app(): |
| """Create the Gradio application""" |
|
|
| with gr.Blocks( |
| title="Virtual Pokemon Companion", |
| theme=gr.themes.Soft(), |
| css=""" |
| .main-container { max-width: 1200px; margin: 0 auto; } |
| .pet-image { border-radius: 15px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); object-fit: contain; } |
| .status-box { background: linear-gradient(45deg, #ff9a9e, #fecfef); padding: 15px; border-radius: 10px; } |
| .interaction-box { background: linear-gradient(45deg, #a8edea, #fed6e3); padding: 15px; border-radius: 10px; } |
| """) as app: |
|
|
| gr.Markdown(""" |
| # ๐ Virtual Pokemon Companion |
| ### An AI-powered pet system using Google Gemini |
| """) |
|
|
| with gr.Row(): |
| with gr.Column(scale=1): |
| gr.Markdown("## ๐พ Your Pet") |
|
|
| pet_image = gr.Image( |
| label="Pet Image", |
| height=300, |
| show_label=False, |
| elem_classes=["pet-image"], |
| interactive=False |
| ) |
|
|
| pet_status = gr.Textbox( |
| label="Pet Status", |
| value="Please create your pet first!", |
| interactive=False, |
| lines=3, |
| elem_classes=["status-box"] |
| ) |
|
|
| gr.Markdown("### ๐ฎ Create Pet") |
| custom_pet_input = gr.Textbox( |
| label="Custom Pet Traits (Optional)", |
| placeholder="e.g., A flying blue dragon with a gentle personality..." |
| ) |
|
|
| with gr.Row(): |
| create_random_btn = gr.Button("๐ฒ Randomize", variant="primary") |
| create_custom_btn = gr.Button("โจ Create Custom", variant="secondary") |
|
|
| with gr.Column(scale=1): |
| gr.Markdown("## ๐ฌ Interaction Area") |
|
|
| chat_output = gr.Textbox( |
| label="Pet Response", |
| value="Your pet is waiting to be created...", |
| interactive=False, |
| lines=4, |
| elem_classes=["interaction-box"] |
| ) |
|
|
| audio_output = gr.Audio( |
| label="Pet Voice", |
| visible=True, |
| autoplay=True |
| ) |
|
|
| gr.Markdown("### ๐ญ Chat") |
| chat_input = gr.Textbox( |
| label="Talk to your pet", |
| placeholder="Enter your message here..." |
| ) |
| chat_btn = gr.Button("๐ฌ Chat", variant="primary") |
|
|
| gr.Markdown("### ๐ฏ Activities") |
| with gr.Row(): |
| feed_btn = gr.Button("๐ Feed", variant="secondary") |
| adventure_btn = gr.Button("๐บ๏ธ Adventure", variant="secondary") |
|
|
| with gr.Row(): |
| battle_btn = gr.Button("โ๏ธ Battle", variant="secondary") |
| history_btn = gr.Button("๐ View Log", variant="secondary") |
|
|
| with gr.Row(): |
| history_output = gr.Textbox( |
| label="๐ Interaction Log", |
| lines=8, |
| interactive=False, |
| visible=False, |
| max_lines=20 |
| ) |
|
|
| |
| create_random_btn.click( |
| fn=lambda: initialize_pet(""), |
| outputs=[pet_image, chat_output, pet_status, custom_pet_input, audio_output] |
| ) |
|
|
| create_custom_btn.click( |
| fn=initialize_pet, |
| inputs=[custom_pet_input], |
| outputs=[pet_image, chat_output, pet_status, custom_pet_input, audio_output] |
| ) |
|
|
| chat_btn.click( |
| fn=chat_with_pet, |
| inputs=[chat_input], |
| outputs=[chat_output, audio_output, chat_input, pet_image] |
| ) |
|
|
| chat_input.submit( |
| fn=chat_with_pet, |
| inputs=[chat_input], |
| outputs=[chat_output, audio_output, chat_input, pet_image] |
| ) |
|
|
| feed_btn.click( |
| fn=lambda: feed_pet(""), |
| outputs=[chat_output, pet_status, audio_output, pet_image] |
| ) |
|
|
| adventure_btn.click( |
| fn=adventure_with_pet, |
| outputs=[chat_output, pet_status, audio_output, pet_image] |
| ) |
|
|
| battle_btn.click( |
| fn=battle_with_pet, |
| outputs=[chat_output, pet_status, audio_output, pet_image] |
| ) |
|
|
| def toggle_history(): |
| current_visibility = history_output.visible |
| new_visibility = not current_visibility |
| history_content = get_interaction_history() if new_visibility else "" |
| return gr.update(visible=new_visibility), history_content |
|
|
| history_btn.click( |
| fn=toggle_history, |
| outputs=[history_output, history_output] |
| ) |
|
|
| return app |
|
|
| app = create_app() |
|
|
| app.launch() |