emirkisa commited on
Commit
33c4a54
·
verified ·
1 Parent(s): 3e77b5d

Upload folder using huggingface_hub

Browse files
Files changed (2) hide show
  1. app.py +54 -15
  2. requirements.txt +1 -0
app.py CHANGED
@@ -50,11 +50,18 @@ DAVIS_ZIP_URL = (
50
  IS_HF_SPACE = bool(os.environ.get("SPACE_ID"))
51
 
52
  # Path resolution:
53
- # • HF Spaces with persistent storage → /data/DAVIS
54
- # • HF Spaces without persistent storage → /tmp/DAVIS
55
- # • Local → workspace path (or DAVIS_ROOT env var)
56
  if IS_HF_SPACE:
57
- _hf_base = Path("/data") if Path("/data").exists() else Path("/tmp")
 
 
 
 
 
 
 
58
  _local_root = _hf_base / "DAVIS"
59
  else:
60
  _local_root = Path("/workspace/diffusion-research/data/raw/DAVIS")
@@ -99,15 +106,14 @@ THUMB_W, THUMB_H = 320, 200 # thumbnail dimensions for Gallery
99
 
100
  # ── Dataset download ───────────────────────────────────────────────────────────
101
 
102
- def ensure_dataset() -> None:
103
- """Download and extract DAVIS 2017 trainval (480p) if not already present.
104
 
105
- Safe to call every startup — exits immediately when data is found.
106
- The zip extracts into a top-level ``DAVIS/`` directory, so we extract
107
- into ``DAVIS_ROOT.parent`` which gives the expected ``DAVIS_ROOT`` layout.
108
- """
109
  if IMG_DIR.exists() and any(IMG_DIR.iterdir()):
110
- return # data already present
111
 
112
  import urllib.request
113
  import zipfile
@@ -134,10 +140,8 @@ def ensure_dataset() -> None:
134
  raise RuntimeError(f"Download failed: {exc}") from exc
135
 
136
  print(f"\n Download complete ({zip_dst.stat().st_size // 1_048_576} MB). Extracting…")
137
-
138
  with zipfile.ZipFile(zip_dst, "r") as zf:
139
  zf.extractall(DAVIS_ROOT.parent)
140
-
141
  zip_dst.unlink(missing_ok=True)
142
 
143
  if not IMG_DIR.exists():
@@ -148,6 +152,40 @@ def ensure_dataset() -> None:
148
  print(f" DAVIS dataset ready at {DAVIS_ROOT}")
149
 
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  # ── Dataset loading ────────────────────────────────────────────────────────────
152
 
153
  def _read_split(year: str, split: str) -> list[str]:
@@ -190,6 +228,7 @@ def build_dataframe() -> pd.DataFrame:
190
 
191
 
192
  ensure_dataset()
 
193
  print("Loading DAVIS metadata…")
194
  DF = build_dataframe()
195
  ALL_SEQUENCES = sorted(DF["sequence"].tolist())
@@ -1033,8 +1072,8 @@ start_precache(fps=DEFAULT_FPS, workers=4)
1033
 
1034
  if __name__ == "__main__":
1035
  if IS_HF_SPACE:
1036
- # HF Spaces manages routing just launch without binding params.
1037
- demo.launch(theme=gr.themes.Soft())
1038
  else:
1039
  parser = argparse.ArgumentParser(description="DAVIS Dataset Explorer")
1040
  parser.add_argument("--share", action="store_true")
 
50
  IS_HF_SPACE = bool(os.environ.get("SPACE_ID"))
51
 
52
  # Path resolution:
53
+ # • HF Spaces with persistent storage → /data/DAVIS (survives restarts ✅)
54
+ # • HF Spaces without persistent storage → /tmp/DAVIS (wiped on restart ⚠️)
55
+ # • Local → workspace path (or DAVIS_ROOT env var)
56
  if IS_HF_SPACE:
57
+ _data_dir = Path("/data")
58
+ if _data_dir.exists() and os.access(_data_dir, os.W_OK):
59
+ _hf_base = _data_dir
60
+ print("Persistent storage detected at /data ✅")
61
+ else:
62
+ _hf_base = Path("/tmp")
63
+ print("⚠️ WARNING: /data not available — using /tmp (data will be lost on restart).")
64
+ print(" → Go to Space Settings → Persistent Storage and attach a disk to fix this.")
65
  _local_root = _hf_base / "DAVIS"
66
  else:
67
  _local_root = Path("/workspace/diffusion-research/data/raw/DAVIS")
 
106
 
107
  # ── Dataset download ───────────────────────────────────────────────────────────
108
 
109
+ HF_CACHE_REPO = "emirkisa/DAVIS-2017-480p-mp4" # pre-encoded MP4s
110
+ HF_CACHE_MARKER = CACHE_DIR / ".hf_cache_downloaded"
111
 
112
+
113
+ def ensure_dataset() -> None:
114
+ """Download and extract DAVIS 2017 trainval (480p) if not already present."""
 
115
  if IMG_DIR.exists() and any(IMG_DIR.iterdir()):
116
+ return
117
 
118
  import urllib.request
119
  import zipfile
 
140
  raise RuntimeError(f"Download failed: {exc}") from exc
141
 
142
  print(f"\n Download complete ({zip_dst.stat().st_size // 1_048_576} MB). Extracting…")
 
143
  with zipfile.ZipFile(zip_dst, "r") as zf:
144
  zf.extractall(DAVIS_ROOT.parent)
 
145
  zip_dst.unlink(missing_ok=True)
146
 
147
  if not IMG_DIR.exists():
 
152
  print(f" DAVIS dataset ready at {DAVIS_ROOT}")
153
 
154
 
155
+ def ensure_cache() -> None:
156
+ """Download pre-encoded MP4 cache from HF Hub if not already present.
157
+
158
+ Downloads ``emirkisa/davis-explorer-cache`` into ``CACHE_DIR``.
159
+ Skipped if the marker file already exists (i.e. downloaded before).
160
+ Falls back silently if the repo is unavailable — the app will encode
161
+ on demand instead.
162
+ """
163
+ if HF_CACHE_MARKER.exists():
164
+ print(f" MP4 cache already downloaded ({CACHE_DIR})")
165
+ return
166
+
167
+ # Count how many raw MP4s are already present locally
168
+ existing = list(CACHE_DIR.glob("*_raw_*fps.mp4"))
169
+ if len(existing) >= len(list(IMG_DIR.iterdir())):
170
+ HF_CACHE_MARKER.touch()
171
+ print(f" MP4 cache already complete locally ({len(existing)} raw files)")
172
+ return
173
+
174
+ try:
175
+ from huggingface_hub import snapshot_download
176
+ print(f"Downloading MP4 cache from {HF_CACHE_REPO} (~290 MB)…")
177
+ snapshot_download(
178
+ repo_id=HF_CACHE_REPO,
179
+ repo_type="dataset",
180
+ local_dir=str(CACHE_DIR),
181
+ )
182
+ HF_CACHE_MARKER.touch()
183
+ n = len(list(CACHE_DIR.glob("*.mp4")))
184
+ print(f" MP4 cache ready — {n} files in {CACHE_DIR}")
185
+ except Exception as e:
186
+ print(f" ⚠️ Could not download MP4 cache ({e}). Will encode on demand.")
187
+
188
+
189
  # ── Dataset loading ────────────────────────────────────────────────────────────
190
 
191
  def _read_split(year: str, split: str) -> list[str]:
 
228
 
229
 
230
  ensure_dataset()
231
+ ensure_cache()
232
  print("Loading DAVIS metadata…")
233
  DF = build_dataframe()
234
  ALL_SEQUENCES = sorted(DF["sequence"].tolist())
 
1072
 
1073
  if __name__ == "__main__":
1074
  if IS_HF_SPACE:
1075
+ # HF Spaces runs `python app.py` directly must bind to 0.0.0.0.
1076
+ demo.launch(server_name="0.0.0.0", server_port=7860, theme=gr.themes.Soft())
1077
  else:
1078
  parser = argparse.ArgumentParser(description="DAVIS Dataset Explorer")
1079
  parser.add_argument("--share", action="store_true")
requirements.txt CHANGED
@@ -3,3 +3,4 @@ numpy
3
  pandas
4
  pillow
5
  plotly
 
 
3
  pandas
4
  pillow
5
  plotly
6
+ huggingface_hub