Files
videoreg.ru/scripts/rebuild-v2/inventory.py
T

106 lines
14 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from pathlib import Path
from urllib.parse import urlsplit,urljoin,parse_qsl,urlencode,unquote
import json,hashlib,re,collections,email.utils
from bs4 import BeautifulSoup
P=Path(__file__).resolve().parents[2];D=P/'docs/rebuild-v2';RAW=D/'raw'
plan=json.loads((D/'discovery-plan.json').read_text());by={x['normalizedPath']:x for x in plan}
articles=json.loads((P/'web-front/src/content/v2-articles.json').read_text())+json.loads((P/'web-front/src/content/v2-community.json').read_text())
routes=json.loads((P/'deploy/legacy-routes.json').read_text());content_dest={src:a['path'] for a in articles for src in a['sourcePaths'] if src.startswith('/')}
# Recovered full source cards take precedence over changed later category labels.
commercial={'/price.shtml':'Historic sale prices, installer promotions and phone numbers removed. Models retained in /system and /catalog.', '/where.shtml':'Historic dealer/contact advertisements, including unrelated casino/HVAC paid links; no original technical article body.', '/shop/index.php?aux_page=aux1':'Historic ordering instructions and sales contacts, no technical body.', '/shop/index.php?aux_page=aux2':'Historic payment/delivery/consumer-terms page; obsolete commerce/terms not republished as current advice.'}
source_outbound=[];new_leads={};raw_integrity=[]
def norm(url):
u=urlsplit(url);params=[(k,v) for k,v in parse_qsl(u.query) if k!='sid'];return u.path+('?' +urlencode(sorted(params)) if params else '')
def canonical(url):return urlsplit(url).hostname in ('videoreg.ru','www.videoreg.ru')
def actual_snapshot(file,fallback):
h=Path(str(file)+'.headers')
if h.exists():
m=re.findall(r'(?im)^memento-datetime:\s*(.+)$',h.read_text(errors='replace'))
if m:
try:return email.utils.parsedate_to_datetime(m[-1].strip()).strftime('%Y%m%d%H%M%S')
except:pass
return fallback
audit_plan=list(plan)
known_raw={x['rawFile'] for x in audit_plan}
for article in articles:
for raw_file in article['rawFiles']:
if raw_file.endswith('.html') and raw_file not in known_raw:
known_raw.add(raw_file)
original=next((p for p in article['sourcePaths'] if p.startswith('http')), 'http://www.videoreg.ru'+article['sourcePaths'][0] if article['sourcePaths'] else 'http://www.videoreg.ru/')
audit_plan.append(dict(normalizedPath=article['path'], originalUrl=original, rawFile=raw_file,snapshot=article['date'], reason=None))
for item in audit_plan:
f=P/item['rawFile']
if not (f.exists() and f.stat().st_size>500):continue
b=f.read_bytes();s=BeautifulSoup(b if '/gallery/' in str(f) or 'narod-' in str(f) else b.decode('cp1251',errors='replace'),'html.parser');item['_title']=s.title.get_text(' ',strip=True) if s.title else '';item['_text']=s.get_text(' ',strip=True);item['_sha']=hashlib.sha256(b).hexdigest();item['_actualSnapshot']=actual_snapshot(f,item['snapshot'])
for tag in s.find_all(True):
for attr in ['href','src','action','data','background']:
value=tag.get(attr)
if not isinstance(value,str) or not value.strip():continue
absolute=urljoin(item['originalUrl'],value)
context=' '.join(tag.get_text(' ',strip=True).split())[:220] or tag.get('alt','') or tag.name+' '+attr
if canonical(absolute):
u=urlsplit(absolute);key=norm(absolute)
if key not in by and not re.search(r'\.(?:gif|jpe?g|png|avi|zip|pdf|css|ico|bin)$',u.path,re.I) and u.path!='/':
if any(x in u.path for x in ['.shtml','.html','.htm','.php']):lead=new_leads.setdefault(key,dict(originalUrl=absolute,foundOn=[],context=context));lead['foundOn'].append(item['normalizedPath'])
if lead['context'] in ['подробнее...','a href','link href','img src'] and context not in ['подробнее...','a href','link href','img src']:lead['context']=context
continue
if absolute.startswith('#'):continue
if value.lower().startswith('javascript:'):reason='Old script-driven template interaction; no archived JavaScript is executed or carried to the new site.'
elif absolute.startswith('mailto:'):reason='Old sales/support contact; not republished as an active contact.'
elif re.search('казино|тур|тайланд|psp|бассейн|ворзел|кондиционер|хостинг|дилер|магазин|купить|установить|автоюрист',context,re.I):reason='Advertising/sales/paid-link context individually identified in this anchor; unrelated to technical body.'
elif 'youtube' in absolute or 'rutube' in absolute or 'video.yandex' in absolute:reason='Original demonstration host: archived Flash/embed removed. Exact verified video links, when retained, are separately approved per published page and anchor in v2-link-approvals.json; playable video bytes not recovered.'
elif tag.name in ('script','iframe','embed','object') or 'counter' in absolute or 'stat' in absolute:reason='Remote runtime/embed/counter removed; no downloaded runtime is executed.'
elif 'phpbb' in absolute:reason='Historical forum engine footer removed; no phpBB runtime is published. Technical observations are paraphrased with source dates.'
else:reason='Reviewed in original context: old partner, press, hosted sample or template reference is not needed for the edited technical body; omitted instead of carrying an unverified external destination.'
source_outbound.append(dict(stage='raw-source',sourcePage=item['normalizedPath'],sourceFile=item['rawFile'],snapshot=item['_actualSnapshot'],element=tag.name,attribute=attr,context=context,destination=absolute,decision='remove-from-publication',reason=reason,reviewed=True,reviewer='root-v2-editorial'))
# A URL-shaped script literal is reviewed even when it is not an HTML attribute.
for tag in s.find_all(['script','style']):
for url in re.findall(r'https?://[^\s"\'<>);]+',tag.get_text()):
if not canonical(url):source_outbound.append(dict(stage='raw-inline',sourcePage=item['normalizedPath'],sourceFile=item['rawFile'],snapshot=item['_actualSnapshot'],element=tag.name,attribute='literal',context=tag.get_text()[:200],destination=url,decision='remove-from-publication',reason='Untrusted archived script/style literal; no archived scripts/styles imported.',reviewed=True,reviewer='root-v2-editorial'))
# Additional exact aliases proved by named post anchors/canonical topic links in recovered raw threads.
for key,dest in routes.items():
if key not in by:new_leads.setdefault(key,dict(originalUrl='http://www.videoreg.ru'+key,foundOn=['recovered canonical topic/post links or explicit equivalent routing'],context='Verified canonical/alias path'))
for src in content_dest:
if src not in by:new_leads.setdefault(src,dict(originalUrl='http://www.videoreg.ru'+src,foundOn=['recovered document link'],context='Original technical document'))
entries=[]
for key in sorted(set(by)|set(new_leads)):
item=by.get(key);lead=new_leads.get(key)
u=urlsplit(key);semantic=[(k,v) for k,v in parse_qsl(u.query) if not (k=='sid' or k=='start' and v=='0' or k=='postdays' and v=='0' or k=='postorder' and v=='asc' or k=='highlight' and not v)]
semanticKey=u.path+('?' +urlencode(sorted(semantic)) if semantic else '')
dest=content_dest.get(key) or routes.get(key) or routes.get(semanticKey)
f=P/item['rawFile'] if item else None;valid=bool(item and '_sha' in item)
reason=None;status='unresolved';action='Recover actual body; no generic substitute or inferred text from an anchor.';kind=item['type'] if item else 'linked-content-url'
if item and item['reason']:status='excluded-utility';reason=item['reason'];action='Not a historical content article.'
elif key in commercial:status='excluded-commercial';reason=commercial[key];action='Read full source, remove commerce/advertising; relevant model facts retained separately.'
elif dest:
if valid and key in content_dest:status='edited-recovered';action='Full recovered body read and edited into typed safe sections; advertisements removed.'
elif key=='/download/samples/zeiss_800_600_GPS_1.zip':status='partial-media-recovery';action='Original ZIP is truncated and unpublished. Four complete JPEG members validated by declared size/CRC and decoded locally; companion does not replace missing archive.'
elif key=='/download/svk-002-mn.pdf':status='recovered-document';action='Complete3page January2008 Mobile News SVK002 journal test, validated PDF and all pages read; original exact PDF available.'
elif key.startswith('/download/'):status='recovered-document';action='Validated original PDF extracted from original ZIP; complete document available.'
elif '/forum/index.php' in key:status='replacement-navigation';action='Read-only technical case navigation replaces obsolete interactive forum entry; missing topic bodies tracked individually.'
else:status='verified-equivalent';action='Mapped only through recovered same-page/section/canonical-post evidence; not counted as a newly recovered body.'
reason='Edited technical purpose retained; see per-page editorial ledger.'
elif item and key.startswith('/forum/viewforum.php') and valid:status='unresolved-listing';reason='Listing fetched and read; linked topics not all recovered, so not silently redirected to an incomplete body.'
elif 'mark=topics' in key:status='excluded-utility';reason='Mark-as-read interaction, not a content body.'
elif not item and any(x in key for x in ['/forum/login.php','/forum/profile.php','/forum/groupcp.php','/forum/search.php','/forum/memberlist.php','/forum/viewonline.php','/forum/posting.php','/forum/privmsg.php']):status='excluded-utility';reason='Linked authentication/profile/posting/search utility, not an original technical article.'
elif not item and '/shop/index.php' in key and not any(x in key for x in ['productID=','categoryID=']):status='excluded-utility';reason='Linked shop action, sort, cart, language or commercial utility; no original technical body.'
# Verify a linked original document by its actual extracted source, not HTTP200 alone.
title=item.get('_title') if item else (lead or {}).get('context')
entry=dict(originalUrl=item['originalUrl'] if item else lead['originalUrl'],normalizedPath=key,type=kind,chosenSnapshot=item.get('_actualSnapshot',item['snapshot']) if item and valid else None,requestedSnapshot=item.get('snapshot') if item else None,fetchStatus='validated-html-body' if valid else ('not-fetched-utility' if status.startswith('excluded') else 'unresolved'),rawFile=item['rawFile'] if valid else None,rawSha256=item.get('_sha') if item else None,title=title,rawVisibleTextChars=len(item.get('_text','')) if item else 0,currentDestination=dest,editorialAction=action,publicationStatus=status,exclusionOrUnresolvedReason=reason or 'No validated source body recovered after actual capture/version/URL attempts; restoration remains blocked.',discoveredFrom=(lead or {}).get('foundOn',[]))
entries.append(entry)
(D/'url-inventory.json').write_text(json.dumps(entries,ensure_ascii=False,indent=2)+'\n')
(D/'outbound-links.json').write_text(json.dumps(dict(scope='Every external HTML attribute and inline URL in all fetched source pages. Public-source/build/DOM stages appended by verification script.',links=source_outbound),ensure_ascii=False,indent=2)+'\n')
semrush=D/'semrush';semrush.mkdir(exist_ok=True)
(semrush/'recovery-questions.json').write_text(json.dumps(dict(domain='videoreg.ru',scope=['apex','www'],status='awaiting actual coordinator Noxtools/Semrush evidence; not inspected by domain executor',missing=[dict(path=x['normalizedPath'],url=x['originalUrl'],title=x['title'],source=x['discoveredFrom']) for x in entries if x['publicationStatus'].startswith('unresolved')],questions=['Lost backlink targets beyond the CDX/HTML link union?','Exact titles and context for predpr.shtml, moves.htm, law1.htm, law2.htm and unindexed product/topic paths?','Separate manufacturer technical pages from later casino/real-estate/SEO anchors.','Record database, report scope/date, limits and first/last-seen dates.'],currentKnownEvidence='CDX883HTMLcaptures;259allresourceURLkeys; body recovery recorded per URL; all distinct pre/post2015 versions tried on missing indexed content.'),ensure_ascii=False,indent=2)+'\n')
counts=collections.Counter(e['publicationStatus'] for e in entries);meaningful=[e for e in entries if not e['publicationStatus'].startswith('excluded')]
body_captures=sum('_sha'in x for x in plan)
text=f'''# Coverage V2 — known denominator, unresolved restoration\n\nCDX discovery: 883 HTML captures across 2007–2025; 121 collapsed HTML URL keys and 259 resource URL keys. Removing phpBB sid duplicates gives101 original normalized HTML URLs. Full CDX JSON has no resume key, so returned index is complete for the actual query (all883 originals were HTTP;528www and355apex; no HTTPS200 captures returned). Linked original URLs from every fetched body expand the known inventory. Unfetched bodies may contain further undiscovered links: this is a **known lower bound**, not a complete historical-site claim.\n\nKnown normalized URLs in inventory: **{len(entries)}**. Meaningful/non-utility denominator (including unresolved): **{len(meaningful)}**. Actual validated fetched HTML bodies: **{body_captures}** (includes commercial/navigation pages; not all are published articles). Publication dispositions:\n\n'''+''.join(f'- {k}: {v}\n' for k,v in sorted(counts.items()))+'''\nEach entry has URL/type/snapshot/raw hash/title/body size/destination/editorial action/status/reason in `url-inventory.json`. `edited-recovered` counts source URLs, not unique articles; canonical merges and verified equivalents are separate. Typed article pages include new HTML document companions whose complete original PDFs are available; counts must not be presented as16 historic HTML bodies.\n\nImportant unresolved items include missing historical topic bodies, original installation photographs, unrecovered video bytes and partial GPSsampleZIP. The January2008 SVK002 journal test PDF is now completely recovered (3pages). All alternative versions and URL variants actually attempted are in raw/requests.jsonl. These gaps and pending Semrush reconciliation remain mandatory V2 blockers. No historical article is synthesized from a backlink anchor/title. V1 modern guides/retail cards do not enter recovery counts.\n'''
(D/'coverage.md').write_text(text)
# Freeze successful source bytes in content-addressed files; retain original friendly filenames.
objects=RAW/'objects';objects.mkdir(exist_ok=True)
for f in list(RAW.rglob('*')):
if f.is_file() and 'objects' not in f.parts and not f.name.endswith('.headers') and f.suffix not in ['.json','.jsonl']:
b=f.read_bytes();o=objects/(hashlib.sha256(b).hexdigest()+'.bin')
if not o.exists():o.write_bytes(b)
print('INVENTORY',len(entries),'meaningful',len(meaningful),'status',dict(counts),'outbound occurrences',len(source_outbound))