Spaces:
Sleeping
Sleeping
Update app.py
Browse files5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211225 unmodified linesimport osimport base64# TensorFlow figyelmeztetések elrejtéseos.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'st.set_page_config(page_title="Lunar Lander AI", page_icon="🚀", layout="wide")# --- SEGÉDFÜGGVÉNY: HTML LETÖLTÉS (Hogy ne akadjon be a loop miatt) ---def get_binary_file_downloader_html(bin_file, file_label='File'):with open(bin_file, 'rb') as f:data = f.read()bin_str = base64.b64encode(data).decode()href = f'<a href="data:application/octet-stream;base64,{bin_str}" download="{os.path.basename(bin_file)}" style="text-decoration: none;">'href += f'<button style="background-color: #4CAF50; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; border-radius: 12px;">📥 {file_label} LETÖLTÉSE</button>'href += '</a>'return href# --- FŐ CÍM ---st.title("🌕 Lunar Lander AI")st.markdown("**Deep Q-Network (DQN)** algoritmus demonstrációja.")# --- OLDALSÁV (MODOLL BETÖLTÉS) ---@st.cache_resourcedef load_model():if os.path.exists("lunar_lander_model.zip"):return DQN.load("lunar_lander_model")else:return Nonemodel = load_model()# --- FŐHASÁBOK ---col_game, col_download = st.columns([2, 1])# --- JOBB OLDAL: LETÖLTÉS (MINDIG LÁTHATÓ ÉS MŰKÖDIK) ---with col_download:st.info("🎮 **Próbáld ki te is!**")st.write("Az AI már megtanulta... de vajon neked sikerülne? Töltsd le a játékot a saját gépedre!")zip_filename = "lunar_lander_challenge.zip"if os.path.exists(zip_filename):# HTML Linket használunk a gomb helyett, így a loop nem blokkolja!download_html = get_binary_file_downloader_html(zip_filename, "JÁTÉK CSOMAG")st.markdown(download_html, unsafe_allow_html=True)st.caption("Windows .zip | Tartalmazza: Python kód + Automata indító")else:st.warning("A letölthető fájl feltöltés alatt...")# --- BAL OLDAL: AI DEMO ---with col_game:if model is None:st.error("⚠️ Hiányzik a 'lunar_lander_model.zip'!")else:st.subheader("🤖 AI Visszajátszás")# Helyőrzők a UI elemeknekstart_button_placeholder = st.empty()status_text = st.empty()video_placeholder = st.empty()# A gomb a placeholderben jön létrestart_clicked = start_button_placeholder.button("▶️ Szimuláció Indítása", type="primary")if start_clicked:# 1. ELTÜNTETJÜK A GOMBOTstart_button_placeholder.empty()# Inicializálásenv = gym.make("LunarLander-v3", render_mode="rgb_array")episode_count = 0fps = 30# VÉGTELEN CIKLUSwhile True:episode_count += 1# Takarítás az új kör előttvideo_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ó ("láthatatlanul" és gyorsan)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())# GIF generálásagif_path = "replay.gif"imageio.mimsave(gif_path, frames, fps=fps)video_duration = len(frames) / fps# Lejátszásstatus_text.success(f"🎬 {episode_count}. kör visszajátszása...")video_placeholder.image(gif_path, caption=f"{episode_count}. Leszállás")# Várakozástime.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)5 unmodified lines67891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641655 unmodified linesimport osimport base64# --- KONFIGURÁCIÓ ---# TensorFlow üzenetek elnyomásaos.environ['TF_ENABLE_ONEDNN_OPTS'] = '0'st.set_page_config(page_title="Lunar Lander AI", page_icon="🚀", layout="wide")# --- SEGÉDFÜGGVÉNY: HTML LETÖLTÉS ---# (Ez elengedhetetlen, mert a végtelen ciklus miatt a sima Streamlit gomb nem működne)def get_binary_file_downloader_html(bin_file, file_label='File'):try:with open(bin_file, 'rb') as f:data = f.read()bin_str = base64.b64encode(data).decode()# Stílusos gomb CSS-elhref = f'''<a href="data:application/octet-stream;base64,{bin_str}" download="{os.path.basename(bin_file)}" style="text-decoration: none;"><div style="background-color: #4CAF50;color: white;padding: 15px 20px;text-align: center;border-radius: 8px;font-family: sans-serif;font-weight: bold;box-shadow: 0 4px 6px rgba(0,0,0,0.1);transition: 0.3s;margin-top: 10px;display: flex; align-items: center; justify-content: center; gap: 10px;">📥 {file_label} LETÖLTÉSE</div></a>'''return hrefexcept FileNotFoundError:return None# --- MODEL BETÖLTÉS (Cache-elve) ---@st.cache_resourcedef load_model():path = "lunar_lander_model.zip"if os.path.exists(path):return DQN.load("lunar_lander_model")return None# --- UI FELÉPÍTÉSE ---st.title("🌕 Lunar Lander AI")st.markdown("**Deep Q-Network (DQN)** algoritmus demonstrációja.")# Két oszlop létrehozása a legelejéncol_game, col_download = st.columns([2, 1])# ==========================================# 1. JOBB OLDAL: STATIKUS TARTALOM (FIX)# ==========================================with col_download:# Ezt a blokkot a Streamlit egyszer rendereli le, és békén hagyjacontainer = st.container(border=True)with container:st.info("🎮 **Próbáld ki te is!**")st.write("Az AI már megtanulta... de vajon neked sikerülne? Töltsd le a játékot a saját gépedre!")zip_filename = "lunar_lander_challenge.zip"# HTML gomb generálásadownload_btn_html = get_binary_file_downloader_html(zip_filename, "JÁTÉK CSOMAG")if download_btn_html:st.markdown(download_btn_html, unsafe_allow_html=True)st.caption("Windows .zip | Tartalmazza: Python kód + Automata indító")else:st.warning("⚠️ A játékcsomag (zip) jelenleg nem érhető el.")# ==========================================# 2. BAL OLDAL: DINAMIKUS TARTALOM (LOOP)# ==========================================with col_game:model = load_model()if model is None:st.error("⚠️ Hiányzik a 'lunar_lander_model.zip' fájl! Kérlek töltsd fel.")else:st.subheader("🤖 AI Visszajátszás")# Helyőrző a vezérlőknek (hogy el tudjuk tüntetni a gombot)controls_placeholder = st.empty()start_clicked = controls_placeholder.button("▶️ Szimuláció Indítása", type="primary")# Helyőrzők a játék kimenetének (KÍVÜL a cikluson definiáljuk)status_placeholder = st.empty()video_placeholder = st.empty()if start_clicked:# Eltüntetjük a gombot, hogy tisztább legyen a felületcontrols_placeholder.empty()# Környezet inicializálásaenv = gym.make("LunarLander-v3", render_mode="rgb_array")episode_count = 0# --- VÉGTELEN CIKLUS ---while True:episode_count += 1# Állapot frissítésestatus_placeholder.info(f"🔄 **{episode_count}. szimuláció** számolása a háttérben...")video_placeholder.empty() # Előző videó törléseobs, info = env.reset()done = Falsetruncated = Falsetotal_reward = 0frames = []# Szimuláció futtatása (modell predikció)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())# GIF mentésegif_path = "replay.gif"# Optimalizálás: loop=0 végtelen ismétléshez, de itt egyszer játsszuk le a UI miattimageio.mimsave(gif_path, frames, fps=30)# Lejátszás idejevideo_duration = len(frames) / 30# Eredmény kiértékeléseif total_reward >= 200:status_msg = f"✅ **SIKER!** (Pontszám: {total_reward:.1f})"status_type = "success"elif total_reward >= 0:status_msg = f"⚠️ **Biztonságos.** (Pontszám: {total_reward:.1f})"status_type = "warning"else:status_msg = f"💥 **ZUHANÁS!** (Pontszám: {total_reward:.1f})"status_type = "error"# UI Frissítése a lejátszáshozif status_type == "success":status_placeholder.success(f"🎬 {episode_count}. kör: {status_msg}")# Csak ritkán lufizzon, ne minden körben, mert zavaró lehetif episode_count % 5 == 0:st.balloons()elif status_type == "warning":status_placeholder.warning(f"🎬 {episode_count}. kör: {status_msg}")else:status_placeholder.error(f"🎬 {episode_count}. kör: {status_msg}")video_placeholder.image(gif_path, caption=f"AI Leszállás - {episode_count}. próba")# Várakozás, amíg a videó "lefut" a felhasználónaktime.sleep(video_duration + 0.5)# Kis szünet az újragenerálás előtttime.sleep(1)
app.py+114-71