#!/usr/bin/env python3 """ Repair the asset set of the local mirror. Stage 1 re-download every referenced image that is missing or corrupt, keeping only responses that really are images (the busy Wayback endpoint happily returns HTML error pages with a 404 status). Stage 2 rebuild the handful of images that were NEVER archived from the artwork that surrounds them on the page. """ import io import shutil import time import urllib.error import urllib.request from pathlib import Path from PIL import Image ROOT = Path(__file__).resolve().parent MIRROR = ROOT / "norbourg-2002" IMAGES = MIRROR / "images" TS = "20020929201450" UA = "Mozilla/5.0 (X11; Linux x86_64) norbourg-mirror/1.1" MAGIC = (b"GIF8", b"\x89PNG", b"\xff\xd8", b"BM") def valid_image(path): try: with Image.open(path) as im: im.verify() return path.stat().st_size > 20 except Exception: # noqa: BLE001 return False def referenced(): names = set() for p in list(MIRROR.glob("*.html")) + list(MIRROR.glob("*.css")): text = p.read_bytes().decode("latin-1") for line in text.split("images/")[1:]: name = "" for ch in line: if ch.isalnum() or ch in "._-": name += ch else: break if name.lower().endswith((".gif", ".jpg", ".jpeg", ".png")): names.add(name) return names def fetch(name, tries=3): url = f"http://web.archive.org/web/{TS}id_/http://norbourg.com/images/{name}" for attempt in range(tries): try: req = urllib.request.Request(url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=60) as r: data = r.read() ctype = r.headers.get("Content-Type", "") if data[:4] in MAGIC and "html" not in ctype: return data return None # a capture exists but it is a 404 page except urllib.error.HTTPError as e: if e.code in (404, 403): return None time.sleep(4 * (attempt + 1)) except Exception: # noqa: BLE001 time.sleep(5 * (attempt + 1)) return None def tile_from_caps(top, bottom, height=8): """Rebuild a 533px content-body tile from its top/bottom caps.""" im = Image.open(top).convert("RGB") w = im.size[0] out = Image.new("RGB", (w, height)) px = out.load() for x in range(w): px[x, height - 1] = im.getpixel((x, im.size[1] - 1)) px[x, 0] = im.getpixel((x, im.size[1] - 1)) for y in range(height): for x in range(w): px[x, y] = im.getpixel((x, im.size[1] - 1)) return out def main(): names = referenced() missing = [n for n in sorted(names) if not (IMAGES / n).is_file()] corrupt = [n for n in sorted(names) if (IMAGES / n).is_file() and not valid_image(IMAGES / n)] print(f"{len(names)} referenced images, {len(missing)} missing, {len(corrupt)} corrupt") recovered = [] for name in missing + corrupt: data = fetch(name) if data: (IMAGES / name).write_bytes(data) recovered.append(name) print(f" recovered {name} ({len(data)} B)") time.sleep(2) print(f"recovered {len(recovered)}") # ---- stage 2: rebuild what the Archive never kept -------------------- rebuilt = [] def save(im, name): im.save(IMAGES / name, optimize=True) rebuilt.append(name) # body of the 533px content panels (33 pages) if not (IMAGES / "bg_mid_content.gif").is_file() or not valid_image(IMAGES / "bg_mid_content.gif"): save(tile_from_caps(IMAGES / "bg_top_content.gif", IMAGES / "bg_bottom_content.gif", 8), "bg_mid_content.gif") # left-menu backgrounds: the menu table itself is #DBE2EF for name in ("men_nb_bg.gif", "men_el_bg.gif", "men_as_bg.gif", "men_ma_bg.gif", "men_nb_ca_bg.gif", "str_arc_bg.gif"): if (IMAGES / name).is_file() and valid_image(IMAGES / name): continue save(Image.new("RGB", (155, 8), (219, 226, 239)), name) # header banner / bottom picture of the Cité du REER page if not (IMAGES / "cr_banner.gif").is_file() or not valid_image(IMAGES / "cr_banner.gif"): shutil.copyfile(IMAGES / "norbourg_com.gif", IMAGES / "cr_banner.gif") rebuilt.append("cr_banner.gif") if not (IMAGES / "cr_bottom_pic.gif").is_file() or not valid_image(IMAGES / "cr_bottom_pic.gif"): src = Image.open(IMAGES / "nb_pic_bottom.gif").convert("RGB") w, h = src.size src.crop((0, (h - 40) // 2, w, (h - 40) // 2 + 40)).save(IMAGES / "cr_bottom_pic.gif") rebuilt.append("cr_bottom_pic.gif") # monthly Strategia banners: reuse the nearest captured month for name, donor in (("str_jul_02.gif", "stra_ban_0702.gif"), ("stra_ban_0602.gif", "stra_ban_0702.gif")): if not (IMAGES / name).is_file() or not valid_image(IMAGES / name): shutil.copyfile(IMAGES / donor, IMAGES / name) rebuilt.append(name) print(f"rebuilt {len(rebuilt)}: {', '.join(rebuilt)}") still = [n for n in names if not (IMAGES / n).is_file() or not valid_image(IMAGES / n)] print(f"still unavailable ({len(still)}): {', '.join(sorted(still))}") if __name__ == "__main__": main()