Prepare V2 corpus, editorial journal and reproducible publication boundary

This commit is contained in:
huncode committed 2026-10-26 17:46:00 +03:00
1 parent 7b3f49788d
commit 69607c52fd
498 files changed
+97671 -468

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
from pathlib import Path
from urllib.parse import urlsplit,unquote,quote
from bs4 import BeautifulSoup
import json,re,hashlib,collections
r=Path(__file__).resolve().parents[1];doc=r/'docs/rebuild-v2';data=r/'web/data'
cdx=json.load(open(doc/'raw/domain-all.json'));h=cdx[0];rows=[dict(zip(h,x)) for x in cdx[1:]]
fetched=json.load(open(doc/'raw/fetch-results.json'));fetchby={unquote(urlsplit(x['original']).path).rstrip('/') or '/':x for x in fetched}
arts=json.load(open(data/'articles.json'));manifest=json.load(open(r/'provenance/manifest.json'))['articles'];routes={};articleMeta={};shortlinks={};rawFor={};allhref=[]
for a in arts:
rec=next(x for x in manifest if unquote(x['slug'])==a['slug']);legacy=unquote(urlsplit(rec['original']).path);key=legacy.rstrip('/');f=fetchby.get(key);p=r/f['raw'] if f and f['result']=='downloaded' else r/'provenance'/Path(rec['file']).name
raw=p.read_text();s=BeautifulSoup(raw,'html.parser');body=s.select_one('.entry-content');cats=[x.get_text(' ',strip=True) for x in s.select('.entry-categories a')];tags=[x.get_text(' ',strip=True) for x in s.select('.entry-tags a')];refs=[unquote(urlsplit(x.get('href','')).path).rstrip('/')+'/' for x in s.select('.entry-categories a,.entry-tags a')]
articleMeta[a['slug']]={'categories':cats,'tags':tags,'taxonomyPaths':refs,'raw':str(p.relative_to(r)),'rawSha256':hashlib.sha256(p.read_bytes()).hexdigest(),'bodySize':len(body.get_text(' ',strip=True)) if body else 0,'snapshot':(f.get('resolvedSnapshot') if f and f['result']=='downloaded' else rec['source']),'legacyPath':legacy}
for tag in s.select('link[rel=shortlink]'):
q=urlsplit(tag.get('href','')).query
if q.startswith('p='):shortlinks[q[2:]]='/articles/'+a['slug']+'/'
routes[key]={'type':'article','slug':a['slug']};rawFor[key]=articleMeta[a['slug']]
for link in s.select('a[href]'):
u=urlsplit(link['href']);path=unquote(u.path)
if u.hostname in ['progcode.ru','www.progcode.ru'] and re.match(r'/20\d\d/\d\d/\d\d/',path):allhref.append(path.rstrip('/')+'/')
# Query aliases are explicit data; home routes only known ids, never unknown pages.
(data/'shortlinks.json').write_text(json.dumps(shortlinks,ensure_ascii=False,indent=2)+'\n')
meaningful=set();inventory=[];counts=collections.Counter()
for row in rows:
u=urlsplit(row['original']);path=unquote(u.path);key=path.rstrip('/') or '/';query=u.query;mime=row['mimetype'];t='asset';action='exclude';reason='Ресурс оформления/служебный endpoint, не самостоятельная статья.';destination=None;pub='excluded';raw=None;title='';bodySize=None
if key in rawFor:
t='article' if not query else 'article-comment-alias';action='restore-edited-body';destination='/articles/'+routes[key]['slug']+'/';pub='planned';reason='Полное тело сохранено и проходит редактуру; комментарии, включая спам, исключены.';raw=rawFor[key];meaningful.add(key)
elif path.startswith('/articles/editorial-'):
t='synthetic-editorial';reason='Поздняя сгенерированная серия подтверждается исходным генератором репозитория; не историческая публикация. Не возвращается под видом архива.'
elif path.startswith('/articles/'):
slug=path.strip('/').split('/')[-1];known=next((a for a in arts if a['slug']==slug),None)
if known:t='article-modern-alias';destination='/articles/'+slug+'/';action='equivalent';pub='planned';reason='Современный адрес той же подтверждённой исторической статьи.'
else:t='unknown-modern';reason='Поздний маршрут без подтверждённого исторического тела; не оригинальный корпус.'
elif key=='/' and query.startswith('p='):
t='wordpress-shortlink';destination=shortlinks.get(query[2:]);action='equivalent-client-redirect' if destination else 'exclude';pub='planned' if destination else 'excluded';reason='Подтверждённый rel=shortlink исходной статьи.' if destination else 'Идентификатор не подтверждён исходным rel=shortlink.'
elif key=='/' and not query:
t='home';action='redesign';pub='planned';destination='/';reason='Полный индекс подтверждённых статей и маршруты чтения.';meaningful.add(key)
elif key in ['/контакты','/полезные-ссылки']:
t='standalone-empty-original';action='meaningful-equivalent';pub='planned';destination='/about/' if key=='/контакты' else '/resources/';reason='Повторно полученный снимок имеет пустую entry-content. Вместо мёртвой формы — сведения об авторе; вместо пустого списка — проверенные справочники по темам.';meaningful.add(key);routes[key]={'type':'about' if key=='/контакты' else 'resources'}
elif key.startswith(('/category/','/tag/','/author/')) or re.fullmatch('/20\d\d/\d\d',key) or key=='/page/2':
t='taxonomy';action='equivalent-filtered-index';pub='planned';destination=path.rstrip('/')+'/';reason='Индекс с фактическим набором подходящих статей по исходной таксономии/дате/автору.';meaningful.add(key)
if key not in routes:
matches=[a['slug'] for a in arts if key+'/' in articleMeta[a['slug']]['taxonomyPaths']]
if '/author/' in key:matches=[a['slug'] for a in arts];matches=matches[-4:] if key.endswith('/page/2') else matches
if re.fullmatch('/20\d\d/\d\d',key):matches=[a['slug'] for a in arts if a['date'].startswith(key[1:].replace('/','-'))]
if key=='/page/2':matches=[a['slug'] for a in arts][-4:]
title=key.split('/')[-1].replace('-',' ')
routes[key]={'type':'index','title':('Статьи за '+key[1:].replace('/',' · ')) if re.fullmatch('/20\d\d/\d\d',key) else 'DarkRiDDeR' if '/author/' in key else 'Ранние заметки' if key=='/page/2' else title,'slugs':matches}
elif key in ['/feed','/comments/feed'] or '/feed' in key:
t='feed';reason='Машинный RSS/комментарии, не отдельная публикация. Статьи доступны в полном индексе.'
elif key=='/wp.html':
t='wordpress-service-page';reason='Служебный WordPress endpoint не является публикацией (отдельно проверяется raw, публикация не планируется).'
# For available discovery captures attach exact evidence.
f=fetchby.get(key)
if not raw and f and f.get('result')=='downloaded':
p=r/f['raw'];s=BeautifulSoup(p.read_text(),'html.parser');b=s.select_one('.entry-content');raw={'raw':f['raw'],'rawSha256':f['sha256'],'snapshot':f.get('resolvedSnapshot'),'bodySize':len(b.get_text(' ',strip=True)) if b else 0};title=s.title.get_text(' ',strip=True) if s.title else ''
if raw:bodySize=raw.get('bodySize')
inv={'originalURL':row['original'],'normalizedPath':key,'type':t,'chosenSnapshot':raw.get('snapshot') if raw else 'https://web.archive.org/web/'+row['timestamp']+'id_/'+row['original'],'snapshotDate':row['timestamp'],'fetchStatus':'validated-local-or-fresh-raw' if raw else f.get('result') if f else 'not-required-for-disposition','rawFile':raw.get('raw') if raw else None,'rawHash':raw.get('rawSha256') if raw else None,'title':title,'bodySize':bodySize,'currentDestination':destination,'editorialAction':action,'publicationStatus':pub,'reason':reason,'cdxStatus':row['statuscode'],'mimetype':mime}
inventory.append(inv);counts[t]+=1
# Cross-check links discovered in raw: never let a dated article evade inventory.
unknown=sorted(set(allhref)-{a['legacyPath'] for a in articleMeta.values()})
for path in unknown:print('UNRECONCILED ARTICLE LINK',path)
(doc/'url-inventory.json').write_text(json.dumps({'discovery':{'domainRows':len(rows),'snapshotRows':len(json.load(open(doc/'raw/clean-snapshots.json')))-1,'pagination':'limit5000, showResumeKey=true; response exhausted below limit with no resume token','historicalArticlePaths':14,'meaningfulCanonicalPages':len(meaningful),'countsByType':dict(counts),'unreconciledDatedArticleLinks':unknown},'urls':inventory},ensure_ascii=False,indent=2)+'\n')
(data/'archive-routes.json').write_text(json.dumps(routes,ensure_ascii=False,indent=2)+'\n');(doc/'article-source-metadata.json').write_text(json.dumps(articleMeta,ensure_ascii=False,indent=2)+'\n')
print('rows',len(rows),'meaningful',len(meaningful),'articles',len(arts),'routes',len(routes),'emptyTaxonomies',[(k,v.get('title')) for k,v in routes.items() if v.get('type')=='index' and not v['slugs']]);print('shortlinks',shortlinks)