Fred808 commited on
Commit
cd27320
·
verified ·
1 Parent(s): e75a663

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -35
app.py CHANGED
@@ -1,41 +1,109 @@
1
  import requests
2
- from huggingface_hub import upload_file
3
  import os
 
 
4
 
5
- # Load Hugging Face token from environment (Space secrets)
6
  HF_TOKEN = os.environ.get("HF_TOKEN")
7
  REPO_ID = "Fred808/BG1"
8
  DATA_PATH = "Blenders"
9
- DOWNLOAD_ENDPOINT = "https://fred808-data2.hf.space/download/"
10
-
11
- AVAILABLE_FILES = [
12
- "wJe9zz_G4js.mp4", "6RKL-j1k4Dc.mp4", "tK848ib0BBw.mp4", "r6ZQil-zd5Y.mp4", "-gbCSnkvwNo.mp4",
13
- "oso5I277FRY.mp4", "4haAdmHqGOw.mp4", "OeGULgqwJh8.mp4", "QtIfb9JXOJg.mp4", "lgljOqhhgHg.mp4",
14
- "bokz-7HbgGM.mp4", "-CiHJ41n6VI.mp4", "Ys4793edotw.mp4", "9N87-yRR5aE.mp4", "5WOrfMz2Sqs.mp4",
15
- "1qVbGr_ie30.mp4", "qa_1LjeWsJg.mp4", "9OVvnOh2ZGk.mp4", "xEpVyEi1Hts.mp4", "Wg244y2f9Fw.mp4",
16
- "a-4oCHe-hDE.mp4", "Q30-nakUrSM.mp4", "HSm-cq7zd2s.mp4", "x6oWgtJInCQ.mp4", "9gn_1V1sCS8.mp4",
17
- "dIv2FXyD3CU.mp4", "SGUBriL9bNU.mp4", "ABayYXu7OfI.mp4", "-c0Evpf8V3A.mp4", "F7VggbBaCsg.mp4",
18
- "cn5BC3Vzcsc.mp4", "TbjEVSNPiMQ.mp4", "2PNiRWStZIo.mp4", "UEeXv1bczuE.mp4", "mYgznqvbisM.mp4"
 
19
  ]
20
 
21
- def download_video(filename):
22
- url = f"{DOWNLOAD_ENDPOINT}{filename}"
23
- local_path = f"/tmp/{filename}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  try:
25
- res = requests.get(url, stream=True)
26
- if res.status_code == 200:
27
- with open(local_path, "wb") as f:
28
- for chunk in res.iter_content(chunk_size=8192):
29
- f.write(chunk)
30
- print(f"[+] Downloaded {filename}")
31
- return local_path
 
 
 
 
 
 
 
 
 
32
  else:
33
- print(f"[!] Failed to download {filename}: {res.status_code}")
34
- return None
35
  except Exception as e:
36
- print(f"[!] Error downloading {filename}: {e}")
37
- return None
 
 
 
 
38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  def upload_to_dataset(filepath):
40
  try:
41
  upload_file(
@@ -45,13 +113,29 @@ def upload_to_dataset(filepath):
45
  repo_type="dataset",
46
  token=HF_TOKEN
47
  )
