Bubbles30 commited on
Commit
d3e5840
·
verified ·
1 Parent(s): df88c95

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -84
app.py CHANGED
@@ -45,64 +45,59 @@ def log_failure(path, reason):
45
  import requests, cloudscraper
46
  from urllib.parse import quote, urlparse
47
 
 
 
48
  def download_image_fast(url, out_path, fail_log, code, suf):
49
- """
50
- 1) Encode the URL for safe HTTP requests
51
- 2) Try a short requests.get
52
- 3) If that fails, try a short cloudscraper.get
53
- 4) Log *every* status/exception so nothing is silent
54
- """
55
  def log(msg):
56
  with open(fail_log, "a") as f:
57
- f.write(f"{code}{suf}: {msg}\\n")
58
 
59
- # 1) URL‑encode (spaces, parens, etc.)
60
- # Keep scheme and netloc intact, encode path+query
61
- parts = urlparse(url)
62
- safe_path = quote(parts.path + ("?"+parts.query if parts.query else ""),
63
- safe="/?=&%")
64
  safe_url = f"{parts.scheme}://{parts.netloc}{safe_path}"
 
 
65
 
66
- headers = {
67
- "User-Agent": random.choice(USER_AGENTS),
68
- "Referer": parts.netloc,
69
- }
70
-
71
- # 2) Try plain requests
72
  try:
73
- r = requests.get(safe_url, headers=headers,
74
- timeout=8, stream=True, allow_redirects=True)
 
 
 
 
 
 
75
  log(f"requests status={r.status_code}")
76
  r.raise_for_status()
77
- ct = r.headers.get("Content-Type","")
78
- if "image" in ct.lower():
79
  with open(out_path, "wb") as f:
80
- for chunk in r.iter_content(16384):
81
  f.write(chunk)
82
  return True
83
- log(f"requests non-image: {ct}")
84
  except Exception as e:
85
  log(f"requests error: {e}")
86
 
87
- # 3) cloudscraper fallback
88
  try:
89
  scr = cloudscraper.create_scraper(
90
- browser={"browser":"chrome","platform":"windows"})
91
- r = scr.get(safe_url, headers=headers,
92
- timeout=8, stream=True, allow_redirects=True)
 
 
93
  log(f"cloudscraper status={r.status_code}")
94
  r.raise_for_status()
95
- ct = r.headers.get("Content-Type","")
96
- if "image" in ct.lower():
97
  with open(out_path, "wb") as f:
98
- for chunk in r.iter_content(16384):
99
  f.write(chunk)
100
  return True
101
- log(f"cloudscraper non-image: {ct}")
102
  except Exception as e:
103
  log(f"cloudscraper error: {e}")
104
 
105
- # 4) All failed
106
  log("download failed for all methods")
107
  return False
108
 
@@ -292,79 +287,52 @@ def read_links_from_workbook(path):
292
 
293
  # === Batch & Single Handlers ===
294
 
295
- def handle_batch(workbook_path, fmt, w, h):
296
- if workbook_path is None:
297
- return [], None, '❌ Upload a workbook first.'
298
- tmpdir = tempfile.mkdtemp()
299
- outdir = os.path.join(tmpdir, 'out'); os.makedirs(outdir, exist_ok=True)
300
- fail_log = os.path.join(tmpdir, 'failed.txt')
301
 
302
- try:
303
- jobs = read_links_from_workbook(workbook_path.name)
304
- except Exception as e:
305
- shutil.rmtree(tmpdir)
306
- return [], None, f'❌ Read error: {e}'
307
- if not jobs:
308
- shutil.rmtree(tmpdir)
309
- return [], None, '❌ No URLs found.'
310
 
311
- tasks = []
312
- for code, url, _ in jobs:
313
- idx = sum(1 for t in tasks if t[0] == code)
314
- suf = f"_{idx}" if idx else ''
315
- ext_in = os.path.splitext(urlparse(url).path)[1] or '.jpg'
316
- dl_path = os.path.join(outdir, f"{code}{suf}{ext_in}")
317
- tasks.append((code, url, dl_path, suf))
318
-
319
- # Download with tracking
320
  future_to_task = {}
321
  with ThreadPoolExecutor(max_workers=min(32, CPU_CORES*2)) as ex:
322
- # submit each download job *and* remember its (code, suf)
323
  for code, url, dl_path, suf in tasks:
324
  fut = ex.submit(download_image_fast, url, dl_path, fail_log, code, suf)
325
- future_to_task[fut] = (code, suf)
326
 
327
- # as each future finishes, look up its metadata
328
  for fut in as_completed(future_to_task):
329
  success = fut.result()
330
- code, suf = future_to_task[fut]
331
  if not success:
332
  log_failure(fail_log, f"{code}{suf}: download failed")
 
333
  processed = []
334
  for code, url, dl_path, suf in tasks:
335
- if not os.path.exists(dl_path): continue
 
336
  try:
337
- img = Image.open(dl_path)
338
- final = resize_and_pad(img, max_size=w)
339
-
340
- out_filename = f"{code}{suf}{('.jpg' if fmt.upper()=='JPEG' else f'.{fmt.lower()}')}"
341
- out_path = os.path.join(outdir, out_filename)
342
 
343
  if fmt.upper() == "JPEG":
344
- final_jpg = flatten_and_pad(final, target=w) # flatten+pad
 
345
  final_jpg.save(
346
- out_path,
347
- "JPEG",
348
- quality=95, # high‑quality
349
- optimize=True, # run Huffman optimization
350
- progressive=True, # progressive JPEG
351
- subsampling=0 # no chroma subsampling
352
  )
