Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
|
@@ -42,6 +42,50 @@ def log_failure(path, reason):
|
|
| 42 |
with open(path, "a") as f:
|
| 43 |
f.write(reason + "\n")
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
def download_image(url, out_path, fail_log, code, suf):
|
| 46 |
def log(msg):
|
| 47 |
with open(fail_log, "a") as f:
|
|
|
|
| 42 |
with open(path, "a") as f:
|
| 43 |
f.write(reason + "\n")
|
| 44 |
|
| 45 |
+
def download_image_fast(url, out_path, fail_log, code, suf):
|
| 46 |
+
import requests, cloudscraper
|
| 47 |
+
from urllib.parse import urlparse
|
| 48 |
+
|
| 49 |
+
def log(msg):
|
| 50 |
+
with open(fail_log, "a") as f:
|
| 51 |
+
f.write(f"{code}{suf}: {msg}\n")
|
| 52 |
+
|
| 53 |
+
headers = {
|
| 54 |
+
"User-Agent": random.choice(USER_AGENTS),
|
| 55 |
+
"Referer": urlparse(url).netloc,
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
# 1) Quick requests pass
|
| 59 |
+
try:
|
| 60 |
+
r = requests.get(url, headers=headers, timeout=5, stream=True)
|
| 61 |
+
r.raise_for_status()
|
| 62 |
+
if "image" in r.headers.get("Content-Type", "").lower():
|
| 63 |
+
with open(out_path, "wb") as f:
|
| 64 |
+
for chunk in r.iter_content(8192):
|
| 65 |
+
f.write(chunk)
|
| 66 |
+
return True
|
| 67 |
+
log(f"requests non-image: {r.headers.get('Content-Type')}")
|
| 68 |
+
except Exception as e:
|
| 69 |
+
log(f"requests error: {e}")
|
| 70 |
+
|
| 71 |
+
# 2) cloudscraper fallback
|
| 72 |
+
try:
|
| 73 |
+
scr = cloudscraper.create_scraper(browser={"browser":"chrome","platform":"windows"})
|
| 74 |
+
r = scr.get(url, headers=headers, timeout=10, stream=True)
|
| 75 |
+
r.raise_for_status()
|
| 76 |
+
if "image" in r.headers.get("Content-Type", "").lower():
|
| 77 |
+
with open(out_path, "wb") as f:
|
| 78 |
+
for chunk in r.iter_content(8192):
|
| 79 |
+
f.write(chunk)
|
| 80 |
+
return True
|
| 81 |
+
log(f"cloudscraper non-image: {r.headers.get('Content-Type')}")
|
| 82 |
+
except Exception as e:
|
| 83 |
+
log(f"cloudscraper error: {e}")
|
| 84 |
+
|
| 85 |
+
log("download failed")
|
| 86 |
+
return False
|
| 87 |
+
|
| 88 |
+
|
| 89 |
def download_image(url, out_path, fail_log, code, suf):
|
| 90 |
def log(msg):
|
| 91 |
with open(fail_log, "a") as f:
|