File size: 7,089 Bytes
c9ff965 6f9647d c9ff965 057d70d c9ff965 8fc9264 c9ff965 6f9647d 8673beb c9ff965 8673beb c9ff965 8673beb c9ff965 8673beb c9ff965 8673beb c9ff965 6f9647d 8673beb 6f9647d 541b32b 6f9647d 541b32b 6f9647d 541b32b 6f9647d 541b32b 6f9647d 541b32b 6f9647d 541b32b 6f9647d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | import path from "node:path";
import { AccessToken, RepoDesignation } from "@huggingface/hub";
import * as hub from "@huggingface/hub";
import { NS_routes_c } from "../../../../../packages/lib/helpers/client/route";
import { NS_misc } from "./misc";
import { NS_promise } from "./promise";
import { NS_ffmpeg_v2 } from "./ffmpeg-v2";
const HF_BUCKET_ACCESS_TOKEN = process.env.HF_BUCKET_ACCESS_TOKEN;
const HF_BUCKET_REPO = process.env.HF_BUCKET_REPO;
export const STORAGE_ROOT =
process.env.STORAGE_ROOT || path.join(process.cwd(), "S3");
export const repo: RepoDesignation = {
type: "bucket",
name: HF_BUCKET_REPO || ""
};
export const credentials: { accessToken: AccessToken } = {
accessToken: HF_BUCKET_ACCESS_TOKEN!
};
// await hub.createRepo({
// repo,
// accessToken: credentials.accessToken,
// private: false
// });
type T_UploadJob = {
status: "in-progress" | "done" | "failed";
tmp_path?: string | null;
created_at: number;
error?: string;
percent?: number;
transcoded_size?: string;
progress_endpoint?: string;
};
const upload_jobs = new Map<string, T_UploadJob>();
export const NS_bucket = {
track_upload_process: {
v1: trackProgress,
v2: trackProgress_v2
},
get_hf_bucket_file_info,
get_hf_bucket_list_of_files,
get_latest_hf_bucket_file_by_name,
upload_to_bucket
};
function trackProgress(
blob: Blob,
onProgress: (pct: number) => void
): ReadableStream<Uint8Array> {
const total = blob.size;
let loaded = 0;
let lastReported = -1;
return new ReadableStream({
async start(controller) {
const reader = blob.stream().getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
loaded += value.byteLength;
// only fire when % actually changes
const pct = Math.round((loaded / total) * 100);
if (pct !== lastReported) {
lastReported = pct;
onProgress(pct);
}
controller.enqueue(value);
}
controller.close();
}
});
}
function trackProgress_v2(
blob: Blob,
onProgress: (pct: number) => void
): ReadableStream {
const total = blob.size;
let loaded = 0;
let lastReported = -1;
return new ReadableStream({
async start(controller) {
const reader = blob.stream().getReader();
while (true) {
const { done, value } = await reader.read();
if (done) break;
loaded += value.byteLength;
const pct = Math.round((loaded / total) * 100);
if (pct % 5 === 0 && pct !== lastReported) {
lastReported = pct;
onProgress(pct);
}
controller.enqueue(value);
}
controller.close();
}
});
}
async function get_hf_bucket_file_info(arg0: { file_path: string }) {
const { file_path } = arg0;
if (
!credentials.accessToken ||
typeof file_path !== "string" ||
NS_routes_c.F_is_url(file_path)
) {
return;
}
try {
const info = await hub.fileDownloadInfo({
repo,
path: file_path,
accessToken: credentials.accessToken
});
return info;
} catch {
// file doesn't exist
}
}
async function get_hf_bucket_list_of_files() {
if (!credentials.accessToken) return;
const available_files = await Array.fromAsync(
hub.listFiles({
repo,
recursive: true,
accessToken: credentials.accessToken
})
);
return available_files;
}
async function get_latest_hf_bucket_file_by_name(arg0: {
folder_path: string;
human_filename: string;
sbe_id?: string;
}) {
const { folder_path, human_filename, sbe_id } = arg0;
if (
!credentials.accessToken ||
typeof folder_path !== "string" ||
typeof human_filename !== "string"
) {
return;
}
try {
const files = await Array.fromAsync(
hub.listFiles({
repo,
accessToken: credentials.accessToken,
path: folder_path,
recursive: false
})
);
// match files whose name ends with -{human_filename}
const matching = files.filter((f) => {
const name = f.path.split("/").pop() ?? "";
const withoutPrefix = name.slice(name.indexOf("-") + 1);
return withoutPrefix.toLowerCase() === human_filename.toLowerCase();
});
if (matching.length === 0) return;
// pool 1 — sbe_id prefixed
const sbe_id_pool = sbe_id
? matching.filter((f) => {
const name = f.path.split("/").pop() ?? "";
const prefix = name.slice(0, name.indexOf("-"));
return prefix === sbe_id;
})
: [];
// pool 2 — timestamp prefixed, from what's left after removing sbe_id matches
const remaining = matching.filter((f) => !sbe_id_pool.includes(f));
const timestamp_pool = remaining
.map((f) => {
const name = f.path.split("/").pop() ?? "";
const prefix = Number(name.slice(0, name.indexOf("-")));
return { f, ts: NS_misc.isValidUnixTimestamp(prefix) ? prefix : null };
})
.filter((x) => x.ts !== null)
.sort((a, b) => b.ts! - a.ts!)
.map((x) => x.f);
// prefer timestamp pool, fallback to sbe_id pool
let pool =
timestamp_pool.length > 0
? timestamp_pool
: sbe_id_pool.length > 0
? sbe_id_pool
: [];
if (true) {
const _ = matching.sort((a, b) => {
const da = new Date(a.uploadedAt ?? 0).getTime();
const db = new Date(b.uploadedAt ?? 0).getTime();
return db - da;
});
if (_.length) {
pool = [..._];
}
}
const best_file = await get_hf_bucket_file_info({
file_path: pool[0].path
});
return best_file;
} catch {}
}
async function upload_to_bucket(arg0: {
job_id: string;
bucket_path: string;
file_with_path: string;
skip?: {
probe?: boolean;
};
REQ0?: URL;
}) {
const { job_id, bucket_path, skip, file_with_path, REQ0 } = arg0;
upload_jobs.set(job_id, {
status: "in-progress",
created_at: Date.now()
});
console.log("\n", "🧲 UPLOADING TO BUCKET", "\n");
if (!skip?.probe) {
const [E_, R_] = await NS_promise.F_catch_promise({
promise: NS_ffmpeg_v2.F_probe_t1({
playback: {
url: file_with_path,
type: "video",
protocol: "local"
}
})
});
if (E_ || !R_) {
upload_jobs.delete(job_id);
console.log("\n", "❌ UPLOAD BUCKET: FFPROBE FAILED", "\n");
return;
}
}
const blob: any = Bun.file(file_with_path);
const [E__, R__] = await NS_promise.F_catch_promise({
promise: hub.uploadFiles({
repo,
accessToken: credentials.accessToken,
files: [
{
path: bucket_path,
content: blob
}
]
})
});
upload_jobs.delete(job_id);
if (E__) {
console.log("\n", "❌ UPLOAD BUCKET FAILED", E__, "\n");
return { success: false };
}
console.log("\n", "🔥 UPLOAD BUCKET DONE", "\n");
if (REQ0) {
REQ0.searchParams.set("ops", "just_check");
fetch(REQ0.toString());
}
return { success: true };
}
|