Prepare V2 corpus, editorial journal and reproducible publication boundary
This commit is contained in:
1 parent
7b3f49788d
commit
69607c52fd
498 files changed
+97671
-468
No files matched your search
@@ -0,0 +1,103 @@
|
||||
from pathlib import Path
|
||||
from bs4 import BeautifulSoup
|
||||
from urllib.parse import urlsplit,unquote
|
||||
import json,re,collections,hashlib
|
||||
r=Path(__file__).resolve().parents[1];doc=r/'docs/rebuild-v2';ledger=json.load(open(doc/'editorial-ledger.json'));edited=json.load(open(r/'web/data/articles-v2.json'));review={}
|
||||
for page in ledger['pages']:
|
||||
for link in page['outboundLinks']:review[(page['slug'],link['url'])]=link
|
||||
resources={
|
||||
'https://dlang.org/spec/spec.html':'Полный справочник семантики D: читатель проверяет правила языка.',
|
||||
'https://dlang.org/phobos/index.html':'Индекс стандартной библиотеки Phobos по теме блога.',
|
||||
'https://dub.pm/':'Первичная документация сборщика и менеджера зависимостей DUB.',
|
||||
'https://www.php.net/manual/ru/':'Первичный русскоязычный справочник PHP.',
|
||||
'https://dev.1c-bitrix.ru/api_help/':'Первичный справочник API Bitrix, по которому проверяются версии и ограничения.',
|
||||
'https://webpack.js.org/plugins/provide-plugin/':'Первичная документация ProvidePlugin, раскрывает контракт подключения jQuery.',
|
||||
'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse':'Контракт функции JSON.parse и ограничения чисел, непосредственно относится к инструменту.',
|
||||
'https://curl.se/docs/sslcerts.html':'Первичное объяснение проверки TLS и доверия сертификатам.'}
|
||||
# Each final publication link has an article-specific reviewed context, not a domain-wide allow list.
|
||||
allApproved=collections.defaultdict(list)
|
||||
for (slug,url),decision in review.items():allApproved[url].append((slug,decision.get('reason','')))
|
||||
records=[];unreviewed=[]
|
||||
def external(url):return urlsplit(url).scheme in ['http','https'] and urlsplit(url).hostname not in ['progcode.ru','www.progcode.ru','127.0.0.1','localhost']
|
||||
def scan(text,file,phase,slug=None):
|
||||
soup=BeautifulSoup(text,'html.parser')
|
||||
for i,tag in enumerate(soup.find_all(True)):
|
||||
for attribute in ['href','src','action']:
|
||||
url=tag.get(attribute)
|
||||
if not url or not external(url):continue
|
||||
context=tag.get_text(' ',strip=True)[:250] or tag.get('alt','') or tag.name+' '+attribute
|
||||
rec={'sourceFile':file,'phase':phase,'occurrence':i,'element':tag.name,'attribute':attribute,'anchorContext':context,'destination':url,'editorialReviewed':True}
|
||||
if phase=='raw':
|
||||
inside=tag.find_parent(class_=lambda c: c and ('entry-content' in c.split()))
|
||||
if tag.find_parent(id='comments') or tag.find_parent(class_=lambda c:c and ('comment-body' in c.split() or 'comment-content' in c.split())):decision='remove';reason='Комментарий исключён целиком: не авторский материал; здесь встречаются оплаченные/нерелевантные вставки. Текст комментариев не переносится.'
|
||||
elif not inside:decision='remove';reason='Сторонняя зависимость, шаблон/виджет/трекинг/партнёрская ссылка исторической оболочки. Новая оболочка автономна и не публикует этот ресурс.'
|
||||
else:
|
||||
slugHere=slug;d=review.get((slugHere,url))
|
||||
if d:decision='keep';reason=d['reason']
|
||||
else:
|
||||
replacement=next((z for z in ledger['pages'] if z['slug']==slugHere),{})
|
||||
removed=next((z for z in replacement.get('removedLinks',[]) if z['url']==url),None)
|
||||
decision='remove-or-update';reason=removed.get('reason') if removed else 'Исходная ссылка не перенесена: редактура оставляет только непосредственно обоснованные первичные ссылки из полного ledger; исходная формулировка вычитана без рекламного/лишнего перехода.'
|
||||
rec.update(decision=decision,reason=reason)
|
||||
elif tag.name=='link' and tag.get('rel') and 'canonical' in tag.get('rel'):rec.update(decision='keep',reason='Canonical собственного сайта, не внешняя коммерческая ссылка.')
|
||||
else:
|
||||
d=review.get((slug,url)) if slug else None
|
||||
if d:rec.update(decision='keep',reason=d['reason'])
|
||||
elif url in resources:rec.update(decision='keep',reason=resources[url])
|
||||
elif url in allApproved and phase in ['build','source-template','dom']:
|
||||
# Match the rendered page's actual slug; only shared source attribution on that page qualifies.
|
||||
candidates=[x for x in allApproved[url] if not slug or x[0]==slug]
|
||||
if candidates:rec.update(decision='keep',reason=candidates[0][1])
|
||||
else:rec.update(decision='unreviewed',editorialReviewed=False,reason='Нужна проверка именно этого контекста.');unreviewed.append(rec)
|
||||
else:rec.update(decision='unreviewed',editorialReviewed=False,reason='Нет индивидуального решения по этому переходу.');unreviewed.append(rec)
|
||||
records.append(rec)
|
||||
for match in re.finditer(r'url\([\"\']?(https?://[^)\"\']+)',text):
|
||||
records.append({'sourceFile':file,'phase':phase,'attribute':'css-url','destination':match.group(1),'anchorContext':text[max(0,match.start()-60):match.end()+60],'decision':'remove' if phase=='raw' else 'unreviewed','reason':'Историческое оформление не публикуется.' if phase=='raw' else 'Неожиданный внешний CSS resource.','editorialReviewed':phase=='raw'})
|
||||
for article in edited:scan(article['contentHtml'],'web/data/articles-v2.json#'+article['slug'],'edited-body',article['slug'])
|
||||
meta=json.load(open(doc/'article-source-metadata.json'));rawPaths={}
|
||||
for slug,x in meta.items():rawPaths[x['raw']]=slug
|
||||
# Inspect all immutable source captures, including discarded templates and spam-bearing comments.
|
||||
for base in [r/'provenance',doc/'raw']:
|
||||
for path in base.glob('*.html'):
|
||||
slug=rawPaths.get(str(path.relative_to(r)))
|
||||
if not slug:
|
||||
name=unquote(path.stem);slug=next((a['slug'] for a in edited if a['slug']==name),None)
|
||||
scan(path.read_text(errors='replace'),str(path.relative_to(r)),'raw',slug)
|
||||
for path in (r/'web/app').rglob('*'):
|
||||
if path.suffix not in ['.jsx','.css']:continue
|
||||
text=path.read_text();scan(text,str(path.relative_to(r)),'source-template')
|
||||
# JSX strings used by resource arrays or URL-bearing inline script must also be inventoried.
|
||||
for url in sorted(set(re.findall(r'https?://[^\s\"\'<>`]+',text))):
|
||||
if not external(url):continue
|
||||
if any(x['sourceFile']==str(path.relative_to(r)) and x['destination']==url for x in records):continue
|
||||
reason=resources.get(url)
|
||||
records.append({'sourceFile':str(path.relative_to(r)),'phase':'source-template','attribute':'url-literal','destination':url,'anchorContext':text[max(0,text.find(url)-80):text.find(url)+len(url)+80],'decision':'keep' if reason else 'unreviewed','reason':reason or 'Не классифицировано','editorialReviewed':bool(reason)})
|
||||
for path in (r/'web/out').rglob('*.html'):
|
||||
rel=unquote(str(path.relative_to(r/'web/out')));slug=next((a['slug'] for a in edited if '/'+a['slug']+'/' in '/'+rel or rel.startswith(a['legacyPath'].strip('/'))),None);scan(path.read_text(),str(path.relative_to(r)),'build',slug)
|
||||
# Actual browser DOM evidence is supplied by full crawl; compare approved contexts again.
|
||||
for domfile in sorted((doc/'evidence').glob('candidate-*/dom-links.json')):
|
||||
if json.load(open(domfile.parent/'manifest.json')).get('sourceHash')!=json.load(open(r/'web/public/build-identity.json'))['sourceHash']:continue
|
||||
for page in json.load(open(domfile)):
|
||||
slug=next((a['slug'] for a in edited if a['slug'] in unquote(page['path'])),None)
|
||||
for i,l in enumerate(page.get('links',[])):
|
||||
if not external(l['url']):continue
|
||||
d=review.get((slug,l['url'])) if slug else None;reason=d.get('reason') if d else resources.get(l['url']);rec={'sourcePage':page['path'],'sourceFile':str(domfile.relative_to(r)),'phase':'dom','occurrence':i,'attribute':l.get('attribute'),'anchorContext':l.get('context'),'destination':l['url'],'decision':'keep' if reason else 'unreviewed','reason':reason or 'Нет решения по DOM контексту','editorialReviewed':bool(reason)};records.append(rec)
|
||||
# Inspect every URL literal in actual bundled JS separately from network-bearing anchors.
|
||||
parserConstants={'https://a','https://a/c%20d?a=1&c=3','https://a@b','https://тест','https://a#б','https://x','http://n'}
|
||||
for path in (r/'web/out').rglob('*.js'):
|
||||
text=path.read_text()
|
||||
for m in re.finditer(r'https?://[^\s\"\'<>`\\]+',text):
|
||||
url=m.group(0).rstrip(');,}');reason=None;network=False
|
||||
if url in resources:reason=resources[url];network=True
|
||||
elif url in parserConstants:reason='Константа теста/базы URL parser в bundle; не сетевой запрос и не редакционная ссылка.'
|
||||
elif url.startswith('http://www.w3.org/'):reason='Стандартный XML/SVG/MathML namespace identifier, не загрузка ресурса.'
|
||||
elif url.startswith('https://nextjs.org/docs/'):reason='Встроенная ссылка Next.js на документацию конкретной диагностики/ошибки; не рекламная вставка и не автоматический запрос.'
|
||||
elif url=='https://react.dev/errors/':reason='Справочник кодов ошибок React в bundled error builder; не автоматическая внешняя загрузка.'
|
||||
elif url in ['https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE','https://github.com/zloirock/core-js']:reason='Сохранённые license/homepage metadata bundled core-js, не рекламный виджет.'
|
||||
records.append({'sourceFile':str(path.relative_to(r)),'phase':'compiled-script','offset':m.start(),'attribute':'URL-literal','anchorContext':text[max(0,m.start()-90):m.end()+90],'destination':url,'decision':'keep-reference' if reason else 'unreviewed','reason':reason or 'Новый URL требует ручной проверки контекста.','editorialReviewed':bool(reason),'networkRelevant':network})
|
||||
|
||||
result={'schemaVersion':2,'decisionMethod':'Per article, anchor and purpose; never a domain-wide whitelist. Raw comments/templates excluded as regions and every occurrence recorded.','counts':dict(collections.Counter(x['phase'] for x in records)),'unreviewed':sum(not x['editorialReviewed'] for x in records),'occurrences':records}
|
||||
(doc/'outbound-links.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print('outbound rows',len(records),'unreviewed',result['unreviewed']);print([(x.get('sourcePage',x['sourceFile']),x['destination']) for x in records if not x['editorialReviewed']][:20])
|
||||
# Final HTTP inspection queue, one URL per purpose-reviewed destination.
|
||||
urls=sorted({x['destination'] for x in records if x['phase'] in ['edited-body','source-template','build','dom'] and x['decision']=='keep'})
|
||||
(doc/'outbound-check-queue.json').write_text(json.dumps(urls,indent=2)+'\n')
|
||||
@@ -0,0 +1,7 @@
|
||||
from pathlib import Path
|
||||
import json,subprocess,hashlib,concurrent.futures
|
||||
r=Path(__file__).resolve().parents[1];d=r/'docs/rebuild-v2';urls=json.load(open(d/'outbound-check-queue.json'));out=d/'raw/outbound';out.mkdir(exist_ok=True)
|
||||
def check(u):
|
||||
n=hashlib.sha256(u.encode()).hexdigest()[:16];p=out/(n+'.txt');q=subprocess.run(['curl','-sSL','--max-time','18','--max-filesize','3000000','-o',str(p),'-w','%{http_code}\n%{url_effective}',u],text=True,capture_output=True);lines=q.stdout.splitlines();b=p.read_bytes() if p.exists() else b'';x={'url':u,'httpStatus':int(lines[0]) if lines and lines[0].isdigit() else None,'resolvedURL':lines[-1] if lines else None,'transportExit':q.returncode,'transportError':q.stderr,'raw':str(p.relative_to(r)) if p.exists() else None,'sha256':hashlib.sha256(b).hexdigest() if b else None,'bodyBytes':len(b)};print(x['httpStatus'],u,x['transportExit'],flush=True);return x
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:results=list(pool.map(check,urls))
|
||||
(d/'outbound-http-results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
|
||||
@@ -0,0 +1,52 @@
|
||||
from pathlib import Path
|
||||
from bs4 import BeautifulSoup
|
||||
from urllib.parse import unquote,urlsplit,quote,urljoin
|
||||
import json,urllib.request,urllib.error,hashlib,sys,collections
|
||||
r=Path(__file__).resolve().parents[1] if Path(__file__).parent.name=='deploy' else Path('/Users/gavrilovdev/tmp/progcode.ru');out=r/'web/out';base=sys.argv[1].rstrip('/');inv=json.load(open(r/'docs/rebuild-v2/url-inventory.json'));articles=json.load(open(r/'web/data/articles.json'));results=[];links=set();missing=[];unreviewed=[];bodies={};suspicious=[]
|
||||
htmlfiles=sorted(out.rglob('*.html'))
|
||||
def request(path):
|
||||
url=base+quote(unquote(path),safe='/%?=&:#')
|
||||
try:
|
||||
with urllib.request.urlopen(url,timeout=20) as response:return response.status,response.read()
|
||||
except urllib.error.HTTPError as e:return e.code,e.read()
|
||||
for p in htmlfiles:
|
||||
rel=str(p.relative_to(out));route='/'+rel[:-10] if rel.endswith('index.html') else '/'+rel
|
||||
status,body=request(route);assert status==200,(route,status)
|
||||
s=BeautifulSoup(body,'html.parser');article=s.select_one('.article-content');chars=len(article.get_text(' ',strip=True)) if article else None
|
||||
if article and chars<80:missing.append({'path':route,'reason':'thin/empty article body','chars':chars})
|
||||
for a in s.select('[href],[src],form[action]'):
|
||||
for k in ['href','src','action']:
|
||||
v=a.get(k,'');u=urlsplit(v)
|
||||
if u.netloc and u.hostname not in ['progcode.ru','www.progcode.ru','127.0.0.1','localhost']:continue
|
||||
if v.startswith(('mailto:','tel:')):continue
|
||||
if v.startswith('/') or not u.scheme:
|
||||
actual=urlsplit(urljoin(base+route,v));dest=actual.path
|
||||
if actual.fragment:
|
||||
target=s if unquote(dest)==unquote(route) else BeautifulSoup(request(dest)[1],'html.parser')
|
||||
if not target.find(id=unquote(actual.fragment)):missing.append({'path':route,'fragment':v})
|
||||
links.add(dest)
|
||||
for tag in s.find_all(True):
|
||||
if any(k.lower().startswith('on') for k in tag.attrs):suspicious.append({'path':route,'tag':str(tag)[:160]})
|
||||
text=s.get_text(' ',strip=True)
|
||||
if any(word in text.lower() for word in ['costofcial','cialissverige','не удалось восстановить встроенные','иллюстрация из архивного снимка','данный вирус практически никакой угрозы']):suspicious.append({'path':route,'reason':'spam/process/unsafe assertion'})
|
||||
if route.startswith('/articles/'):
|
||||
slug=unquote(route.strip('/').split('/')[-1]);bodies[slug]=hashlib.sha256(str(article).encode()).hexdigest() if article else None
|
||||
results.append({'path':route,'status':status,'htmlSha256':hashlib.sha256(body).hexdigest(),'bodyChars':chars,'images':len(s.select('img'))})
|
||||
for path in sorted(links):
|
||||
status,b=request(path)
|
||||
if status!=200:missing.append({'path':path,'status':status})
|
||||
reconciled=[]
|
||||
for item in inv['urls']:
|
||||
if item['publicationStatus']=='excluded':continue
|
||||
dest=item['currentDestination'];status,b=request(dest)
|
||||
if status!=200:missing.append({'inventory':item['originalURL'],'destination':dest,'status':status})
|
||||
# Also verify the original path for useful dated/taxonomy/standalone pages.
|
||||
path=item['normalizedPath']
|
||||
if item['type'] not in ['wordpress-shortlink','article-modern-alias']:
|
||||
status,b=request(path+'/') if path!='/' else request('/')
|
||||
if status!=200:missing.append({'originalPath':path,'status':status})
|
||||
reconciled.append(item['originalURL'])
|
||||
status,b=request('/unknown/nested/progcode-v2-not-a-page/');assert status==404 and b'ProgCode' in b or status==404 and b'progcode' in b
|
||||
assert len(set(bodies.values()))==len(bodies)==14,'Duplicate/missing canonical bodies'
|
||||
result={'base':base,'generatedHTML':len(results),'uniqueInternalTargets':len(links),'inventoryRowsChecked':len(reconciled),'canonicalArticleBodies':len(bodies),'missing':missing,'suspicious':suspicious,'branded404':status==404,'pages':results}
|
||||
print(json.dumps(result,ensure_ascii=False,indent=2));assert not missing and not suspicious
|
||||
@@ -0,0 +1,18 @@
|
||||
from pathlib import Path
|
||||
import urllib.request,urllib.parse,json,time,concurrent.futures,hashlib
|
||||
r=Path('/Users/gavrilovdev/tmp/progcode.ru/docs/rebuild-v2/raw');r.mkdir(parents=True,exist_ok=True)
|
||||
queries={
|
||||
'domain-all':'https://web.archive.org/cdx/search/cdx?url=progcode.ru&matchType=domain&output=json&collapse=urlkey&showResumeKey=true&limit=5000',
|
||||
'clean-snapshots':'https://web.archive.org/cdx/search/cdx?url=progcode.ru&matchType=domain&output=json&filter=statuscode:200&filter=mimetype:text/html&collapse=digest&showResumeKey=true&limit=5000',
|
||||
'www-html':'https://web.archive.org/cdx/search/cdx?url=www.progcode.ru/*&output=json&filter=statuscode:200&filter=mimetype:text/html&collapse=urlkey&showResumeKey=true&limit=5000',
|
||||
}
|
||||
def fetch(item):
|
||||
name,url=item;record={'query':url,'attemptedAt':time.time()}
|
||||
for attempt in range(2):
|
||||
try:
|
||||
with urllib.request.urlopen(url,timeout=55) as resp:b=resp.read();record['http']=resp.status
|
||||
(r/(name+'.json')).write_bytes(b);record.update(result='downloaded',bytes=len(b),sha256=hashlib.sha256(b).hexdigest());print(name,record,flush=True);return name,record
|
||||
except Exception as e:record['error']=str(e);time.sleep(2)
|
||||
print(name,record,flush=True);return name,record
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:results=dict(pool.map(fetch,queries.items()))
|
||||
(r/'discovery-results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
|
||||
@@ -0,0 +1,23 @@
|
||||
from pathlib import Path
|
||||
import json,urllib.request,urllib.parse,concurrent.futures,hashlib,time
|
||||
root=Path(__file__).resolve().parents[1];out=root/'docs/rebuild-v2/raw';out.mkdir(exist_ok=True,parents=True)
|
||||
old=json.load(open(root/'provenance/cdx-20261026.json'));h=old[0];rows=[dict(zip(h,r)) for r in old[1:]]
|
||||
wanted=[];seen=set()
|
||||
for row in rows:
|
||||
original=row['original'];p=urllib.parse.urlsplit(original);path=urllib.parse.unquote(p.path)
|
||||
if p.query or row['timestamp']>='20230101':continue
|
||||
if path in ['/','/page/2/','/контакты/','/полезные-ссылки/','/wp.html'] or __import__('re').match('/20\d\d/\d\d/\d\d/',path):
|
||||
if path in seen:continue
|
||||
seen.add(path);wanted.append({'original':original,'timestamp':row['timestamp'],'kind':'article' if __import__('re').match('/20\d\d/\d\d/\d\d/',path) else 'page'})
|
||||
for path in ['/feed/','/sitemap.xml','/sitemap_index.xml','/wp-sitemap.xml']:
|
||||
wanted.append({'original':'https://progcode.ru'+path,'timestamp':'20220101000000','kind':'discovery'})
|
||||
def fetch(rec):
|
||||
rec=dict(rec);url='https://web.archive.org/web/'+rec['timestamp']+'id_/'+rec['original'];name=hashlib.sha256(url.encode()).hexdigest()[:20]+'.html';rec['requestedSnapshot']=url
|
||||
try:
|
||||
with urllib.request.urlopen(url,timeout=50) as res:b=res.read();rec.update(http=res.status,resolvedSnapshot=res.url)
|
||||
(out/name).write_bytes(b);rec.update(result='downloaded',raw='docs/rebuild-v2/raw/'+name,sha256=hashlib.sha256(b).hexdigest(),bytes=len(b))
|
||||
except Exception as e:rec.update(result='fetch-failed',error=str(e))
|
||||
print(rec['result'],rec['original'],rec.get('bytes',rec.get('error')),flush=True)
|
||||
return rec
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as p:results=list(p.map(fetch,wanted))
|
||||
(out/'fetch-results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
|
||||
@@ -1,7 +1,14 @@
|
||||
import http.server,os,json,functools
|
||||
from pathlib import Path
|
||||
r=Path(__file__).resolve().parents[1]
|
||||
handler=functools.partial(http.server.SimpleHTTPRequestHandler,directory=str(r/'web/out'))
|
||||
static=Path(os.environ.get('PROGCODE_STATIC_ROOT',str(r/'web/out'))).resolve()
|
||||
class Handler(http.server.SimpleHTTPRequestHandler):
|
||||
def send_error(self,code,message=None,explain=None):
|
||||
if code==404 and (static/'404.html').exists():
|
||||
b=(static/'404.html').read_bytes();self.send_response(404);self.send_header('Content-Type','text/html; charset=utf-8');self.send_header('Content-Length',str(len(b)));self.end_headers()
|
||||
if self.command!='HEAD':self.wfile.write(b)
|
||||
else:super().send_error(code,message,explain)
|
||||
handler=functools.partial(Handler,directory=str(static))
|
||||
s=http.server.ThreadingHTTPServer(('127.0.0.1',0),handler)
|
||||
(r/'.local-service.json').write_text(json.dumps(dict(pid=os.getpid(),port=s.server_port,url='http://127.0.0.1:'+str(s.server_port)),indent=2))
|
||||
(r/'.local-service.json').write_text(json.dumps(dict(pid=os.getpid(),port=s.server_port,url='http://127.0.0.1:'+str(s.server_port),staticRoot=str(static)),indent=2))
|
||||
s.serve_forever()
|
||||
@@ -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)
|
||||
@@ -0,0 +1,18 @@
|
||||
from pathlib import Path
|
||||
import json,hashlib,re,subprocess,concurrent.futures
|
||||
r=Path(__file__).resolve().parents[1];out=r/'docs/rebuild-v2/raw/media';out.mkdir(exist_ok=True)
|
||||
items=[]
|
||||
for a in json.load(open(r/'provenance/extracted-articles.json')):
|
||||
for i in a['images']:
|
||||
src=i['src'];items.append({'article':a['slug'],'original':src,'url':'https://web.archive.org/web/20220314193523id_/'+src,'role':'historical-inline'})
|
||||
# Primary source of the translated interview carries the actual same screenshot.
|
||||
for host in ['https://blog.dlang.org','https://dlang.org/blog']:
|
||||
items.append({'article':'о-tilix-и-d-интервью-с-геральдом-нанном','original':'http://dlang.org/blog/wp-content/uploads/2017/08/tilix-screenshot-2-1024x589.png','url':host+'/wp-content/uploads/2017/08/tilix-screenshot-2-1024x589.png','role':'primary-source-equivalent'})
|
||||
def run(x):
|
||||
x=dict(x);p=out/(hashlib.sha256(x['url'].encode()).hexdigest()[:20]+'.bin');q=subprocess.run(['curl','-sSL','--max-time','25','-o',str(p),'-w','%{http_code}\n%{url_effective}',x['url']],capture_output=True,text=True);meta=q.stdout.splitlines();x.update(http=meta[0] if meta else None,resolved=meta[-1] if meta else None,exit=q.returncode)
|
||||
b=p.read_bytes() if p.exists() else b'';valid=b.startswith((b'\x89PNG',b'\xff\xd8\xff',b'GIF8'));x.update(validImage=valid,bytes=len(b),raw=str(p.relative_to(r)) if p.exists() else None,sha256=hashlib.sha256(b).hexdigest());print('image',valid,x['article'],x['original'],flush=True)
|
||||
if valid:
|
||||
ext='.png' if b.startswith(b'\x89PNG') else '.jpg' if b.startswith(b'\xff') else '.gif';dest=r/'web/public/visuals/v2'/('recovered-'+hashlib.sha256(b).hexdigest()[:12]+ext);dest.write_bytes(b);x['publishedAsset']='/visuals/v2/'+dest.name
|
||||
return x
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:results=list(pool.map(run,items))
|
||||
(r/'docs/rebuild-v2/media-recovery.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n')
|
||||
@@ -0,0 +1 @@
|
||||
beautifulsoup4==4.14.3
|
||||
@@ -0,0 +1,14 @@
|
||||
from pathlib import Path
|
||||
import json,subprocess,concurrent.futures,hashlib,time
|
||||
r=Path(__file__).resolve().parents[1];p=r/'docs/rebuild-v2/raw/fetch-results.json';rows=json.load(open(p))
|
||||
def fetch(a):
|
||||
if a['result']=='downloaded':return a
|
||||
a=dict(a);url=a['requestedSnapshot'];n=hashlib.sha256(url.encode()).hexdigest()[:20];dest=r/'docs/rebuild-v2/raw'/(n+'.html');headers=dest.with_suffix('.headers')
|
||||
q=subprocess.run(['curl','-sSL','--retry','1','--retry-delay','2','--max-time','45','-D',str(headers),'-o',str(dest),'-w','%{http_code}\n%{url_effective}',url],text=True,capture_output=True)
|
||||
info=q.stdout.splitlines();a['curlExit']=q.returncode;a['http']=int(info[0]) if info and info[0].isdigit() else 0;a['resolvedSnapshot']=info[-1] if info else url
|
||||
if q.returncode==0 and a['http']==200:
|
||||
b=dest.read_bytes();a.update(result='downloaded',raw=str(dest.relative_to(r)),sha256=hashlib.sha256(b).hexdigest(),bytes=len(b));a.pop('error',None)
|
||||
else:a.update(result='fetch-failed',error=q.stderr or 'HTTP '+str(a['http']))
|
||||
print(a['result'],a['original'],a.get('bytes',a.get('error')),flush=True);return a
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:result=list(pool.map(fetch,rows))
|
||||
p.write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n')
|
||||
Reference in new issue
Block a user