sudo-soldier commited on
Commit
bfca1dd
·
verified ·
1 Parent(s): 5fb9d35

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +39 -107
app.py CHANGED
@@ -2,97 +2,54 @@ import gradio as gr
2
  import os
3
  import zipfile
4
  from pathlib import Path
 
5
  import urllib.parse
6
 
7
  # Define paths
8
  ZIP_FILE = "nes.zip"
9
- EXTRACTED_FOLDER = "nes" # Directory to serve extracted ROMs
 
10
 
11
- # Ensure extraction directory exists
12
- os.makedirs(EXTRACTED_FOLDER, exist_ok=True)
13
 
14
  def extract_roms():
15
  """
16
- Extract ROM files from a zip archive into an extracted folder.
17
-
18
- Raises:
19
- FileNotFoundError: If the zip file is missing or not found in the current directory.
20
- PermissionError: When attempting to write data somewhere without sufficient permissions.
21
-
22
- Returns:
23
- list: A list of paths for extracted ROMs.
24
  """
25
  try:
26
  if os.path.exists(ZIP_FILE):
27
  with zipfile.ZipFile(ZIP_FILE, 'r') as zip_ref:
28
- for file in zip_ref.namelist():
29
- # Ignore special files that do not contain actual data
30
- if not file.startswith("__MACOSX/"):
31
- zip_ref.extract(file, EXTRACTED_FOLDER)
32
- extracted_path = os.path.join(EXTRACTED_FOLDER, file)
33
- print(f"Extracted: {extracted_path}")
 
 
 
 
 
34
  else:
35
- raise FileNotFoundError("Error: `nes.zip` is missing. Please upload it to the root directory.")
36
-
37
  except PermissionError as e:
38
- # Handle permission errors gracefully
39
- print(f"Permission error encountered while extracting ROMs - {e}")
40
-
41
- return [str(extracted_path) for extracted_path in os.listdir(EXTRACTED_FOLDER)]
42
-
43
- def list_roms():
44
- """
45
- List all available ROM files and construct a dropdown menu with the file paths.
46
-
47
- Returns:
48
- list: A list of paths to extracted ROMs, which are used as options for Gradio's dropdown input.
49
-
50
- Raises:
51
- FileNotFoundError: If the directory containing extracted files does not exist or if `nes.zip` is missing.
52
- """
53
- try:
54
- # Check that a directory exists where our data will be stored and download from 'nes' zip archive
55
- rom_files = extract_roms()
56
-
57
- except FileNotFoundError as e:
58
- print(f"Error: ROM folder has been removed. The program should not continue with this action - {e}")
59
-
60
- return [str(rom) for rom in rom_files]
61
-
62
- # Function to extract nested zip files (ROM zips)
63
- def extract_nested_zip(nested_zip_path):
64
- with zipfile.ZipFile(nested_zip_path, 'r') as nested_zip:
65
- nested_folder = os.path.splitext(nested_zip_path)[0]
66
- os.makedirs(nested_folder, exist_ok=True)
67
- nested_zip.extractall(nested_folder)
68
- os.remove(nested_zip_path)
69
- print(f"Extracted nested zip: {nested_zip_path}")
70
-
71
- # Ensure ROMs are extracted on startup
72
- extract_roms()
73
 
74
  # Function to list available ROMs
75
  def list_roms():
76
- if not os.path.exists(EXTRACTED_FOLDER):
77
- print("ROM folder missing.")
78
  return []
 
 
 
 
79
 
80
- # Debugging output: List all files in the directory
81
- print("Listing all files in extracted folder:")
82
- for root, dirs, files in os.walk(EXTRACTED_FOLDER):
83
- for file in files:
84
- print(f"Found file: {file}")
85
-
86
- # Look for .nes files in all directories
87
- roms = [f for f in Path(EXTRACTED_FOLDER).rglob("*.nes")]
88
- print("Found ROMs:", roms) # Debugging output
89
- return [str(rom.relative_to(EXTRACTED_FOLDER)) for rom in roms]
90
-
91
- # Function to generate HTML for playing the selected ROM
92
  def generate_rom_page(rom_name):
93
- rom_path = os.path.join(EXTRACTED_FOLDER, rom_name)
94
- rom_url = urllib.parse.quote(rom_path.replace("\\", "/"))
95
-
96
  html_content = f"""
97
  <html>
98
  <head>
@@ -104,27 +61,7 @@ def generate_rom_page(rom_name):
104
  EJS_core = "nes";
105
  EJS_color = "#0064ff";
106
  EJS_pathtodata = "https://cdn.emulatorjs.org/stable/data/";
107
- EJS_gameUrl = "/{rom_url}"; // Serve directly from local folder
108
- </script>
109
- <script src="https://cdn.emulatorjs.org/stable/data/loader.js"></script>
110
- </head>
111
- <body>
112
- </body>
113
- </html>
114
- """
115
- return html_content
116
-
117
- <html>
118
- <head>
119
- <div style='width:640px;height:480px;max-width:100%'>
120
- <div id='game'></div>
121
- </div>
122
- <script>
123
- EJS_player = "#game";
124
- EJS_core = "nes";
125
- EJS_color = "#0064ff";
126
- EJS_pathtodata = "https://cdn.emulatorjs.org/stable/data/";
127
- EJS_gameUrl = "https://sudo-soldier-nes.hf.space/RETRO/{rom_url}"; // Correct ROM URL
128
  </script>
