Spaces:
Sleeping
Sleeping
Update app.py
Browse files1 unmodified line23456782 unmodified lines11121314151617181 unmodified line2021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687881 unmodified lineimport gymnasium as gymfrom stable_baselines3 import DQNimport imageioimport numpy as npimport timeimport os2 unmodified linesst.set_page_config(page_title="Lunar Lander AI", page_icon="🚀")st.markdown("### 🌕 Lunar Lander AI - Replay Mód 🚀")@st.cache_resourcedef load_model():if os.path.exists("lunar_lander_model.zip"):1 unmodified lineelse:return Nonemodel = load_model()if model is None:st.error("Hiányzik a 'lunar_lander_model.zip'!")else:if st.button("Start / Végtelen ciklus indítása ▶️"):# Helyőrzők létrehozásastatus_text = st.empty()video_placeholder = st.empty()env = gym.make("LunarLander-v3", render_mode="rgb_array")episode_count = 0fps = 30while True:episode_count += 1# 1. Előkészítés# Töröljük az előző videót, hogy ne látszódjon, amíg az újat számoljukvideo_placeholder.empty()status_text.info(f"🔄 {episode_count}. szimuláció számolása a háttérben...")obs, info = env.reset()done = Falsetruncated = Falsetotal_reward = 0frames = []# 2. Szimuláció futtatása (láthatatlanul)while not done and not truncated:action, _states = model.predict(obs, deterministic=True)obs, reward, done, truncated, info = env.step(action)total_reward += rewardframes.append(env.render())# 3. GIF generálásagif_path = "replay.gif"imageio.mimsave(gif_path, frames, fps=fps)# Videó hossza másodpercbenvideo_duration = len(frames) / fps# 4. Videó indítása (Eredmény MÉG NINCS kiírva)status_text.info(f"🎬 {episode_count}. kör visszajátszása...")video_placeholder.image(gif_path, caption=f"{episode_count}. Leszállás")# Várakozás, amíg a felhasználó végignézi a videóttime.sleep(video_duration)# 5. Eredmény felfedése (Csak most!)if total_reward >= 200:msg = f"✅ SIKER! Profi munka. Pontszám: {total_reward:.2f}"st.balloons() # Csak siker esetén jön lufielif total_reward >= 0:msg = f"⚠️ OK. Biztonságos. Pontszám: {total_reward:.2f}"else:msg = f"💥 ZUHANÁS! Pontszám: {total_reward:.2f}"# Kiírjuk az eredménytstatus_text.markdown(f"### {msg}")# 6. Szünet az olvasáshoztime.sleep(2)# Ezután ugrik vissza a ciklus elejére1 unmodified line2345672 unmodified lines1011121314151617181920211 unmodified line23242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251 unmodified lineimport gymnasium as gymfrom stable_baselines3 import DQNimport imageioimport timeimport os2 unmodified linesst.set_page_config(page_title="Lunar Lander AI", page_icon="🚀")# --- FŐ CÍM ---st.title("🌕 Lunar Lander AI")st.markdown("**Deep Q-Network (DQN)** algoritmus demonstrációja.")# --- 1. SZEKCIÓ: AI DEMO (Visszajátszás) ---@st.cache_resourcedef load_model():if os.path.exists("lunar_lander_model.zip"):1 unmodified lineelse:return Nonemodel = load_model()if model is None:st.error("⚠️ Hiányzik a 'lunar_lander_model.zip' fájl!")else:# Konténer a videónakdemo_container = st.container()with demo_container:st.subheader("🤖 Így csinálja a gép:")start_button = st.button("AI Indítása / Végtelen ciklus ▶️")if start_button:# Helyőrzőkstatus_text = st.empty()video_placeholder = st.empty()env = gym.make("LunarLander-v3", render_mode="rgb_array")episode_count = 0fps = 30while True:episode_count += 1# Takarításvideo_placeholder.empty()status_text.info(f"🔄 {episode_count}. szimuláció számolása a háttérben...")obs, info = env.reset()done = Falsetruncated = Falsetotal_reward = 0frames = []# Szimuláció futtatásawhile not done and not truncated:action, _states = model.predict(obs, deterministic=True)obs, reward, done, truncated, info = env.step(action)total_reward += rewardframes.append(env.render())# GIF generálásagif_path = "replay.gif"imageio.mimsave(gif_path, frames, fps=fps)video_duration = len(frames) / fps# Lejátszásstatus_text.info(f"🎬 {episode_count}. kör visszajátszása...")video_placeholder.image(gif_path, caption=f"{episode_count}. Leszállás")# Várakozás amíg a videó tarttime.sleep(video_duration)# Eredmény kiírásaif total_reward >= 200:msg = f"✅ SIKER! Profi munka. Pontszám: {total_reward:.2f}"st.balloons()elif total_reward >= 0:msg = f"⚠️ OK. Biztonságos. Pontszám: {total_reward:.2f}"else:msg = f"💥 ZUHANÁS! Pontszám: {total_reward:.2f}"status_text.markdown(f"### {msg}")time.sleep(2)# --- 2. SZEKCIÓ: EMBERI KIHÍVÁS (LETÖLTÉS) ---st.markdown("---") # Elválasztó vonalst.header("🎮 Te le tudod tenni?")col1, col2 = st.columns([2, 1])with col1:st.write("""Az AI már megtanulta... de vajon neked sikerülne?Töltsd le a játékot, és próbáld ki a saját gépeden az eredeti, nehéz fizikával!**A csomag tartalma:*** 🐍 `lunar_lander.py` (A játék kódja)* ⚙️ `INDITAS.bat` (Automatikus telepítő és indító)""")with col2:# Letöltés gombzip_filename = "lunar_lander_challenge.zip"if os.path.exists(zip_filename):with open(zip_filename, "rb") as fp:st.download_button(label="📥 JÁTÉK LETÖLTÉSE\n(Windows .zip)",data=fp,file_name=zip_filename,mime="application/zip",help="Kattints a letöltéshez, csomagold ki, és indítsd el a .bat fájlt!")else:st.warning("A letölthető fájl (lunar_lander_challenge.zip) még nincs feltöltve.")st.markdown("---")st.caption("Készítette: Gemini & Faragó Csaba | Powered by Stable Baselines3 & Streamlit")
app.py+101-64