"""Small evidence-led batch: two exact metadata queries and at most five replays. Stop all Wayback work on HTTP429; no alternate host/IP, proxy or limit bypass. """ from pathlib import Path from urllib.parse import urlencode from bs4 import BeautifulSoup import sys,json,time,re sys.path.insert(0,str(Path(__file__).parent)) from fetch import fetch P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';RAW=D/'raw';flag=RAW/'wayback-rate-limit.json' leads=[dict(key='topic196',url='http://www.videoreg.ru/forum/viewtopic.php?t=196',title='Применение доказательств',why='Exact Semrush83 target; actual recovered forumf2 listing supplies same technical/legal topic title, no body invented.',replays=['https://web.archive.org/web/2012id_/http://www.videoreg.ru:80/forum/viewtopic.php?t=196','https://web.archive.org/web/2009id_/http://videoreg.ru:80/forum/viewtopic.php?t=196']),dict(key='product138',url='http://www.videoreg.ru/shop/index.php?productID=138',title='СВК-005',why='Exact Semrush83 target; recovered category79 links this model/card. Category summary does not prove full product body.',replays=['https://web.archive.org/web/2009id_/http://www.videoreg.ru:80/shop/index.php?productID=138','https://web.archive.org/web/2012id_/http://videoreg.ru:80/shop/index.php?productID=138']),dict(key='svk007-hyphen-zip',url='http://videoreg.ru/download/doc/svk-007-instr.zip',title='svk-007-instr.zip',why='Actual resourceCDX20160914115702 and original document link. Differently named underscore manual is not assumed identical.',replays=['https://web.archive.org/web/20160914115702id_/http://videoreg.ru/download/doc/svk-007-instr.zip'])] requests=[] def bounded(url,name): if flag.exists():raise RuntimeError('Wayback429 stop marker exists; no further calls on this IP.') r=fetch(url,name,90);requests.append(r) if r['httpStatus']=='429': headers=(P/r['raw']).with_suffix(Path(r['raw']).suffix+'.headers').read_text(errors='replace');retry=re.findall(r'(?im)^retry-after:\s*(.*)$',headers);flag.write_text(json.dumps(dict(url=url,observedAt=r['checkedAt'],retryAfterRaw=retry,action='Stop all Wayback requests on currentIP; no bypass'),indent=2)+'\n');raise RuntimeError('HTTP429; stopped whole Wayback batch.') time.sleep(2) return r result=dict(scope='3actualcontent/documenttargets; no bulkuniformretry',leads=leads,requests=requests,acceptedNewBodies=[]) try: for lead in leads[:2]: u='https://web.archive.org/cdx/search/cdx?'+urlencode(dict(url=lead['url'],output='json',collapse='digest',filter='statuscode:200',fl='timestamp,original,mimetype,statuscode,digest,length')) bounded(u,'priority83-'+lead['key']+'-cdx.json') for lead in leads: lead['attempts']=[] for i,u in enumerate(lead['replays']): r=bounded(u,f'priority83-{lead["key"]}-{i}.bin');lead['attempts'].append(r) if r['curlExit']==0 and r['httpStatus']=='200' and r['bytes']>500: f=P/r['raw'] if lead['key']=='svk007-hyphen-zip': import zipfile try: with zipfile.ZipFile(f) as z: valid=z.testzip() is None;lead['members']=z.namelist() if valid:lead['candidateRaw']=r['raw'];lead['candidateKind']='validated ZIP, members require full content review';break except Exception as e:lead['validationError']=str(e) else: s=BeautifulSoup(f.read_bytes().decode('cp1251',errors='replace'),'html.parser');text=s.get_text(' ',strip=True) lead['returnedTitle']=s.title.get_text(' ',strip=True) if s.title else None;lead['bodyChars']=len(text) if len(text)>1000 and not re.search('wayback machine|not found|cannot be crawled|too many requests|just a moment',text,re.I):lead['candidateRaw']=r['raw'];lead['candidateKind']='HTML candidate requiring actual full body review';break except Exception as e:result['stopped']=str(e) (D/'semrush/priority83-recovery-batch.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print('BATCH',[(r['httpStatus'],r['bytes'],r['curlExit']) for r in requests],result.get('stopped',''))