48
- print(f"[+] Uploaded {filepath}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  except Exception as e:
50
- print(f"[!] Upload failed for {filepath}: {e}")
51
-
52
- if __name__ == "__main__":
53
- for filename in AVAILABLE_FILES:
54
- local_file = download_video(filename)
55
- if local_file:
56
- upload_to_dataset(local_file)
57
- os.remove(local_file)
 
1
  import requests
 
2
  import os
3
+ import time
4
+ from huggingface_hub import upload_file
5
 
6
+ # === CONFIGURATION ===
7
  HF_TOKEN = os.environ.get("HF_TOKEN")
8
  REPO_ID = "Fred808/BG1"
9
  DATA_PATH = "Blenders"
10
+
11
+ # HF Space API
12
+ INIT_API_URL = "https://fred808-data1.hf.space/batch/download"
13
+ STATUS_API_URL = "https://fred808-data1.hf.space/batch/status/{}"
14
+ FETCH_API_URL = "https://fred808-data1.hf.space/batch/download-all/{}"
15
+
16
+ # Video URLs to send
17
+ VIDEO_URLS = [
18
+ "https://youtu.be/8v_KFHnPImY?si=ymCyTu9Arj2sGUuE",
19
+ "https://youtu.be/wJe9zz_G4js",
20
+ "https://youtu.be/OeGULgqwJh8"
21
  ]
22
 
23
+ # Local download settings
24
+ OUTPUT_DIR = "batch_downloads"
25
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
26
+
27
+ # Polling behavior
28
+ POLL_DELAY = 5
29
+ MAX_WAIT_MINUTES = 5
30
+ MAX_RETRIES = int((MAX_WAIT_MINUTES * 60) / POLL_DELAY)
31
+
32
+ # === STEP 1: Submit batch request ===
33
+ print(f"[*] Submitting {len(VIDEO_URLS)} URLs to batch API...")
34
+
35
+ try:
36
+ res = requests.post(INIT_API_URL, json={"urls": VIDEO_URLS})
37
+ res.raise_for_status()
38
+ batch_id = res.json().get("batch_id")
39
+ if not batch_id:
40
+ raise Exception("No batch_id returned.")
41
+ print(f"[+] Batch submitted. ID: {batch_id}")
42
+ except Exception as e:
43
+ print(f"[!] Submission error: {e}")
44
+ exit(1)
45
+
46
+ # === STEP 2: Poll for status ===
47
+ status_url = STATUS_API_URL.format(batch_id)
48
+ print("[*] Waiting for batch processing to complete...")
49
+
50
+ for attempt in range(MAX_RETRIES):
51
  try:
52
+ res = requests.get(status_url)
53
+ res.raise_for_status()
54
+ data = res.json()
55
+
56
+ status = data.get("status")
57
+ total = data.get("total_urls", "?")
58
+ completed = data.get("completed", 0)
59
+ failed = data.get("failed", 0)
60
+
61
+ if status == "completed":
62
+ print(f"[✓] All {completed}/{total} processed.")
63
+ break
64
+ elif status in ["started", "processing", "in_progress"]:
65
+ print(f"[~] Still processing... {completed}/{total} done, {failed} failed.")
66
+ elif status == "failed":
67
+ raise Exception("Server marked batch as failed.")
68
  else:
69
+ print(f"[~] Unknown status '{status}', retrying...")
70
+
71
  except Exception as e:
72
+ print(f"[!] Polling error: {e}")
73
+
74
+ time.sleep(POLL_DELAY)
75
+ else:
76
+ print("[!] Timeout while waiting for batch to complete.")
77
+ exit(1)
78
 
79
+ # === STEP 3: Get downloadable URLs ===
80
+ fetch_url = FETCH_API_URL.format(batch_id)
81
+ print("[*] Fetching downloadable links...")
82
+
83
+ for attempt in range(MAX_RETRIES):
84
+ try:
85
+ res = requests.get(fetch_url)
86
+ if res.status_code != 200:
87
+ print(f"[~] Server not ready yet ({res.status_code}). Retry {attempt+1}")
88
+ time.sleep(POLL_DELAY)
89
+ continue
90
+
91
+ data = res.json()
92
+ downloads = data.get("downloads", [])
93
+ if downloads:
94
+ print(f"[+] Found {len(downloads)} downloadable files.")
95
+ break
96
+ else:
97
+ print(f"[~] No files yet, retrying ({attempt+1})...")
98
+
99
+ except Exception as e:
100
+ print(f"[!] Fetching error: {e}")
101
+ time.sleep(POLL_DELAY)
102
+ else:
103
+ print("[!] Timeout: Download URLs not available.")
104
+ exit(1)
105
+
106
+ # === STEP 4: Download + Upload to Hugging Face dataset ===
107
  def upload_to_dataset(filepath):
108
  try:
109
  upload_file(
 
113
  repo_type="dataset",
114
  token=HF_TOKEN
115
  )
116
+ print(f"[↑] Uploaded to HF: {filepath}")
117
+ except Exception as e:
118
+ print(f"[!] Upload failed: {filepath} - {e}")
119
+
120
+ for video in downloads:
121
+ filename = video.get("filename")
122
+ url = video.get("url")
123
+
124
+ if not filename or not url:
125
+ print("[!] Skipping invalid download entry.")
126
+ continue
127
+
128
+ local_path = os.path.join(OUTPUT_DIR, filename)
129
+ try:
130
+ print(f"[*] Downloading {filename}...")
131
+ with requests.get(url, stream=True) as r:
132
+ r.raise_for_status()
133
+ with open(local_path, "wb") as f:
134
+ for chunk in r.iter_content(chunk_size=8192):
135
+ if chunk:
136
+ f.write(chunk)
137
+ print(f"[✓] Saved to: {local_path}")
138
+ upload_to_dataset(local_path)
139
+ os.remove(local_path)
140
  except Exception as e:
141
+ print(f"[!] Download/upload failed for {filename}: {e}")