Mario2 / app.py
Gregniuki's picture
Update app.py
701daab verified
import os
from flask import Flask, send_from_directory
from flask_cors import CORS
import gradio as gr
import threading
import logging
# Set the temporary directory for Gradio to a writable location
os.environ["GRADIO_TEMP_DIR"] = "/tmp"
# Create a Flask app to serve static files
flask_app = Flask(__name__)
CORS(flask_app) # Enable CORS
# Configure logging
logging.basicConfig(level=logging.INFO)
# Serve the Mario game files
@flask_app.route("/mario")
def serve_index():
return send_from_directory("/app/mario", "index.html")
# Serve static files (JavaScript, CSS, assets, etc.)
@flask_app.route("/mario/<path:path>")
def serve_static(path):
return send_from_directory("/app/mario", path)
# Debug route to list files
@flask_app.route("/mario/files")
def list_files():
files = os.listdir("/app/mario")
return {"files": files}
# Run Flask in a separate thread
def run_flask():
try:
logging.info("Starting Flask server...")
flask_app.run(host="0.0.0.0", port=5000)
except Exception as e:
logging.error(f"Failed to start Flask server: {e}")
flask_thread = threading.Thread(target=run_flask)
flask_thread.daemon = True
flask_thread.start()
# Gradio interface to embed the game
def serve_game():
game_url = "http://localhost:5000/mario" # Flask is running on port 5000
return f'<iframe src="{game_url}" width="800" height="600" style="border: none;"></iframe>'
# Create a Gradio interface
iface = gr.Interface(
fn=serve_game, # Function to generate the HTML content
inputs=None, # No inputs needed
outputs=gr.HTML(), # Output is HTML content
live=True, # Keep the interface live
title="Mario HTML Game",
description="Play the Mario HTML game embedded in Gradio!",
allow_flagging="never" # Disable flagging
)
# Launch the Gradio app
try:
logging.info("Starting Gradio interface...")
iface.launch(server_name="0.0.0.0", server_port=7860)
except Exception as e:
logging.error(f"Failed to start Gradio interface: {e}")