Files

79 lines
13 KiB
Python

from pathlib import Path
from urllib.parse import urlsplit,unquote
import json,hashlib,collections,re,xml.etree.ElementTree as ET,datetime
from bs4 import BeautifulSoup
r=Path(__file__).resolve().parents[4];out=Path(__file__).parent;obs=json.loads((out/'observed-input.json').read_text());urls=obs['urls'];compact=json.dumps(urls,ensure_ascii=False,separators=(',',':'));assert compact.isascii();fnv=2166136261
for ch in compact:fnv=((fnv^ord(ch))*16777619)&0xffffffff
integrity={'rows':len(urls),'compactLength':len(compact),'FNV1a32':f'{fnv:08x}','compactSHA256':hashlib.sha256(compact.encode()).hexdigest()};assert len(urls)==100 and integrity['compactLength']==9361 and integrity['FNV1a32']=='a0080cc9' and integrity['compactSHA256']==obs['transcriptionCheck']['urlsJSONSHA256']
inv=json.loads((r/'docs/rebuild-v2/url-inventory.json').read_text())['urls'];routes=json.loads((r/'web/data/archive-routes.json').read_text());arts=json.loads((r/'web/data/articles.json').read_text());bySlug={v['slug']:v for v in arts};meta=json.loads((r/'docs/rebuild-v2/article-source-metadata.json').read_text());comments=json.loads((out/'comments/comments.json').read_text());commentBy={(v['articleSlug'],'comment-'+str(v['commentID'])):v for v in comments['records']};candidate=json.loads((out/'accepted-baseline.json').read_text());frozen=Path(candidate['staticRoot']);assert candidate['sourceHash'].startswith('f4aa72')
byPath=collections.defaultdict(list)
for item in inv:byPath[item['normalizedPath'].rstrip('/') or '/'].append(item)
def norm(s):return re.sub(r'\s+',' ',s).strip()
def decode(path):return unquote(path,errors='strict').rstrip('/') or '/'
rawProof={};taxonomy=collections.defaultdict(list)
for slug,m in meta.items():
p=r/m['raw'];assert hashlib.sha256(p.read_bytes()).hexdigest()==m['rawSha256'];s=BeautifulSoup(p.read_bytes(),'html.parser');links=[{'href':a['href'],'label':a.get_text(' ',strip=True)} for a in s.select('.entry-categories a,.entry-tags a')];keys={decode(urlsplit(v['href']).path) for v in links};assert keys=={v.rstrip('/') for v in m['taxonomyPaths']}
rawProof[slug]={'rawFile':m['raw'],'sha256':m['rawSha256'],'legacyPath':m['legacyPath'],'canonicalHref':s.select_one('link[rel=canonical]').get('href') if s.select_one('link[rel=canonical]') else None,'taxonomyLinks':links,'publicationTime':str(s.select_one('time.entry-date.published')),'authorLinks':[a.get('href') for a in s.select('a[href]') if '/author/darkridder/' in a.get('href','')],'bodyTextSHA256':hashlib.sha256(norm(s.select_one('.entry-content').get_text(' ',strip=True)).encode()).hexdigest()}
for key in keys:taxonomy[key].append(slug)
cache={}
def published(key):
if key not in cache:
p=frozen/('index.html' if key=='/' else key.strip('/')+'/index.html')
if not p.exists():cache[key]={'exists':False};return cache[key]
s=BeautifulSoup(p.read_bytes(),'html.parser');main=s.select_one('main');slugs=[]
for a in s.select('main .journal-list .index-entry a[href]'):
path=decode(urlsplit(a['href']).path)
if path.startswith('/articles/'):slugs.append(path[len('/articles/'):])
cache[key]={'exists':True,'file':str(p),'HTMLSHA256':hashlib.sha256(p.read_bytes()).hexdigest(),'mainTextCharacters':len(main.get_text(' ',strip=True)) if main else 0,'heading':main.h1.get_text(' ',strip=True) if main and main.h1 else None,'articleLinks':slugs,'elementIDs':[v['id'] for v in s.select('[id]')]}
return cache[key]
fetches=json.loads((out/'fetch-evidence.json').read_text());fetchBy={v['path']:v for v in fetches};feedProof={}
for key,name in [('/feed','feed'),('/comments/feed','comments-feed')]:
fetch=fetchBy[key];assert fetch['exitCode']==0 and fetch['requestedSnapshot']==fetch['resolvedURL'];p=r/fetch['rawFile'];assert hashlib.sha256(p.read_bytes()).hexdigest()==fetch['sha256'];x=ET.fromstring(p.read_bytes());assert x.tag=='rss';items=[]
for item in x.findall('./channel/item'):
link=item.findtext('link');u=urlsplit(link);path=decode(u.path);route=routes.get(path);assert route and route['type']=='article';slug=route['slug'];content=item.findtext('{http://purl.org/rss/1.0/modules/content/}encoded') or item.findtext('description') or '';text=norm(BeautifulSoup(content,'html.parser').get_text(' ',strip=True));rec={'title':item.findtext('title'),'link':link,'slug':slug,'fragment':u.fragment,'textCharacters':len(text),'textSHA256':hashlib.sha256(text.encode()).hexdigest()}
if key=='/feed':assert rec['textSHA256']==rawProof[slug]['bodyTextSHA256'];rec['owningRawArticleTextIdentical']=True
else:assert text=='Nice!' and u.fragment=='comment-2';rec['meaning']='nontechnical acknowledgement, not an additional article'
items.append(rec)
feedProof[key]={'fetch':fetch,'root':'rss','items':items,'publishedProtocolEndpointExists':published(key)['exists'],'disposition':'RSS protocol excluded, not rebuilt; feed item substance reconciled individually to known full article/comment; no generic redirect','newHistoricalArticle':False}
pagination={}
for key in ['/page/2','/author/darkridder/page/2']:
v=fetchBy[key];assert v['exitCode']==0 and v['requestedSnapshot']==v['resolvedURL'];p=r/v['rawFile'];assert hashlib.sha256(p.read_bytes()).hexdigest()==v['sha256'];s=BeautifulSoup(p.read_bytes(),'html.parser');links=[{'title':a.get_text(' ',strip=True),'href':a['href'],'slug':routes[decode(urlsplit(a['href']).path)]['slug']} for a in s.select('article .entry-title a')];current=published(key);assert current['mainTextCharacters']>80 and current['articleLinks']==routes[key]['slugs'];pagination[key]={'fetch':v,'historicalArticleLinks':links,'currentArticleSlugs':current['articleLinks'],'allHistoricalItemsStillAvailable':all(v['slug'] in current['articleLinks'] for v in links),'exactHistoricalListEqual':[v['slug'] for v in links]==current['articleLinks'],'scope':'Current full-corpus early-article index, not a blank redirect. Exact captured page2 list differs (1 vs4); author page2 list matches4. Cause of old page-size difference not inferred.'}
# The original forms are direct evidence for service endpoints, not title inference.
p=r/'provenance/bitrix-api-add-foto-editor.html';s=BeautifulSoup(p.read_bytes(),'html.parser');serviceProof={'rawFile':str(p.relative_to(r)),'sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'commentPostForm':str(s.select_one('form#commentform'))[:250],'loginLinks':[str(a) for a in s.select('a[href]') if '/wp-login.php' in a['href']]}
rows=[]
for number,url in enumerate(urls,1):
u=urlsplit(url);row={'row':number,'observedURL':url,'observedScheme':u.scheme,'observedHost':u.netloc,'rawEncodedPath':u.path,'rawQuery':u.query,'rawFragment':u.fragment,'rowMetadataAndReferrers':None}
try:key=decode(u.path)
except UnicodeDecodeError as err:
row.update(type='malformed-unconfirmed',lookupPath=None,decodingError=str(err),inventoryMatches=[],decision='Preserve exact malformed URI, no repair/double-decoding/title-based identity or alias. No exact existing inventory match; remain explicit unresolved, expected true404.',candidateArticleIdentity=None,published={'exists':False});rows.append(row);continue
row['lookupPath']=key;matches=byPath.get(key,[]);row['inventoryMatches']=[{'originalURL':v['originalURL'],'type':v['type'],'rawFile':v['rawFile'],'currentDestination':v['currentDestination']} for v in matches];row['published']=dict(published(key));route=routes.get(key)
if key=='/':row.update(type='home',decision='Existing substantive14-article home; HTTP/HTTPS/www transport variants are not separate articles')
elif route and route['type']=='article':
slug=route['slug'];row.update(type='article',articleSlug=slug,articleSource=rawProof[slug],decision='Known dated publication restored as full edited body; identity from explicit source canonical/legacy path, not title')
if u.fragment:
c=commentBy[(slug,u.fragment)];row.update(type='comment-fragment',commentRecord='comments/comments.json#'+slug+':'+str(c['commentID']),commentClassification=c['classification'],commentDecision=c['researchDisposition'],currentFragmentExists=u.fragment in row['published']['elementIDs'],usefulFactOmitted=c['usefulFactOmitted'],freshCommentCorroboration=c.get('freshCaptureCorroboration'),decision='Article exists; exact historical comment anchor is not published. Use per-comment raw/coverage decision; no fake comment/anchor.')
elif route and route['type']=='index':
actual=row['published']['articleLinks'];assert actual==route['slugs'] and len(actual)>0;proof={'actualPublishedSlugs':actual,'rawSources':[rawProof[v]['rawFile'] for v in actual],'blankOrGenericRedirect':False}
if key.startswith(('/tag/','/category/')):assert set(actual)==set(taxonomy[key]);proof['membership']='independently reparsed exact source .entry-categories/.entry-tags hrefs'
elif re.fullmatch(r'/20\d\d/\d\d',key):assert set(actual)=={v['slug'] for v in arts if v['date'].startswith(key[1:].replace('/','-'))};proof['membership']='source publicationISO/calendar and dated legacy paths'
elif key in pagination:proof['pagination']=pagination[key]
else:proof['membership']='full known author corpus with source author hrefs'
row.update(type='index',indexProof=proof,decision='Actual nonempty filtered index of source-confirmed articles, no blanket redirect')
elif route and route['type'] in ['about','resources']:
m=next(v for v in matches if v['type']=='standalone-empty-original');raw=r/m['rawFile'];b=BeautifulSoup(raw.read_bytes(),'html.parser').select_one('.entry-content');assert b is not None and len(b.get_text(' ',strip=True))==0;assert row['published']['mainTextCharacters']>80;row.update(type='standalone-equivalent',originalBodyChars=0,decision='Captured owning body empty; current meaningful author/primary-resource equivalent. Not a claim of recovered absent form/list.')
elif key in feedProof:row.update(type='feed',feedProof=feedProof[key],decision=feedProof[key]['disposition'])
elif key in ['/wp-comments-post.php','/wp-login.php']:row.update(type='wordpress-service',sourceServiceProof=serviceProof,decision='Old comment-submit/login endpoint evidenced by source form/login link; excluded service, no article or generic alias. Current static endpoint absent.')
else:raise AssertionError((number,url,key))
row['published'].pop('elementIDs',None);rows.append(row)
probeFile=out/'current-service-malformed-probes.json'
if probeFile.exists():
probes={v['row']:v for v in json.loads(probeFile.read_text())['checks']}
for row in rows:
if row['row'] in probes:row['currentHTTPProbe']=probes[row['row']]
assert [v['observedURL'] for v in rows]==urls and len(rows)==100
summary={'timeUTC':datetime.datetime.now(datetime.timezone.utc).isoformat(),'domain':'progcode.ru','scope':'All100 exact cached observedURL strings, not fresh Semrush and not all174 reported rows','inputIntegrity':integrity,'reportedTotal':174,'exactObservedRowsReconciled':100,'reportedRowsUnseen':74,'countsByType':dict(collections.Counter(v['type'] for v in rows)),'uniqueConfirmedArticleSlugs':sorted({v['articleSlug'] for v in rows if 'articleSlug' in v}),'newHistoricalArticlesDiscovered':0,'uniqueHistoricalCommentsInspected':6,'newUsefulClarifications':1,'usefulFinding':'VibeDiet template-edit/rebuild operational consequence, sourcecomments4/5; already-described compile mechanism, explicit consequence pending narrow integration','malformedUnconfirmedRows':[v['row'] for v in rows if v['type']=='malformed-unconfirmed'],'acceptedCandidate':candidate,'productSourceChangedByResearch':False,'productionDeployRequested':False,'mandatoryIssue':'webprogcode-v2.6','mandatoryIssueComplete':False,'remaining':['ExactURL/metadata of74 reported-but-unseen rows','Full referringURL/anchor/target context and metadata not included in100URL-only transcription','MalformedjQueryrow28 identity staysunconfirmed/404; no guessed alias','Source-bound Diet clarification to integrate with bounded review/release; historical full-project-clean-rebuild opinion is not an invariant','Currentpage2 is semantic4-article index vs captured1; explicitly not exact old pagination; no missing sourcearticle found']}
resolutionFile=out/'diet-finding-resolution.json'
if resolutionFile.exists():
summary['successorResolution']='diet-finding-resolution.json';summary['usefulFindingCurrentState']='publishedexact148/source53; originalf4baselineomissionretainedasresearchhistory';summary['remaining']=[v for v in summary['remaining'] if not v.startswith('Source-bound Diet clarification')]
(out/'reconciliation-100.json').write_text(json.dumps({'summary':summary,'rows':rows,'feeds':feedProof,'pagination':pagination},ensure_ascii=False,indent=2)+'\n');(out/'remaining-sources.json').write_text(json.dumps({'scope':summary['scope'],'reportedRowsUnseen':74,'remaining':summary['remaining'],'fullRestorationAccepted':False},ensure_ascii=False,indent=2)+'\n');print(json.dumps({k:v for k,v in summary.items() if k not in ['acceptedCandidate','remaining','uniqueConfirmedArticleSlugs']},ensure_ascii=False,indent=2))