drdata commited on
Commit
780f03f
Β·
verified Β·
1 Parent(s): fa184c4

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. hf_deploy/app.py +120 -34
hf_deploy/app.py CHANGED
@@ -1,7 +1,14 @@
1
  #!/usr/bin/env python3
2
  """
3
  HuggingFace Spaces main launcher for BytePlus Image Generation Studio
4
- Ensures all required directories exist before starting the app
 
 
 
 
 
 
 
5
  """
6
 
7
  import os
@@ -9,37 +16,114 @@ import sys
9
  from pathlib import Path
10
  import importlib.util
11
 
12
- def ensure_directories_exist():
13
- """Create all required directories for BytePlus operation."""
14
- print("πŸ—οΈ Ensuring required directories exist...")
15
-
16
- # Define all directories needed
17
- directories = [
18
- "Generated",
19
- "static",
20
- "view_session",
21
- "static/css",
22
- "static/js",
23
- "static/images"
24
- ]
25
-
26
- for dir_name in directories:
27
- dir_path = Path(dir_name)
28
- try:
29
- if not dir_path.exists():
30
- dir_path.mkdir(parents=True, exist_ok=True)
31
- print(f"βœ… Created directory: {dir_name}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  else:
33
- print(f"βœ… Directory exists: {dir_name}")
34
-
35
- # Set proper permissions (755 for directories)
36
- if dir_path.is_dir():
37
- dir_path.chmod(0o755)
38
-
39
- except Exception as e:
40
- print(f"⚠️ Warning: Could not handle {dir_name}: {e}")
41
-
42
- print("🎯 All required directories are ready!")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
 
44
  def load_byteplus_app():
45
  """Load and return the BytePlus application."""
@@ -73,8 +157,8 @@ def main():
73
  """Main function to setup and launch BytePlus."""
74
  print("πŸš€ Starting BytePlus Image Generation Studio for HuggingFace Spaces...")
75
 
76
- # Ensure directories exist first
77
- ensure_directories_exist()
78
 
79
  # Load and launch the BytePlus app
80
  try:
@@ -82,7 +166,9 @@ def main():
82
  demo = load_byteplus_app()
83
 
84
  print("πŸŽ‰ Launching BytePlus Image Generation Studio...")
85
- demo.launch()
 
 
86
 
87
  except Exception as e:
88
  print(f"❌ Error launching BytePlus: {e}")
 
1
  #!/usr/bin/env python3
2
  """
3
  HuggingFace Spaces main launcher for BytePlus Image Generation Studio
4
+
5
+ Alternative directory strategy for Spaces where the repository may not contain
6
+ the required folders (Generated/, static/, view_session/):
7
+
8
+ 1) Create these folders under a persistent/writable base (prefer /data, fallback /tmp)
9
+ 2) Symlink them into the working directory so the app can use relative paths
10
+
11
+ This works even when the repo itself doesn't track those directories.
12
  """
13
 
14
  import os
 
16
  from pathlib import Path
17
  import importlib.util
18
 
19
+ def _is_writable(p: Path) -> bool:
20
+ try:
21
+ p.mkdir(parents=True, exist_ok=True)
22
+ test_file = p / ".__writable_test__"
23
+ test_file.write_text("ok")
24
+ test_file.unlink(missing_ok=True)
25
+ return True
26
+ except Exception:
27
+ return False
28
+
29
+ def _pick_persistent_base() -> Path:
30
+ """Pick a persistent base directory on Spaces.
31
+ - Prefer /data if available/writable (persisted across restarts)
32
+ - Fallback to /tmp if /data is unavailable
33
+ """
34
+ candidates = [Path("/data/byteplus"), Path("/data"), Path("/tmp/byteplus")]
35
+ for c in candidates:
36
+ base = c if c.name == "byteplus" else c / "byteplus"
37
+ if _is_writable(base):
38
+ return base
39
+ # Final fallback
40
+ return Path("/tmp/byteplus")
41
+
42
+ def _ensure_dir(path: Path):
43
+ path.mkdir(parents=True, exist_ok=True)
44
+ try:
45
+ path.chmod(0o755)
46
+ except Exception:
47
+ pass
48
+
49
+ def _safe_symlink(target: Path, link_path: Path):
50
+ """Create/repair a symlink from link_path -> target.
51
+ If link_path exists as a real dir, attempt to migrate contents, then replace with symlink.
52
+ """
53
+ try:
54
+ if link_path.is_symlink() or link_path.exists():
55
+ # If it's already the correct symlink, keep it
56
+ try:
57
+ if link_path.is_symlink() and link_path.resolve() == target.resolve():
58
+ return
59
+ except Exception:
60
+ pass
61
+
62
+ if link_path.is_symlink():
63
+ link_path.unlink()
64
+ elif link_path.is_dir():
65
+ # Migrate existing contents to target
66
+ target.mkdir(parents=True, exist_ok=True)
67
+ for item in link_path.iterdir():
68
+ dest = target / item.name
69
+ try:
70
+ if item.is_dir():
71
+ if dest.exists():
72
+ # Merge: move children
73
+ for sub in item.iterdir():
74
+ sub.rename(dest / sub.name)
75
+ item.rmdir()
76
+ else:
77
+ item.rename(dest)
78
+ else:
79
+ if dest.exists():
80
+ dest.unlink()
81
+ item.rename(dest)
82
+ except Exception as e:
83
+ print(f"⚠️ Migration warning for {item}: {e}")
84
+ # Now remove the original dir
85
+ try:
86
+ link_path.rmdir()
87
+ except Exception:
88
+ pass
89
  else:
90
+ # Regular file: remove to replace with symlink
91
+ link_path.unlink(missing_ok=True)
92
+
93
+ # Ensure target exists before linking
94
+ target.mkdir(parents=True, exist_ok=True)
95
+ link_path.symlink_to(target, target_is_directory=True)
96
+ print(f"πŸ”— Linked {link_path} -> {target}")
97
+ except Exception as e:
98
+ print(f"⚠️ Could not create symlink {link_path} -> {target}: {e}")
99
+ # Fallback: ensure local directory exists
100
+ try:
101
+ _ensure_dir(link_path)
102
+ print(f"πŸ“ Fallback: created local dir {link_path}")
103
+ except Exception as ie:
104
+ print(f"❌ Fallback failed for {link_path}: {ie}")
105
+
106
+ def ensure_persistent_dirs_and_symlinks():
107
+ """Ensure required dirs exist in persistent storage and are symlinked into CWD."""
108
+ print("πŸ—οΈ Ensuring required directories via persistent storage and symlinks...")
109
+ base = _pick_persistent_base()
110
+ print(f"πŸ“¦ Using storage base: {base}")
111
+
112
+ # Create persistent dirs
113
+ gen_p = base / "Generated"
114
+ static_p = base / "static"
115
+ view_p = base / "view_session"
116
+
117
+ for d in [gen_p, static_p, view_p, static_p / "css", static_p / "js", static_p / "images"]:
118
+ _ensure_dir(d)
119
+
120
+ # Symlink into working directory
121
+ cwd = Path.cwd()
122
+ _safe_symlink(gen_p, cwd / "Generated")
123
+ _safe_symlink(static_p, cwd / "static")
124
+ _safe_symlink(view_p, cwd / "view_session")
125
+
126
+ print("🎯 Symlinked working directories are ready!")
127
 
128
  def load_byteplus_app():
129
  """Load and return the BytePlus application."""
 
157
  """Main function to setup and launch BytePlus."""
158
  print("πŸš€ Starting BytePlus Image Generation Studio for HuggingFace Spaces...")
159
 
160
+ # Ensure persistent storage dirs exist and are symlinked into CWD
161
+ ensure_persistent_dirs_and_symlinks()
162
 
163
  # Load and launch the BytePlus app
164
  try:
 
166
  demo = load_byteplus_app()
167
 
168
  print("πŸŽ‰ Launching BytePlus Image Generation Studio...")
169
+ # Ensure proper binding for Spaces
170
+ port = int(os.getenv("PORT", "7860"))
171
+ demo.launch(server_name="0.0.0.0", server_port=port)
172
 
173
  except Exception as e:
174
  print(f"❌ Error launching BytePlus: {e}")