mozzic commited on
Commit
21b1198
·
verified ·
1 Parent(s): e9b8ae5

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +49 -35
app.py CHANGED
@@ -1,36 +1,53 @@
1
  #!/usr/bin/env python3
2
- """Hugging Face Spaces - fix backslash filenames"""
3
  import os
4
  import sys
5
  import importlib.util
6
  from pathlib import Path
 
7
 
8
  app_dir = Path("/app")
9
  sys.path.insert(0, str(app_dir))
10
 
11
- print(f"Starting app from {app_dir}\n")
12
 
13
- # Step 1: Preload ALL src modules with proper names (no backslashes)
14
- print("Loading src modules:")
15
- src_modules = {}
16
- for item in app_dir.iterdir():
 
 
 
17
  name = item.name
18
- if name.startswith("src\\") and name.endswith(".py"):
19
  # Extract module name: "src\models.py" -> "models"
20
  module_name = name.split("\\")[-1].replace(".py", "")
21
 
 
 
 
22
  try:
23
- spec = importlib.util.spec_from_file_location(module_name, str(item))
 
 
24
  module = importlib.util.module_from_spec(spec)
 
 
 
25
  sys.modules[module_name] = module
26
- src_modules[module_name] = module
 
27
  spec.loader.exec_module(module)
28
- print(f" {module_name}")
 
 
 
 
29
  except Exception as e:
30
- print(f" {module_name}: {e}")
31
 
32
- # Step 2: Fix imports in the code
33
- print("\nPreparing ui/app.py code:")
34
  ui_app_path = None
35
  for item in app_dir.iterdir():
36
  if item.name == "ui\\app.py":
@@ -41,29 +58,26 @@ if ui_app_path and ui_app_path.exists():
41
  with open(str(ui_app_path), 'r', encoding='utf-8', errors='ignore') as f:
42
  code = f.read()
43
 
44
- # Fix all src imports
45
- original_code = code
46
- code = code.replace("from src.", "from ")
47
- code = code.replace("import src.", "import ")
 
 
48
 
49
- print(f" Fixed imports in ui/app.py")
 
 
 
50
 
51
- # Step 3: Execute the code
52
- print("\nLaunching Gradio app:")
53
  try:
54
- exec_globals = {
55
- "__name__": "__main__",
56
- "__file__": str(ui_app_path),
57
- "create_gradio_app": None
58
- }
59
- exec_locals = {}
60
-
61
- exec(compile(code, str(ui_app_path), "exec"), exec_globals, exec_locals)
62
-
63
- # Get the function from locals
64
- create_gradio_app = exec_globals.get("create_gradio_app") or exec_locals.get("create_gradio_app")
65
 
66
- if create_gradio_app:
 
 
 
67
  demo = create_gradio_app()
68
  demo.launch(
69
  server_name="0.0.0.0",
@@ -71,11 +85,11 @@ if ui_app_path and ui_app_path.exists():
71
  show_error=True
72
  )
73
  else:
74
- print("ERROR: create_gradio_app not found after execution")
75
 
76
  except Exception as e:
77
- print(f"ERROR: {e}")
78
  import traceback
79
  traceback.print_exc()
80
  else:
81
- print(f"ERROR: ui\\app.py not found")
 
1
  #!/usr/bin/env python3
2
+ """Hugging Face Spaces - create proper module namespace"""
3
  import os
4
  import sys
5
  import importlib.util
6
  from pathlib import Path
7
+ from types import ModuleType
8
 
9
  app_dir = Path("/app")
10
  sys.path.insert(0, str(app_dir))
11
 
12
+ print("Setting up module namespace...\n")
13
 
14
+ # Create fake src package
15
+ src_package = ModuleType("src")
16
+ src_package.__path__ = [str(app_dir / "src")]
17
+ sys.modules["src"] = src_package
18
+
19
+ print("Loading src modules into src namespace:")
20
+ for item in sorted(app_dir.iterdir()):
21
  name = item.name
22
+ if name.startswith("src\\") and name.endswith(".py") and not name.endswith("__pycache__"):
23
  # Extract module name: "src\models.py" -> "models"
24
  module_name = name.split("\\")[-1].replace(".py", "")
25
 
26
+ if module_name == "__init__":
27
+ continue
28
+
29
  try:
30
+ # Load as src.MODULE_NAME
31
+ full_name = f"src.{module_name}"
32
+ spec = importlib.util.spec_from_file_location(full_name, str(item))
33
  module = importlib.util.module_from_spec(spec)
34
+ sys.modules[full_name] = module
35
+
36
+ # Also make it accessible as just MODULE_NAME for direct imports
37
  sys.modules[module_name] = module
38
+
39
+ # Execute the module
40
  spec.loader.exec_module(module)
41
+ print(f" {full_name}")
42
+
43
+ # Add to src package
44
+ setattr(src_package, module_name, module)
45
+
46
  except Exception as e:
47
+ print(f" {full_name}: {str(e)[:60]}")
48
 
49
+ # Now load ui/app.py
50
+ print("\nLoading ui/app.py:")
51
  ui_app_path = None
52
  for item in app_dir.iterdir():
53
  if item.name == "ui\\app.py":
 
58
  with open(str(ui_app_path), 'r', encoding='utf-8', errors='ignore') as f:
59
  code = f.read()
60
 
61
+ # Create execution environment with all modules
62
+ exec_globals = {
63
+ "__name__": "__main__",
64
+ "__file__": str(ui_app_path),
65
+ "src": src_package,
66
+ }
67
 
68
+ # Add all src modules to globals
69
+ for key in list(sys.modules.keys()):
70
+ if key.startswith("src."):
71
+ exec_globals[key.split(".")[-1]] = sys.modules[key]
72
 
 
 
73
  try:
74
+ print(" Executing ui/app.py...")
75
+ exec(compile(code, str(ui_app_path), "exec"), exec_globals)
 
 
 
 
 
 
 
 
 
76
 
77
+ # Launch the app
78
+ create_gradio_app = exec_globals.get("create_gradio_app")
79
+ if create_gradio_app and callable(create_gradio_app):
80
+ print(" Launching Gradio app...")
81
  demo = create_gradio_app()
82
  demo.launch(
83
  server_name="0.0.0.0",
 
85
  show_error=True
86
  )
87
  else:
88
+ print(" create_gradio_app not found")
89
 
90
  except Exception as e:
91
+ print(f" Error: {e}")
92
  import traceback
93
  traceback.print_exc()
94
  else:
95
+ print(" ui\\app.py not found")