353
  else:
354
- final.save(out_path, fmt.upper())
355
- processed.append(out_path)
 
356
  except Exception as e:
357
  log_failure(fail_log, f"{code}{suf}: process error: {e}")
358
 
359
- total, done = len(tasks), len(processed)
360
- msg = f"✅ Batch fetched: {total}, processed: {done}, failed: {total-done}."
361
-
362
- zip_path = os.path.join(tmpdir, f"batch_{datetime.now():%Y%m%d_%H%M%S}.zip")
363
- with zipfile.ZipFile(zip_path,'w') as zf:
364
- for p in processed: zf.write(p, os.path.basename(p))
365
- if os.path.exists(fail_log): zf.write(fail_log, os.path.basename(fail_log))
366
-
367
- return processed, zip_path, msg
368
 
369
  def handle_single_upload(uploaded_file, fmt, w, h):
370
  if not uploaded_file: return None, None, "❌ No file."
 
45
  import requests, cloudscraper
46
  from urllib.parse import quote, urlparse
47
 
48
+ from urllib.parse import urlparse, quote
49
+
50
  def download_image_fast(url, out_path, fail_log, code, suf):
 
 
 
 
 
 
51
  def log(msg):
52
  with open(fail_log, "a") as f:
53
+ f.write(f"{code}{suf}: {msg}\n")
54
 
55
+ parts = urlparse(url)
56
+ safe_path = quote(parts.path + (f"?{parts.query}" if parts.query else ""), safe="/?=&%")
 
 
 
57
  safe_url = f"{parts.scheme}://{parts.netloc}{safe_path}"
58
+ referer = f"{parts.scheme}://{parts.netloc}/"
59
+ headers = random_headers(referer)
60
 
61
+ # 1) Try plain requests (no SSL verify)
 
 
 
 
 
62
  try:
63
+ r = requests.get(
64
+ safe_url,
65
+ headers=headers,
66
+ timeout=15,
67
+ stream=True,
68
+ allow_redirects=True,
69
+ verify=False,
70
+ )
71
  log(f"requests status={r.status_code}")
72
  r.raise_for_status()
73
+ if "image" in r.headers.get("Content-Type", "").lower():
 
74
  with open(out_path, "wb") as f:
75
+ for chunk in r.iter_content(16_384):
76
  f.write(chunk)
77
  return True
78
+ log(f"requests non-image: {r.headers.get('Content-Type')}")
79
  except Exception as e:
80
  log(f"requests error: {e}")
81
 
82
+ # 2) cloudscraper fallback
83
  try:
84
  scr = cloudscraper.create_scraper(
85
+ browser={"browser": "chrome", "platform": "windows"}
86
+ )
87
+ r = scr.get(
88
+ safe_url, headers=headers, timeout=15, stream=True, allow_redirects=True
89
+ )
90
  log(f"cloudscraper status={r.status_code}")
91
  r.raise_for_status()
92
+ if "image" in r.headers.get("Content-Type", "").lower():
 
93
  with open(out_path, "wb") as f:
94
+ for chunk in r.iter_content(16_384):
95
  f.write(chunk)
96
  return True
97
+ log(f"cloudscraper non-image: {r.headers.get('Content-Type')}")
98
  except Exception as e:
99
  log(f"cloudscraper error: {e}")
100
 
 
101
  log("download failed for all methods")
102
  return False
103
 
 
287
 
288
  # === Batch & Single Handlers ===
289
 
290
+ from concurrent.futures import ThreadPoolExecutor, as_completed
 
 
 
 
 
291
 
292
+ def handle_batch(…):
293
+ # … read jobs, build `tasks` list …
 
 
 
 
 
 
294
 
 
 
 
 
 
 
 
 
 
295
  future_to_task = {}
296
  with ThreadPoolExecutor(max_workers=min(32, CPU_CORES*2)) as ex:
 
297
  for code, url, dl_path, suf in tasks:
298
  fut = ex.submit(download_image_fast, url, dl_path, fail_log, code, suf)
299
+ future_to_task[fut] = (code, url, dl_path, suf)
300
 
 
301
  for fut in as_completed(future_to_task):
302
  success = fut.result()
303
+ code, url, dl_path, suf = future_to_task[fut]
304
  if not success:
305
  log_failure(fail_log, f"{code}{suf}: download failed")
306
+
307
  processed = []
308
  for code, url, dl_path, suf in tasks:
309
+ if not os.path.exists(dl_path):
310
+ continue
311
  try:
312
+ img = Image.open(dl_path)
313
+ final = resize_and_pad(img, max_size=w)
314
+ out_fn = f"{code}{suf}{'.jpg' if fmt=='JPEG' else f'.{fmt.lower()}'}"
315
+ out_p = os.path.join(outdir, out_fn)
 
316
 
317
  if fmt.upper() == "JPEG":
318
+ # <-- make sure this matches your helper’s name!
319
+ final_jpg = flatten_threshold(final, target=w)
320
  final_jpg.save(
321
+ out_p,
322
+ "JPEG",
323
+ quality=95,
324
+ optimize=True,
325
+ progressive=True,
326
+ subsampling=0,
327
  )
328
  else:
329
+ final.save(out_p, fmt.upper())
330
+
331
+ processed.append(out_p)
332
  except Exception as e:
333
  log_failure(fail_log, f"{code}{suf}: process error: {e}")
334
 
335
+ # … zip up & return …
 
 
 
 
 
 
 
 
336
 
337
  def handle_single_upload(uploaded_file, fmt, w, h):
338
  if not uploaded_file: return None, None, "❌ No file."