Spaces:
Paused
Paused
Upload app.py with huggingface_hub
Browse files123416 unmodified lines212223242526271 unmodified line29303132333435363738394041424344454620 unmodified lines67686970717273747576777879808182838459 unmodified lines1441451461471481491508 unmodified lines1591601611621631641654 unmodified lines17017117217317417517649 unmodified lines2262272282292302316 unmodified lines238239240241242243import os, uuid, re, shutil, traceback, asyncio, json, time, subprocessfrom fastapi import FastAPI, UploadFile, File, Requestfrom fastapi.responses import HTMLResponse, JSONResponsefrom huggingface_hub import batch_bucket_files16 unmodified lines#progress{width:100%;height:24px;background:#e5e7eb;border-radius:12px;overflow:hidden;margin:12px 0;display:none}#bar{height:100%;width:0%;background:#3b82f6;transition:width 0.3s}#log{white-space:pre-wrap;background:#1e293b;color:#e2e8f0;padding:12px;border-radius:8px;max-height:300px;overflow:auto}input[type=text]{width:80%;padding:10px;border:1px solid #cbd5e1;border-radius:8px}button{background:#3b82f6;color:white;border:0;padding:10px 18px;border-radius:8px;cursor:pointer}button:hover{background:#2563eb}</style>1 unmodified line<body><h1>📤 ULP → Private Bucket <code>kovinape/ulp-bucket</code></h1><div class="card"><h3>1. Upload .txt from your PC</h3><div class="drop" id="drop">Drop .txt here or click<br><small>100GB, 5GB shards, private bucket</small><input type="file" id="file" accept=".txt" style="display:none"></div><div id="progress"><div id="bar"></div></div><div id="status"></div></div><div class="card"><h3>2. Fetch from Link (direct upload, no VPS)</h3><input type="text" id="url" placeholder="https://cdn2.linkforge.dpdns.org/download/AgADLg143789 or https://.../file.txt" style="width:75%"><button onclick="fetchLink()">Fetch → Bucket</button><div id="fetchStatus" style="margin-top:10px"></div><div id="fetchBar" style="width:100%;height:24px;background:#e5e7eb;border-radius:12px;overflow:hidden;margin:10px 0;display:none"><div id="fetchBarInner" style="height:100%;width:0%;background:#10b981;transition:width 0.3s"></div></div></div><pre id="log"></pre><script>const drop=document.getElementById('drop'), fileInput=document.getElementById('file'), bar=document.getElementById('bar'), progress=document.getElementById('progress'), status=document.getElementById('status'), log=document.getElementById('log');20 unmodified linesasync function fetchLink(){const url=document.getElementById('url').value.trim();if(!url){alert('Paste a URL');return;}document.getElementById('fetchStatus').textContent='🔗 Fetching → bucket (live progress below)...';document.getElementById('fetchBar').style.display='block';const res=await fetch('/fetch', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({url})});const data=await res.json();if(data.job_id){ poll(data.job_id); } else { document.getElementById('fetchStatus').textContent=JSON.stringify(data); }}async function poll(job_id){const bar=document.getElementById('fetchBarInner'), st=document.getElementById('fetchStatus');const iv=setInterval(async()=>{const r=await fetch('/fetch/progress?job_id='+job_id);const j=await r.json();st.textContent=j.status+ (j.pct?` ${j.pct}%`:'') + (j.speed?` • ${j.speed}`:'');if(j.pct) bar.style.width=j.pct+'%';if(j.status.includes('Done')||j.status.includes('Failed')) clearInterval(iv);},1000);59 unmodified linestry:tmp_base=f"/tmp/fetch_{job_id}"os.makedirs(tmp_base, exist_ok=True)# handle mediafire page -> extract direct linkorig_url=urlif "mediafire.com/file/" in url:try:8 unmodified linesfname=url.split("/")[-1].split("?")[0] or orig_url.split("/")[-1].split("?")[0] or "fetched.txt"fname=re.sub(r'[^A-Za-z0-9._ -]', '_', fname)[:80] or "fetched.txt"if not fname.endswith(".txt"): fname+=".txt"# try to get better filename from content-disposition via HEADtry:import requestsh=requests.head(url, allow_redirects=True, timeout=10)4 unmodified linesexcept: passtmp_path=os.path.join(tmp_base, fname)jobs[job_id]={"status":f"Downloading {fname}...","pct":5}# Try aria2c 16x for speed, fallback to curltry:cmd=["aria2c","-x","16","-s","16","-k","1M","-o",tmp_path,url,"--allow-overwrite=true","--auto-file-renaming=false","--console-log-level=warn"]proc=subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)49 unmodified linestraceback.print_exc()jobs[job_id]={"status":f"Failed: {e}","pct":0}@app.post("/fetch")async def fetch_url(request: Request):data=await request.json()6 unmodified linesthreading.Thread(target=do_fetch, args=(job_id, url), daemon=True).start()return {"job_id":job_id,"status":"Started"}@app.get("/fetch/progress")async def fetch_progress(job_id: str):return jobs.get(job_id, {"status":"Unknown job","pct":0})123416 unmodified lines212223242526271 unmodified line2930313233343536373839404142434445464748495051525320 unmodified lines747576777879808182838485868788899091929394959697989910059 unmodified lines1601611621631641658 unmodified lines1741751761771781794 unmodified lines18418518618718818949 unmodified lines2392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473486 unmodified lines355356357358359360361362363364365366367368369370371372import os, uuid, re, shutil, traceback, time, subprocess, jsonfrom fastapi import FastAPI, UploadFile, File, Requestfrom fastapi.responses import HTMLResponse, JSONResponsefrom huggingface_hub import batch_bucket_files16 unmodified lines#progress{width:100%;height:24px;background:#e5e7eb;border-radius:12px;overflow:hidden;margin:12px 0;display:none}#bar{height:100%;width:0%;background:#3b82f6;transition:width 0.3s}#log{white-space:pre-wrap;background:#1e293b;color:#e2e8f0;padding:12px;border-radius:8px;max-height:300px;overflow:auto}input[type=text]{width:75%;padding:10px;border:1px solid #cbd5e1;border-radius:8px}button{background:#3b82f6;color:white;border:0;padding:10px 18px;border-radius:8px;cursor:pointer}button:hover{background:#2563eb}</style>1 unmodified line<body><h1>📤 ULP → Private Bucket <code>kovinape/ulp-bucket</code></h1><div class="card"><h3>1. Upload .txt from PC</h3><div class="drop" id="drop">Drop .txt here or click<br><small>100GB, 5GB shards, private bucket</small><input type="file" id="file" accept=".txt" style="display:none"></div><div id="progress"><div id="bar"></div></div><div id="status"></div></div><div class="card"><h3>2. Fetch from Link (direct, no VPS)</h3><input type="text" id="url" placeholder="https://cdn2.linkforge.dpdns.org/download/AgADLg143789" style="width:75%"><button onclick="fetchLink()">Fetch → Bucket</button><div id="fetchStatus" style="margin-top:10px"></div><div id="fetchBar" style="width:100%;height:24px;background:#e5e7eb;border-radius:12px;overflow:hidden;margin:10px 0;display:none"><div id="fetchBarInner" style="height:100%;width:0%;background:#10b981;transition:width 0.3s"></div></div></div><div class="card"><h3>3. Fetch from GoFile (direct to bucket)</h3><input type="text" id="gofile" placeholder="https://gofile.io/d/oF3BUlMO" style="width:75%"><button onclick="fetchGofile()">Fetch GoFile → Bucket</button><div id="gofileStatus" style="margin-top:10px"></div><div id="gofileBar" style="width:100%;height:24px;background:#e5e7eb;border-radius:12px;overflow:hidden;margin:10px 0;display:none"><div id="gofileBarInner" style="height:100%;width:0%;background:#ff6b35;transition:width 0.3s"></div></div></div><pre id="log"></pre><script>const drop=document.getElementById('drop'), fileInput=document.getElementById('file'), bar=document.getElementById('bar'), progress=document.getElementById('progress'), status=document.getElementById('status'), log=document.getElementById('log');20 unmodified linesasync function fetchLink(){const url=document.getElementById('url').value.trim();if(!url){alert('Paste a URL');return;}document.getElementById('fetchStatus').textContent='🔗 Fetching → bucket...';document.getElementById('fetchBar').style.display='block';const res=await fetch('/fetch', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({url})});const data=await res.json();if(data.job_id){ poll(data.job_id,'fetch'); } else { document.getElementById('fetchStatus').textContent=JSON.stringify(data); }}async function fetchGofile(){const url=document.getElementById('gofile').value.trim();if(!url){alert('Paste GoFile URL');return;}document.getElementById('gofileStatus').textContent='🔗 Resolving GoFile...';document.getElementById('gofileBar').style.display='block';const res=await fetch('/fetch/gofile', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({url})});const data=await res.json();if(data.job_id){ poll(data.job_id,'gofile'); } else { document.getElementById('gofileStatus').textContent=JSON.stringify(data); }}async function poll(job_id,type='fetch'){const bar=document.getElementById(type=='gofile'?'gofileBarInner':'fetchBarInner'), st=document.getElementById(type=='gofile'?'gofileStatus':'fetchStatus');const iv=setInterval(async()=>{const r=await fetch('/fetch/progress?job_id='+job_id);const j=await r.json();st.textContent=j.status+ (j.pct?` ${j.pct}%`:'');if(j.pct) bar.style.width=j.pct+'%';if(j.status.includes('Done')||j.status.includes('Failed')) clearInterval(iv);},1000);59 unmodified linestry:tmp_base=f"/tmp/fetch_{job_id}"os.makedirs(tmp_base, exist_ok=True)orig_url=urlif "mediafire.com/file/" in url:try:8 unmodified linesfname=url.split("/")[-1].split("?")[0] or orig_url.split("/")[-1].split("?")[0] or "fetched.txt"fname=re.sub(r'[^A-Za-z0-9._ -]', '_', fname)[:80] or "fetched.txt"if not fname.endswith(".txt"): fname+=".txt"try:import requestsh=requests.head(url, allow_redirects=True, timeout=10)4 unmodified linesexcept: passtmp_path=os.path.join(tmp_base, fname)jobs[job_id]={"status":f"Downloading {fname}...","pct":5}try:cmd=["aria2c","-x","16","-s","16","-k","1M","-o",tmp_path,url,"--allow-overwrite=true","--auto-file-renaming=false","--console-log-level=warn"]proc=subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)49 unmodified linestraceback.print_exc()jobs[job_id]={"status":f"Failed: {e}","pct":0}def do_gofile(job_id, url):import hashlib, json as jsjobs[job_id]={"status":"Resolving GoFile...","pct":2}try:m=re.search(r"gofile\.io/d/([A-Za-z0-9-]+)", url)if not m:jobs[job_id]={"status":"Invalid GoFile URL","pct":0}; returncontent_id=m.group(1)GOFILE_UA="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"GOFILE_LANG="en-US"GOFILE_SALT="12af056dacea0b"def website_token(acc, offset=0):import hashlib as hl, time as tmwindow=int(tm.time()//14400)+offsetraw=f"{GOFILE_UA}::{GOFILE_LANG}::{acc}::{window}::{GOFILE_SALT}"return hl.sha256(raw.encode()).hexdigest()# guest tokenout=subprocess.run(["curl","-sS","-X","POST","https://api.gofile.io/accounts","-H",f"User-Agent: {GOFILE_UA}","-H","Origin: https://gofile.io","-d",""], capture_output=True, text=True, timeout=30)token=(js.loads(out.stdout).get("data",{}) or {}).get("token")if not token:jobs[job_id]={"status":"No guest token","pct":0}; returnjobs[job_id]={"status":"Guest token ok, resolving...","pct":10}def contents(acc, off, cid):cmd=["curl","-sS","-G",f"https://api.gofile.io/contents/{cid}","-H",f"Authorization: Bearer {acc}","-H",f"X-Website-Token: {website_token(acc,off)}","-H",f"X-BL: {GOFILE_LANG}","-H",f"User-Agent: {GOFILE_UA}","-H","Accept: */*","-H","Origin: https://gofile.io","-H","Referer: https://gofile.io/","--data-urlencode","contentFilter=","--data-urlencode","page=1","--data-urlencode","pageSize=1000","--data-urlencode","sortField=createTime","--data-urlencode","sortDirection=-1"]out=subprocess.run(cmd, capture_output=True, text=True, timeout=30)return js.loads(out.stdout)def collect(acc, off, cid):out=contents(acc, off, cid)st=out.get("status")if st=="error-notPremium" and off==0:out=contents(acc,-1,cid); st=out.get("status")if st!="ok": return None, f"gofile: {st}"d=out.get("data",{}) or {}if d.get("type")=="file" or d.get("link"):return [(d.get("name") or "gofile_file.txt", int(d.get("size") or 0), d.get("link") or "")], Noneentries=[]for child_id,c in (d.get("children") or {}).items():if c.get("type")=="folder":sub,err=collect(acc,off,child_id)if err: return None, errentries.extend(sub)elif c.get("type")=="file":entries.append((c.get("name") or "gofile_file.txt", int(c.get("size") or 0), c.get("link") or ""))return entries, Nonefiles,err=None,Nonefor off in (0,-1):files,err=collect(token,off,content_id)if files is not None and not err: breakif not files:jobs[job_id]={"status":f"Failed: {err or 'no files'}","pct":0}; returnfiles=[(n,s,u) for n,s,u in files if u]total=len(files)jobs[job_id]={"status":f"Found {total} file(s), downloading...","pct":15}for idx,(fname_raw,fsize_b,dl_url) in enumerate(files,1):fname=re.sub(r'[^A-Za-z0-9._ -]', '_', fname_raw)[:80] or f"gofile_{idx}.txt"tmp_base=f"/tmp/gofile_{job_id}_{idx}"os.makedirs(tmp_base, exist_ok=True)tmp_path=os.path.join(tmp_base, fname)cmd=["curl","-sS","-L","-o",tmp_path,dl_url,"-H",f"Cookie: accountToken={token}","-H",f"User-Agent: {GOFILE_UA}","-H","Referer: https://gofile.io/"]proc=subprocess.Popen(cmd)while proc.poll() is None:try:cur=os.path.getsize(tmp_path) if os.path.exists(tmp_path) else 0pct=15+ int((idx-1)/total*70 + (cur/max(1,fsize_b))*70/total) if fsize_b else 15+int((idx-1)/total*70)jobs[job_id]={"status":f"Downloading {idx}/{total} {fname} {cur//1024//1024}MB/{fsize_b//1024//1024}MB","pct":pct}except: passtime.sleep(1)if proc.returncode!=0 or not os.path.exists(tmp_path) or os.path.getsize(tmp_path)==0:jobs[job_id]={"status":f"Failed {fname}","pct":0}; continuesize=os.path.getsize(tmp_path)if size <= SHARD_SIZE:batch_bucket_files(BUCKET_ID, add=[(tmp_path, fname)])else:with open(tmp_path,"rb") as fh:part=0while True:chunk_path=f"{tmp_path}.part{part:03d}"with open(chunk_path,"wb") as out:written=0while written < SHARD_SIZE:data=fh.read(4*1024*1024)if not data: breakout.write(data)written+=len(data)if written==0:try: os.remove(chunk_path)except: passbreakif not os.path.exists(chunk_path) or os.path.getsize(chunk_path)==0: breakhf_name=f"{os.path.splitext(fname)[0]}_part{part:03d}.txt"batch_bucket_files(BUCKET_ID, add=[(chunk_path, hf_name)])try: os.remove(chunk_path)except: passpart+=1if fh.tell()>=size: breaktry: os.remove(tmp_path)except: passtry: shutil.rmtree(tmp_base)except: passjobs[job_id]={"status":f"Done — {total} file(s) → bucket","pct":100}except Exception as e:traceback.print_exc()jobs[job_id]={"status":f"Failed: {e}","pct":0}@app.post("/fetch")async def fetch_url(request: Request):data=await request.json()6 unmodified linesthreading.Thread(target=do_fetch, args=(job_id, url), daemon=True).start()return {"job_id":job_id,"status":"Started"}@app.post("/fetch/gofile")async def fetch_gofile(request: Request):data=await request.json()url=data.get("url","").strip()if not url or "gofile.io" not in url:return JSONResponse({"status":"error","error":"Invalid GoFile URL"}, status_code=400)job_id=uuid.uuid4().hex[:8]jobs[job_id]={"status":"Queued GoFile...","pct":0}import threadingthreading.Thread(target=do_gofile, args=(job_id, url), daemon=True).start()return {"job_id":job_id,"status":"Started"}@app.get("/fetch/progress")async def fetch_progress(job_id: str):return jobs.get(job_id, {"status":"Unknown job","pct":0})
app.py+142-13