from pathlib import Path from urllib.parse import urlsplit,urljoin import sys,json,hashlib,concurrent.futures from bs4 import BeautifulSoup sys.path.insert(0,str(Path(__file__).parent));from fetch import fetch P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';R=D/'raw';data=json.loads((D/'sample-gallery-inventory.json').read_text());cdx=json.loads((R/'cdx-narod-samples.json').read_text());album_paths=sorted({urlsplit(r[2]).path for r in cdx[1:] if r[3]=='text/html' and ('photoalbum' in r[2] or 'povorot.html' in r[2])}) for path in album_paths: for base in ['http://videoreg-samples.narod.ru','https://web.archive.org/web/2008id_/http://www.videoreg-samples.narod.ru:80']: url=base+path;rec=fetch(url,'gallery/alternate-'+hashlib.sha256(url.encode()).hexdigest()[:16]+'.html',20) if rec['httpStatus']=='200' and rec['bytes']>300: raw=(P/rec['raw']).read_bytes();s=BeautifulSoup(raw,'html.parser') if any(a.get('href','').lower().endswith('.jpg') for a in s.find_all('a')): album=dict(url='http://videoreg-samples.narod.ru'+path,raw=rec['raw'],title=s.title.get_text(' ',strip=True) if s.title else '',text=s.get_text(' ',strip=True),images=[]) for tag in s.find_all(['a','img']): value=tag.get('href') if tag.name=='a' else tag.get('src');u=urlsplit(urljoin(album['url'],value or '')) if u.hostname and u.hostname.endswith('videoreg-samples.narod.ru') and u.path.lower().endswith('.jpg'):album['images'].append(u.path) album['images']=list(dict.fromkeys(album['images']));data['albums'].append(album);break images={i['path']:i for i in data['images']} for a in data['albums']: for path in a['images']:images.setdefault(path,dict(path=path,url='http://videoreg-samples.narod.ru'+path,fetchStatus='pending',rawFile=None)) records={urlsplit(r[2]).path:r for r in cdx[1:] if r[3]=='image/jpeg' and '/.s/' not in r[2]} def work(i): if i['fetchStatus']=='downloaded-unreviewed':return urls=['https://videoreg-samples.narod.ru'+i['path']] if i['path'] in records:urls.append('https://web.archive.org/web/2008id_/http://videoreg-samples.narod.ru:80'+i['path']) for url in urls: name='gallery/retry-'+hashlib.sha256(url.encode()).hexdigest()[:18]+'.jpg';rec=fetch(url,name,20) if rec['httpStatus']=='200' and (P/rec['raw']).read_bytes().startswith(b'\xff\xd8\xff'): i.update(fetchStatus='downloaded-unreviewed',rawFile=rec['raw'],sha256=rec['sha256'],bytes=rec['bytes']);return i['fetchStatus']='unresolved' with concurrent.futures.ThreadPoolExecutor(max_workers=2) as ex:list(ex.map(work,images.values())) data['images']=list(images.values());(D/'sample-gallery-inventory.json').write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n');print('ALTERNATE GALLERY',len(data['albums']),len(images),sum(i['fetchStatus']=='downloaded-unreviewed' for i in images.values()))