129
  <script src="https://cdn.emulatorjs.org/stable/data/loader.js"></script>
130
  </head>
@@ -137,28 +74,23 @@ def generate_rom_page(rom_name):
137
  # Gradio App
138
  def gradio_app():
139
  with gr.Blocks(css=".gradio-dropdown { max-height: 400px; overflow-y: auto; }") as app:
140
- gr.Markdown("# 🎮 Retro ROM File Server")
141
 
142
- # List available ROMs and create a button for each
143
  rom_files = list_roms()
144
 
145
- # Display the available ROM files
146
  with gr.Column():
147
- # Create dropdown with a custom CSS class
148
- rom_buttons = gr.Dropdown(choices=rom_files, label="Select a ROM to Play", interactive=True, elem_id="rom-dropdown")
149
-
150
- output_html = gr.HTML(value="Please select a ROM to play.")
151
-
152
- # When a ROM is selected from the dropdown, update the HTML display with the ROM content
153
- rom_buttons.change(fn=generate_rom_page, inputs=rom_buttons, outputs=output_html)
154
 
155
- # Apply the content directly to the HTML
156
- output_html.value = output_html.value
157
 
158
- app.launch(server_name="0.0.0.0", server_port=7860, share=True)
 
 
 
159
 
160
- # Run Gradio app
161
- gradio_app()
162
 
163
 
164
 
 
2
  import os
3
  import zipfile
4
  from pathlib import Path
5
+ import shutil
6
  import urllib.parse
7
 
8
  # Define paths
9
  ZIP_FILE = "nes.zip"
10
+ EXTRACTED_FOLDER = "extracted_nes"
11
+ PUBLIC_FOLDER = "public/roms" # <-- Important!
12
 
13
+ # Ensure public ROM folder exists
14
+ os.makedirs(PUBLIC_FOLDER, exist_ok=True)
15
 
16
  def extract_roms():
17
  """
18
+ Extract ROM files from the uploaded zip and move them into public/roms/ folder.
 
 
 
 
 
 
 
19
  """
20
  try:
21
  if os.path.exists(ZIP_FILE):
22
  with zipfile.ZipFile(ZIP_FILE, 'r') as zip_ref:
23
+ zip_ref.extractall(EXTRACTED_FOLDER)
24
+ print(f"Extracted into {EXTRACTED_FOLDER}")
25
+
26
+ # Move all .nes files into public/roms/
27
+ for root, dirs, files in os.walk(EXTRACTED_FOLDER):
28
+ for file in files:
29
+ if file.lower().endswith(".nes"):
30
+ source_path = os.path.join(root, file)
31
+ target_path = os.path.join(PUBLIC_FOLDER, file)
32
+ shutil.move(source_path, target_path)
33
+ print(f"Moved ROM: {file} -> {target_path}")
34
  else:
35
+ raise FileNotFoundError("`nes.zip` not found. Please upload it.")
 
36
  except PermissionError as e:
37
+ print(f"Permission error: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
  # Function to list available ROMs
40
  def list_roms():
41
+ if not os.path.exists(PUBLIC_FOLDER):
42
+ print("No ROMs found.")
43
  return []
44
+
45
+ roms = [f for f in os.listdir(PUBLIC_FOLDER) if f.endswith(".nes")]
46
+ print("Available ROMs:", roms)
47
+ return roms
48
 
49
+ # Function to generate EmulatorJS HTML
 
 
 
 
 
 
 
 
 
 
 
50
  def generate_rom_page(rom_name):
51
+ rom_url = f"/roms/{urllib.parse.quote(rom_name)}"
52
+
 
53
  html_content = f"""
54
  <html>
55
  <head>
 
61
  EJS_core = "nes";
62
  EJS_color = "#0064ff";
63
  EJS_pathtodata = "https://cdn.emulatorjs.org/stable/data/";
64
+ EJS_gameUrl = "{rom_url}";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
  </script>
66
  <script src="https://cdn.emulatorjs.org/stable/data/loader.js"></script>
67
  </head>
 
74
  # Gradio App
75
  def gradio_app():
76
  with gr.Blocks(css=".gradio-dropdown { max-height: 400px; overflow-y: auto; }") as app:
77
+ gr.Markdown("# 🎮 Play NES ROMs in Browser!")
78
 
 
79
  rom_files = list_roms()
80
 
 
81
  with gr.Column():
82
+ rom_dropdown = gr.Dropdown(choices=rom_files, label="Select a ROM", interactive=True)
83
+ output_html = gr.HTML(value="Select a ROM to start playing!")
84
+
85
+ rom_dropdown.change(fn=generate_rom_page, inputs=rom_dropdown, outputs=output_html)
 
 
 
86
 
87
+ app.launch(server_name="0.0.0.0", server_port=7860)
 
88
 
89
+ # Run on startup
90
+ if __name__ == "__main__":
91
+ extract_roms()
92
+ gradio_app()
93
 
 
 
94
 
95
 
96