From c2512cb9b9f25485ca6cc95652360dd378e882b7 Mon Sep 17 00:00:00 2001 From: Talal Alqahs <153442159+TFQ0@users.noreply.github.com> Date: Thu, 8 Oct 2026 08:30:40 +0300 Subject: [PATCH] 3.1.0 --- README.md | 31 +++ docs/report-validation.md | 107 ++++++++ tests/test_app.py | 60 +++++ tests/test_cli.py | 9 + tests/test_exporters.py | 67 ++++- tests/test_rule_reports.py | 12 +- tests/wheel_smoke.py | 3 +- tfq0seo/cli.py | 7 + tfq0seo/core/app.py | 56 +++- tfq0seo/core/crawler.py | 4 + tfq0seo/exporters/base.py | 68 ++++- tfq0seo/templates/audit_summary.html | 67 +++++ tfq0seo/templates/enhanced_report.html | 18 +- tfq0seo/templates/optimized_report.html | 325 ++---------------------- tfq0seo/templates/page_inventory.html | 172 +++++++++++++ tfq0seo/templates/report.html | 16 +- 16 files changed, 671 insertions(+), 351 deletions(-) create mode 100644 docs/report-validation.md create mode 100644 tfq0seo/templates/audit_summary.html create mode 100644 tfq0seo/templates/page_inventory.html diff --git a/README.md b/README.md index 6025f4b..918e29e 100644 --- a/README.md +++ b/README.md @@ -385,6 +385,37 @@ and browse 20 findings per page. Details expose complete evidence on demand. This view runs locally in the report and requires JavaScript, without Chart.js or network access. JSON retains every finding as well. +All three HTML templates include **Crawl coverage & timing** and a **Pages & +response times** inventory. They distinguish the configured page limit from +recorded URLs and complete/partial/failed/skipped outcomes. Search by URL, +title, description, or error; filter outcomes; sort by fetch time, score, or +finding count; and paginate every record. Expand **Page details** for metadata, +word/link counts, headings, canonical/robots observations, category scores, +findings, recommendations, and individual timing measurements. The optimized +template's performance charts work offline without external scripts. + +`summary.analysis_duration` uses a monotonic clock and covers discovery, pacing, +fetching, and analysis, excluding report assembly/export. `crawl_stats` records +HTTP requests by kind (including retries), applied robots crawl delays, and +analysis cache hits. Its page throughput counts analyzed HTML pages, excluding +failed/skipped URLs. Imported reports without run context keep these measurements +unavailable. Per-page `load_time` is network time; `timings.total_seconds` also +includes fetch waiting/pacing, while headers and download timings describe the +final response. Concurrent timings overlap and should not be added to estimate +total elapsed time. + +A fast command exit is not evidence of a completed crawl. For example, this +command must include the URL; omitting it produces a usage error (exit code 2) +without creating a report: + +```bash +tfq0seo crawl https://example.com --depth 5 --max-pages 500 --concurrent 5 --format json --output audit.json +``` + +`--max-pages 500` sets a ceiling; fewer discoverable pages can produce a smaller +report. Inspect the actual counts, discovery gaps, and completion reason. See +[the live-site verification](docs/report-validation.md) for a measured example. + JSON, HTML, CSV, and XLSX exports write a temporary file beside the destination, close it successfully, and then atomically replace the destination. Rendering, serialization, write, and replacement failures preserve an existing report and diff --git a/docs/report-validation.md b/docs/report-validation.md new file mode 100644 index 0000000..63657fd --- /dev/null +++ b/docs/report-validation.md @@ -0,0 +1,107 @@ +# HTML reporting and crawl-speed verification + +Measured on 25 September 2026 using the local source checkout, Python 3.14.6, +Windows, and the owner's authorized site `https://siwar.ksaa.gov.sa/`. +These observations describe this run and environment, not a capacity guarantee. + +## Reproducing the reported fast exit + +The supplied command omitted the required URL: + +```sh +tfq0seo crawl --depth 5 --max-pages 500 --concurrent 5 --format json --output audit.json +``` + +Invoking it through `python -m tfq0seo.cli` exited with code **2** after **1.56 +seconds**, with `Error: Missing argument 'URL'.` No crawl or report write occurs +in that case. This explains the command as supplied; it does not establish what +happened in a different invocation that included a URL. + +## Live-site observations + +Two real, unauthenticated crawls respected robots.txt and disabled analysis +caching. The first used a 110-page ceiling, concurrency 3, and a 120-second +crawl deadline. It completed 18 pages in 110.76 seconds; report assembly took +0.44 seconds and JSON/HTML exports 0.84 seconds (112.04 seconds overall). + +The second used the supplied depth, page ceiling, and concurrency with the URL +added: + +```sh +python -m tfq0seo.cli crawl https://siwar.ksaa.gov.sa/ --depth 5 --max-pages 500 --concurrent 5 --config reports/siwar-validation/live-config.yaml --format json --output reports/siwar-validation/audit.json +python -m tfq0seo.cli export --input reports/siwar-validation/audit.json --format html --output reports/siwar-validation/audit.html +``` + +The local verification configuration limited requests to 15 seconds (10 seconds +for connecting), one retry, and a 180-second crawl deadline, with caching off. +No robots or TLS safeguards were disabled. + +To reproduce it, save this as `reports/siwar-validation/live-config.yaml`: + +```yaml +crawler: + max_crawl_time: 180 + timeout: 15 + connect_timeout: 10 + read_timeout: 15 + max_retries: 1 + cache_enabled: false +``` + +| Observation | Second run | +| --- | ---: | +| Configured page ceiling | 500 | +| Recorded URLs / analyzed HTML pages | 18 / 18 | +| Complete / partial / failed / skipped pages | 18 / 0 / 0 / 0 | +| HTTP requests | 23: 18 pages, 4 sitemap requests, 1 robots request | +| Analysis cache hits | 0 | +| Distinct recorded text hashes | 14 | +| Crawl + analysis elapsed | 110.67 s | +| Applied robots crawl delay | 5 s | +| Mean / median HTML network time | 0.100 / 0.064 s | +| Minimum / maximum HTML network time | 0.035 / 0.444 s | +| HTML export from saved JSON | 0.41 s | + +The five-second delay came from the site's robots.txt. Fast HTTP responses do +not imply a two-second audit: pacing, discovery, and analysis are separate work. +The page ceiling is not an inventory of the website, and static crawling does +not render JavaScript or enumerate every dictionary/search result. + +Both runs recorded discovery gaps: an excluded `/login` sitemap entry and +document-type parse errors at the three guessed sitemap locations +`/sitemap_index.xml`, `/sitemap-index.xml`, and `/sitemaps/sitemap.xml`. The report +therefore remains **partial**, despite all 18 fetched HTML pages completing +analysis. No claim of complete site coverage is made. + +The second crawl saved its JSON successfully. The surrounding measurement +script then failed while decoding UTF-8 console output with Windows cp1252, so +its total CLI wall time was not retained. The HTML was subsequently exported +from that saved JSON without recrawling; elapsed crawl time above is the tool's +monotonic measurement. Local artifacts are in `reports/siwar-validation/` +(ignored by Git), including `audit.html`, `audit.json`, `measurements.json`, +`before-measurements.json`, and the observed `robots.txt`. + +## Regression checks + +- A 110-page loopback crawl compares every reported request with the HTTP + server log, verifies URL retention, and includes a failed response and a + skipped non-HTML response. Neither inflates analyzed-page throughput. +- Separate sitemap discovery and page-fetch sessions contribute to request + totals. Imported report records inherit neither stale timings nor budgets. +- HTML checks preserve all 506 records in a large report across all three + templates, retain missing measurements, and escape untrusted page content. +- Browser checks exercise 45-record pagination (20/20/5), search, outcome + filtering, numeric sorting, empty results, and expanded page details. + Injected HTML remains text and unsafe URL schemes are not clickable. + +```sh +python -m pytest tests/test_app.py tests/test_exporters.py tests/test_cli.py +``` + +The complete suite passed **921 tests** in 239.04 seconds on Python 3.14.6. +Wheel and source builds passed Twine validation; the installed wheel passed +the isolated smoke test, including all report templates and shared partials. +Packaged Python/HTML files matched the working tree byte-for-byte. Modified +Python modules also passed Python 3.8 grammar parsing (not a Python 3.8 runtime +test). Interactive browser checks used a loopback HTTP preview; a direct +`file://` preview was blocked by the browser tool's URL policy. diff --git a/tests/test_app.py b/tests/test_app.py index d176a5e..146fc0e 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -126,6 +126,66 @@ def test_http_statuses_and_even_median_are_preserved(): assert metrics['load_time_stats']['median'] == 2 +def test_over_100_page_run_counts_real_requests_and_excludes_failures_from_speed(http_site): + import time + base, routes, requests = http_site + count = 110 + routes['/robots.txt'] = (200, {'Content-Type': 'text/plain'}, 'User-agent: *\nAllow: /') + routes['/'] = (200, {'Content-Type': 'text/html'}, 'Start

Start

' + + ''.join(f'Page {i}' for i in range(1, count)) + '') + for i in range(1, count): + routes[f'/page/{i}'] = (200, {'Content-Type': 'text/html'}, f'Page {i}

Page {i}

') + routes['/page/1'] = (404, {'Content-Type': 'text/html'}, 'Missing') + routes['/page/2'] = (200, {'Content-Type': 'application/json'}, '{}') + cfg = Config.from_dict({'crawler': {'max_pages': 150, 'max_concurrent': 5, 'use_sitemap': False, + 'adaptive_delay': False, 'cache_enabled': False, 'max_retries': 0}, + 'analysis': {'enabled_analyzers': ['seo', 'technical']}}) + async def run(): + analyzer = SEOAnalyzer(cfg) + started = time.perf_counter() + pages = [item async for item in analyzer.crawl_site(base + '/')] + elapsed = time.perf_counter() - started + report = analyzer.generate_site_report(pages) + summary, stats = report['summary'], report['crawl_stats'] + assert len(pages) == summary['total_pages'] == summary['unique_urls'] == count + assert summary['html_pages_analyzed'] == summary['successful_pages'] == count - 2 + assert summary['failed_pages'] == summary['skipped_pages'] == 1 + assert summary['page_limit'] == 150 + assert 0 < summary['analysis_duration'] <= elapsed + assert stats['pages_per_second'] == pytest.approx((count - 2) / summary['analysis_duration']) + assert stats['requests_made'] == len(requests) == count + 1 + assert stats['requests_by_kind'] == {'robots': 1, 'page': count} + assert len(set(requests)) == len(requests) + assert stats['cache_hits'] == 0 + assert summary['completion_reason'] == 'queue_exhausted' + assert all(page['load_time'] is not None for page in pages) + assert all(page['timings']['total_seconds'] >= page['load_time'] for page in pages) + assert report['metadata']['start_url'] == base + '/' + assert report['metadata']['config']['max_depth'] == cfg.crawler.max_depth + assert report['metadata']['config']['respect_robots_txt'] is True + imported = SEOAnalyzer(cfg).generate_site_report(pages) + assert imported['summary']['analysis_duration'] is None + assert imported['summary']['page_limit'] is None + assert imported['crawl_stats']['requests_made'] is None + asyncio.run(run()) + + +def test_request_counters_include_separate_sitemap_discovery_session(http_site): + base, routes, requests = http_site + routes['/robots.txt'] = (200, {}, 'User-agent: *\nAllow: /\nCrawl-delay: 0') + routes['/sitemap.xml'] = (200, {'Content-Type': 'application/xml'}, + f'{base}/page') + routes['/page'] = (200, {'Content-Type': 'text/html'}, 'Page

Page

') + async def run(): + analyzer = SEOAnalyzer(Config.from_dict({'crawler': {'adaptive_delay': False}})) + await analyzer.analyze_sitemap(base + '/sitemap.xml') + stats = analyzer.generate_site_report()['crawl_stats'] + assert stats['requests_made'] == len(requests) == 4 + assert stats['requests_by_kind'] == {'robots': 2, 'sitemap': 1, 'page': 1} + assert stats['robots_delays'] == {base: 0} + asyncio.run(run()) + + def test_rule_aggregation_retains_unique_page_evidence(): issues = [{'rule_id': 'seo.title', 'message': str(i), 'category': 'SEO', 'severity': 'warning', 'url': f'https://example.test/{i}'} for i in range(8)] diff --git a/tests/test_cli.py b/tests/test_cli.py index 042c284..c093e9d 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -6,6 +6,15 @@ from tfq0seo.cli import cli +def test_crawl_without_url_reports_usage_error_and_creates_no_report(tmp_path): + output = tmp_path / 'audit.json' + result = CliRunner().invoke(cli, ['crawl', '--depth', '5', '--max-pages', '500', + '--concurrent', '5', '--format', 'json', '--output', str(output)]) + assert result.exit_code == 2 + assert "Missing argument 'URL'" in result.output + assert not output.exists() + + def write_config(tmp_path, **crawler): path = tmp_path / 'config.json' path.write_text(json.dumps({'profile': 'quick', 'crawler': { diff --git a/tests/test_exporters.py b/tests/test_exporters.py index 0110c87..df91b8c 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -100,6 +100,62 @@ def test_complete_findings_data_survives_pagination_and_escapes_untrusted_text(t assert not soup.find('img') +@pytest.mark.parametrize('template', ['report', 'enhanced', 'optimized']) +def test_html_inventory_exposes_timings_outcomes_and_complete_safe_details(tmp_path, template): + payload = '' + complete = {'url': 'https://example.test/good', 'status': 'complete', 'status_code': 200, + 'load_time': 0.123456, 'analysis_time': 0.25, 'content_length': 2048, 'overall_score': 75, + 'timings': {'headers_seconds': 0.1, 'download_seconds': 0.023456, 'total_seconds': 5.5}, + 'seo': {'score': 75, 'data': {'title': {'text': payload}, 'description': {'text': 'Full description'}}}, + 'content': {'data': {'metrics': {'word_count': 321}}}, + 'context': {'depth': 2, 'parent_url': 'https://example.test/'}, + 'issues': [{'message': payload, 'severity': 'warning', 'category': 'SEO'}]} + records = [complete, + dict(complete, url='https://example.test/partial', status='partial'), + {'url': 'https://example.test/failed', 'status': 'error', 'error': 'Timed out', 'load_time': None}, + {'url': 'https://example.test/skip', 'status': 'skipped', 'skipped': True, 'reason': 'Blocked by robots.txt'}] + data = {'pages': records, 'summary': {'page_limit': 500, 'analysis_duration': 12.5, 'completion_reason': 'queue_exhausted'}, + 'crawl_stats': {'requests_made': 5, 'cache_hits': 0, 'pages_per_second': 2 / 12.5, + 'requests_by_kind': {'page': 4, 'robots': 1}, 'robots_delays': {'https://example.test': 5}}} + original = copy.deepcopy(data) + exporter = ExportManager({'output_directory': str(tmp_path), 'html_template': template}) + soup = BeautifulSoup(Path(exporter.export(data, 'html')).read_text(encoding='utf-8'), 'html.parser') + inventory = json.loads(soup.select_one('#pages-data').string) + assert len(inventory) == 4 + assert inventory[0]['load_time'] == 0.123456 + assert inventory[0]['headers_seconds'] == 0.1 + assert inventory[0]['fetch_elapsed_seconds'] == 5.5 + assert inventory[0]['title'] == inventory[0]['findings'][0]['message'] == payload + assert inventory[0]['word_count'] == 321 + assert inventory[0]['depth'] == 2 + assert inventory[2]['load_time'] is None + assert inventory[3]['reason'] == 'Blocked by robots.txt' + assert soup.select_one('[data-metric="recorded"]').get_text() == '4' + assert soup.select_one('[data-metric="analyzed"]').get_text() == '2' + assert soup.select_one('[data-metric="page-limit"]').get_text() == '500' + assert soup.select_one('[data-metric="duration"]').get_text() == '12.50 s' + assert soup.select_one('#page-search') and soup.select_one('#page-sort') and soup.select_one('#page-outcome') + assert not soup.select('[onerror]') + assert not soup.find('img') + if template == 'optimized': + assert not soup.select('script[src]') + assert '0.123 s' in soup.select_one('#performance').get_text() + assert data == original + + +def test_imported_report_does_not_invent_fast_crawl_or_page_budget(exporter): + prepared = exporter._prepare_html_data({'pages': [{'url': 'https://example.test'}], + 'summary': {'analysis_duration': 0}}) + assert prepared['audit']['duration'] is None + assert prepared['audit']['throughput'] is None + assert prepared['audit']['page_limit'] is None + assert prepared['audit']['requests'] is None + assert prepared['audit']['unknown'] == 1 + empty = exporter._prepare_html_data({'status': 'error', 'error': 'No pages to analyze'}) + assert empty['audit']['recorded'] == 0 + assert empty['pages_summary'] == [] + + @pytest.fixture def page(): html = '''A useful title for the local export fixture @@ -239,12 +295,11 @@ def test_every_page_survives_large_report_export(tmp_path, page, template): assert len(prepared['pages_summary']) == 506 assert prepared['pages_summary'][-1]['error'] == 'Timed out' html = Path(exporter.export(report, 'html')).read_text(encoding='utf-8') - if template == 'optimized': - embedded = re.search(r'const pagesData = (.*);', html).group(1) - assert len(json.loads(embedded)) == 506 - else: - soup = BeautifulSoup(html, 'html.parser') - assert len(soup.select('.pages-table tbody tr')) == 506 + soup = BeautifulSoup(html, 'html.parser') + embedded = json.loads(soup.select_one('#pages-data').string) + assert len(embedded) == 506 + assert embedded[-1]['error'] == 'Timed out' + assert len(soup.select('#pagesTable tbody tr')) == 20 with Path(exporter.export(report, 'csv')).open(encoding='utf-8', newline='') as stream: rows = list(csv.DictReader(stream)) assert len(rows) == 506 diff --git a/tests/test_rule_reports.py b/tests/test_rule_reports.py index f9a8cd7..31300ec 100644 --- a/tests/test_rule_reports.py +++ b/tests/test_rule_reports.py @@ -3,7 +3,6 @@ import asyncio import copy import json -import re from pathlib import Path import pytest @@ -119,10 +118,9 @@ def test_rule_metadata_does_not_drop_paginated_pages(tmp_path, analyzed_page, te report = SEOAnalyzer().generate_site_report(pages) soup, html, exporter = render(tmp_path, template, report) assert len(exporter._prepare_html_data(report)['pages_summary']) == 25 - if template == 'optimized': - embedded = re.search(r'const pagesData = (.*);', html).group(1) - assert len(json.loads(embedded)) == 25 - assert 'Page 1 of 2' in soup.get_text() - else: - assert len(soup.select('.pages-table tbody tr')) == 25 + embedded = json.loads(soup.select_one('#pages-data').string) + assert len(embedded) == 25 + assert {page['url'] for page in embedded} == {page['url'] for page in pages} + assert 'Page 1 of 2' in soup.select_one('#pageInfo').get_text() + assert len(soup.select('#pagesTable tbody tr')) == 20 assert soup.select('.rule-metadata') diff --git a/tests/wheel_smoke.py b/tests/wheel_smoke.py index 5af9c4f..1e15b9f 100644 --- a/tests/wheel_smoke.py +++ b/tests/wheel_smoke.py @@ -92,7 +92,8 @@ async def main(): assert site['links']['node_count'] == 2 and site['links']['edge_count'] == 1 assert {'site.canonical_chain', 'site.canonical_target_redirect'} <= { item['rule_id'] for item in site['findings']} - for filename in ('rule_metadata.html', 'site_analysis.html'): + for filename in ('rule_metadata.html', 'site_analysis.html', 'audit_summary.html', + 'page_inventory.html', 'findings.html'): assert (Path(tfq0seo.__file__).resolve().parent / 'templates' / filename).is_file() exporter.jinja_env.get_template(filename) templates = {'report': 'report.html', 'enhanced': 'enhanced_report.html', 'optimized': 'optimized_report.html'} diff --git a/tfq0seo/cli.py b/tfq0seo/cli.py index 9663f8d..98b8a3c 100644 --- a/tfq0seo/cli.py +++ b/tfq0seo/cli.py @@ -50,6 +50,13 @@ def create_summary_table(results: dict) -> Table: for name in ('total_pages', 'successful_pages', 'partial_pages', 'failed_pages', 'skipped_pages'): if name in results.get('summary', {}): table.add_row(name.replace('_', ' ').title(), str(results['summary'][name])) + summary = results.get('summary', {}) + if summary.get('page_limit') is not None: + table.add_row('Page Limit (Maximum)', str(summary['page_limit'])) + if summary.get('analysis_duration') is not None: + table.add_row('Crawl + Analysis Elapsed', f"{summary['analysis_duration']:.2f}s") + if results.get('crawl_stats', {}).get('requests_made') is not None: + table.add_row('HTTP Requests (Including Discovery)', str(results['crawl_stats']['requests_made'])) table.add_row('Status', results.get('status', 'complete')) return table diff --git a/tfq0seo/core/app.py b/tfq0seo/core/app.py index 86ee7a6..b349066 100644 --- a/tfq0seo/core/app.py +++ b/tfq0seo/core/app.py @@ -179,14 +179,24 @@ def _reset_state(self) -> None: self._run_limits = [] self._discovery_errors = [] self._site_start_url = None + self._run_started = None + self._run_duration = None + self._network_stats = [] def _begin_run(self) -> None: self.config.require_valid() self._reset_state() self._start_time = time.time() self.stats.analysis_start = self._start_time + self._run_started = time.perf_counter() self._semaphore = asyncio.Semaphore(self.config.analysis.max_analysis_threads) + def _track_crawler(self, crawler): + # Keep only the small counters, including discovery and external checks. + stats = getattr(crawler, 'stats', None) + if stats is not None: + self._network_stats.append(stats) + def _get_page_priority(self, url: str, depth: int = 0) -> PagePriority: try: path = urlparse(url).path @@ -479,9 +489,9 @@ def _record_analysis(self, result): self._update_progress() def _update_progress(self): - if self._start_time: - elapsed = max(time.time() - self._start_time, 0.000001) - self.progress.speed_pages_per_sec = self.progress.pages_analyzed / elapsed + if self._run_started is not None: + elapsed = max(time.perf_counter() - self._run_started, 0.000001) + self.progress.speed_pages_per_sec = self.stats.successful_analyses / elapsed memory = psutil.Process().memory_info().rss / 1024 / 1024 self.stats.memory_peak_mb = max(self.stats.memory_peak_mb, memory) if memory > self.config.max_memory_mb: @@ -492,6 +502,7 @@ async def analyze_url(self, url: str) -> PageResult: try: async with Crawler(self.config.crawler.as_dict()) as crawler: self.crawler = crawler + self._track_crawler(crawler) raw = await crawler.fetch_page(url) result = await self.analyze_page(raw or {'url': url, 'error': 'No fetch result'}) self.results.append(result) @@ -505,6 +516,7 @@ async def analyze_urls(self, urls: List[str]) -> AsyncIterator[PageResult]: try: async with Crawler(self.config.crawler.as_dict()) as crawler: self.crawler = crawler + self._track_crawler(crawler) iterator = self._analyze_url_list(crawler, urls) try: async for result in iterator: @@ -543,6 +555,7 @@ async def analyze_sitemap(self, sitemap_url: str) -> List[PageResult]: self._begin_run() try: async with Crawler(self.config.crawler.as_dict()) as discovery: + self._track_crawler(discovery) urls = await discovery.parse_sitemap(sitemap_url, self.config.crawler.max_pages) self._run_limits.extend(discovery.limit_reasons) self._discovery_errors.extend(copy.deepcopy(discovery.discovery_errors)) @@ -555,6 +568,7 @@ async def analyze_sitemap(self, sitemap_url: str) -> List[PageResult]: return self.results async with Crawler(self.config.crawler.as_dict()) as crawler: self.crawler = crawler + self._track_crawler(crawler) async for _ in self._analyze_url_list(crawler, urls): pass await self._complete_run() @@ -569,6 +583,7 @@ async def crawl_site(self, start_url: str) -> AsyncIterator[PageResult]: try: async with Crawler(self.config.crawler.as_dict()) as crawler: self.crawler = crawler + self._track_crawler(crawler) crawler.set_result_buffer_limit( self.config.crawler.effective_concurrency + self.config.analysis.max_analysis_threads) producer = asyncio.create_task(crawler.crawl_site(start_url, self.config.crawler.max_pages)) @@ -645,6 +660,7 @@ async def _check_external_links(self): settings = self.config.crawler.as_dict() settings.update(timeout=self.config.analysis.external_link_timeout, use_sitemap=False) async with Crawler(settings) as checker: + self._track_crawler(checker) for start in range(0, len(targets), self.config.crawler.effective_concurrency): tasks = [asyncio.create_task(checker.fetch_page(url)) for url in targets[start:start + self.config.crawler.effective_concurrency]] @@ -731,6 +747,10 @@ def _resolve_site_links(self, pages, link_checks=None): def _calculate_final_stats(self): self.stats.analysis_end = time.time() + if self._run_started is not None: + self._run_duration = max(0, time.perf_counter() - self._run_started) + self.progress.speed_pages_per_sec = ( + self.stats.successful_analyses / self._run_duration if self._run_duration else 0) self.stats.total_pages = len(self.results) if self._page_times: self.stats.avg_analysis_time = sum(self._page_times) / len(self._page_times) @@ -811,6 +831,14 @@ def generate_site_report(self, page_results=None) -> SiteReport: observations = self._observed_statuses(pages + link_checks) broken = sorted({page['url'] for page in pages + link_checks if observations.get(self._url_identity(page['url']), 0) >= 400}) + network_stats = self._network_stats if current_run else [] + request_counts = Counter() + robots_delays = {} + for network in network_stats: + request_counts.update(network.requests_by_kind) + for origin, delay in network.robots_delays.items(): + robots_delays[origin] = max(delay, robots_delays.get(origin, 0)) + duration = self._run_duration if current_run else None report = { 'schema_version': SCHEMA_VERSION, 'site_analysis': site_analysis, @@ -819,8 +847,15 @@ def generate_site_report(self, page_results=None) -> SiteReport: 'summary': {'total_pages': len(pages), 'successful_pages': len(usable) - len(partial_pages), 'partial_pages': len(partial_pages), 'failed_pages': len(failed), 'skipped_pages': len(skipped), 'analysis_mode': self.mode.value, 'analysis_timestamp': time.time(), - 'analysis_duration': max(0, self.stats.analysis_end - self.stats.analysis_start) - if current_run and self.stats.analysis_end else 0, + 'analysis_duration': duration, + 'duration_scope': 'Crawl, pacing, discovery, and analysis; excludes report assembly and export.', + 'html_pages_analyzed': len(usable), + 'unique_urls': len({self._url_identity(page['url']) for page in pages}), + 'page_limit': self.config.crawler.max_pages if current_run else None, + 'completion_reason': ('not_recorded' if not current_run else + 'limits_reached' if run_limits else + 'discovery_errors' if discovery_errors else + 'queue_exhausted' if self._site_start_url else 'input_processed'), 'crawl_complete': crawl_complete, 'limits_reached': run_limits, 'discovery_errors': discovery_errors, @@ -844,6 +879,13 @@ def generate_site_report(self, page_results=None) -> SiteReport: 'link_checks': copy.deepcopy(link_checks)}, 'performance_metrics': generate_performance_metrics(pages), 'crawl_stats': {'pages_per_second': self.progress.speed_pages_per_sec if current_run else 0, + 'throughput_scope': 'Analyzed HTML pages (complete or partial) per elapsed crawl/analysis second; excludes failed and skipped URLs.', + 'requests_made': sum(stats.requests_made for stats in network_stats) if network_stats else None, + 'requests_by_kind': dict(request_counts), + 'robots_delays': robots_delays, + 'bytes_downloaded': sum(stats.bytes_downloaded for stats in network_stats) if network_stats else None, + 'unique_content_count': len({page['content_hash'] for page in pages if page.get('content_hash')}) + if any(page.get('content_hash') for page in pages) else None, 'result_buffer_capacity': getattr(self.crawler, 'result_buffer_capacity', None) if current_run else None, 'result_buffer_peak': getattr(self.crawler, 'result_buffer_peak', 0) if current_run else 0, 'avg_analysis_time': self.stats.avg_analysis_time if current_run else 0, @@ -857,8 +899,12 @@ def generate_site_report(self, page_results=None) -> SiteReport: 'depth': page.get('context', {}).get('depth')} for page in usable], 'detailed': usable, 'failed': failed, 'skipped': skipped}, 'metadata': {'analyzer_version': self.config.version, 'schema_version': SCHEMA_VERSION, + 'start_url': self._site_start_url if current_run else None, 'config': {'max_pages': self.config.crawler.max_pages, 'analysis_mode': self.mode.value, 'concurrent_requests': self.config.crawler.effective_concurrency, + 'max_depth': self.config.crawler.max_depth, + 'respect_robots_txt': self.config.crawler.respect_robots_txt, + 'delay_between_requests': self.config.crawler.delay_between_requests, 'enabled_analyzers': self._enabled_analyzers()}}, } recommendations = generate_specific_recommendations(report) diff --git a/tfq0seo/core/crawler.py b/tfq0seo/core/crawler.py index f758843..deede2a 100644 --- a/tfq0seo/core/crawler.py +++ b/tfq0seo/core/crawler.py @@ -42,6 +42,8 @@ class CrawlStats: rate_limit_hits: int = 0 robots_blocked: int = 0 redirects_followed: int = 0 + requests_by_kind: Dict[str, int] = field(default_factory=dict) + robots_delays: Dict[str, float] = field(default_factory=dict) def get_summary(self) -> Dict[str, Any]: elapsed = max(0, time.time() - self.start_time) @@ -468,6 +470,7 @@ async def _request(self, url: str, base_url: str, kind: str = 'page', request_started = time.monotonic() try: self.stats.requests_made += 1 + self.stats.requests_by_kind[kind] = self.stats.requests_by_kind.get(kind, 0) + 1 async with self.session.get(current, allow_redirects=False, ssl=self.verify_ssl, proxy=self.proxy) as response: headers_seconds = time.monotonic() - request_started @@ -566,6 +569,7 @@ async def _get_robots(self, url: str): self._robots_sitemaps[origin] = rp.site_maps() or [] delay = rp.crawl_delay(self.user_agent) if delay is not None: + self.stats.robots_delays[origin] = delay * self.crawl_delay_factor self.rate_limiter.set_minimum_delay(origin, delay * self.crawl_delay_factor) rate = rp.request_rate(self.user_agent) if rate and rate.requests: diff --git a/tfq0seo/exporters/base.py b/tfq0seo/exporters/base.py index 3fa7095..d5ac839 100644 --- a/tfq0seo/exporters/base.py +++ b/tfq0seo/exporters/base.py @@ -16,6 +16,7 @@ from jinja2 import Environment, FileSystemLoader, TemplateNotFound, select_autoescape from markupsafe import Markup from ..core.report_contracts import validate_report +from ..core.report_optimizer import generate_performance_metrics try: from openpyxl import Workbook @@ -348,15 +349,64 @@ def _prepare_html_data(self, data: Dict[str, Any]) -> Dict[str, Any]: counts = self._issue_counts(data, issues) recs = self._recommendations(data) recommendations = data.get('recommendations', {}) if isinstance(data.get('recommendations'), dict) else {} - pages = self._page_records(data) + pages = self._page_records(data) if 'pages' in data or 'url' in data else [] summaries = [] for page in pages: count_data = page.get('issue_counts', page.get('issues', {})) issue_count = count_data.get('total', 0) if isinstance(count_data, dict) else len(count_data) + flat = self._flatten_page_data(page) + facts = page.get('page_facts', {}) + timings = page.get('timings', {}) + context = page.get('context', {}) + site = page.get('site_analysis', {}) + links = page.get('links', {}).get('data', {}) + status = page.get('status') or ('error' if page.get('error') else + 'skipped' if page.get('skipped') else 'not_recorded') summaries.append({'url': str(page.get('url', '')), 'score': self._number(page.get('overall_score', page.get('score'))), 'status_code': page.get('status_code'), 'load_time': self._number(page.get('load_time')), - 'issue_count': issue_count, 'error': page.get('error'), 'status': page.get('status')}) + 'issue_count': issue_count, 'error': page.get('error'), 'status': status, + 'reason': page.get('reason'), 'title': flat['title'], 'description': flat['description'], + 'word_count': flat['word_count'], 'content_length': page.get('content_length'), + 'requested_url': page.get('requested_url'), 'depth': context.get('depth', page.get('depth')), + 'parent_url': context.get('parent_url'), 'cached': page.get('cached', False), + 'headers_seconds': self._number(timings.get('headers_seconds')), + 'download_seconds': self._number(timings.get('download_seconds')), + 'fetch_elapsed_seconds': self._number(timings.get('total_seconds')), + 'analysis_time': self._number(page.get('analysis_time')), + 'category_scores': self._scores(page)[1], 'coverage': page.get('coverage', {}), + 'analyzer_errors': page.get('analyzer_errors', {}), + 'canonical_status': site.get('canonical_status'), + 'canonical_targets': site.get('canonical_targets'), + 'robots': facts.get('robots', {}), 'language': facts.get('language'), + 'h1': [heading.get('text', '') for heading in facts.get('headings', {}).get('headings', {}).get('h1', [])], + 'internal_links': len(links['internal_links']) if isinstance(links.get('internal_links'), list) else None, + 'external_links': len(links['external_links']) if isinstance(links.get('external_links'), list) else None, + 'redirect_chain': page.get('redirect_chain', []), + 'findings': [{key: issue.get(key) for key in ('rule_id', 'severity', 'message', 'recommendation')} + for issue in self._issues(page)], + 'recommendations': [self._recommendation_text(rec) for rec in self._recommendations(page)]}) summary = data.get('summary', {}) + crawl_stats = data.get('crawl_stats', {}) + states = {status: sum(page['status'] == status for page in summaries) + for status in ('complete', 'partial', 'error', 'skipped', 'not_recorded')} + observed_duration = self._number(summary.get('analysis_duration')) + # Old imported reports used zero for missing run timing. Do not call it a fast crawl. + if observed_duration == 0 and not summary.get('duration_scope'): + observed_duration = None + audit = {'recorded': len(summaries), 'analyzed': states['complete'] + states['partial'], + 'complete': states['complete'], 'partial': states['partial'], 'failed': states['error'], + 'skipped': states['skipped'], 'unknown': states['not_recorded'], + 'page_limit': summary.get('page_limit'), 'duration': observed_duration, + 'requests': crawl_stats.get('requests_made'), + 'requests_by_kind': crawl_stats.get('requests_by_kind', {}), + 'robots_delays': crawl_stats.get('robots_delays', {}), + 'cache_hits': crawl_stats.get('cache_hits'), + 'throughput': crawl_stats.get('pages_per_second') if observed_duration is not None else None, + 'unique_content': crawl_stats.get('unique_content_count'), + 'limits': summary.get('limits_reached', []), + 'discovery_errors': summary.get('discovery_errors', []), + 'config': data.get('metadata', {}).get('config', {}) if summary.get('page_limit') is not None else {}, + 'completion_reason': summary.get('completion_reason', 'not_recorded')} executive_defaults = { 'overview': {'total_pages_analyzed': summary.get('total_pages', len(pages)), 'successful_pages': summary.get('successful_pages', sum(not page.get('error') for page in pages)), @@ -406,9 +456,19 @@ def _prepare_html_data(self, data: Dict[str, Any]) -> Dict[str, Any]: aggregation_stats = issue_data.get('stats', data.get('aggregation_stats', {})) if self._number(aggregation_stats.get('reduction_ratio')) is None: aggregation_stats = {} + performance_metrics = data.get('performance_metrics') or generate_performance_metrics(pages) + fetch_distribution = {label: 0 for label in ('Under 0.1 s', '0.1–0.5 s', '0.5–1 s', '1–3 s', '3 s or more')} + for item in performance_metrics.get('load_times', []): + seconds = self._number(item.get('time')) + if seconds is not None: + bucket = sum(seconds >= threshold for threshold in (0.1, 0.5, 1, 3)) + fetch_distribution[list(fetch_distribution)[bucket]] += 1 return { 'data': data, - 'url': data.get('url', 'Multiple Pages'), 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), + 'url': data.get('url') or data.get('metadata', {}).get('start_url') or + (pages[0].get('url') if pages else None) or 'Multiple Pages', + 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), + 'audit': audit, 'error': data.get('error'), 'overall_score': overall, 'category_scores': categories, 'report_status': data.get('status'), 'scoring_policies': scoring_policies, 'scoring_versions': scoring_versions, @@ -425,7 +485,7 @@ def _prepare_html_data(self, data: Dict[str, Any]) -> Dict[str, Any]: 'executive_summary': executive, 'aggregated_issues': issue_data.get('aggregated', data.get('aggregated_issues', [])), 'aggregation_stats': aggregation_stats, - 'performance_metrics': data.get('performance_metrics', {}), + 'performance_metrics': performance_metrics, 'fetch_distribution': fetch_distribution, 'pages': pages, 'pages_summary': summaries, 'pages_truncated': data.get('pages_truncated', False), 'pages_truncated_count': data.get('pages_truncated_count', 0), 'summary': summary, 'seo_data': seo, 'content_data': content, 'technical_data': technical, diff --git a/tfq0seo/templates/audit_summary.html b/tfq0seo/templates/audit_summary.html new file mode 100644 index 0000000..c22a743 --- /dev/null +++ b/tfq0seo/templates/audit_summary.html @@ -0,0 +1,67 @@ + +
+

Crawl coverage & timing

+

{% if url|safe_url %}{{ url }}{% else %}{{ url }}{% endif %}

+
+
{{ audit.recorded }}URL records in this report
+
{{ audit.analyzed }}HTML pages analyzed (complete + partial)
+
{{ audit.page_limit|number }}Configured page limit
+
{{ audit.duration|number(2, ' s') }}Crawl + analysis elapsed time
+
+
+ Complete: {{ audit.complete }}Partial: {{ audit.partial }} + Failed: {{ audit.failed }}Skipped: {{ audit.skipped }} + {% if audit.unknown %}Status not recorded: {{ audit.unknown }}{% endif %} +
+

--max-pages is an upper limit, not the number of pages found on the site. + Counts cover the URLs discovered or supplied for this run. JavaScript-generated routes and content are not rendered.

+
+
HTTP requests (including discovery / retries)
{{ audit.requests|number }}
+
Analyzed HTML pages / second
{{ audit.throughput|number(2) }}
+
Analysis cache hits
{{ audit.cache_hits|number }}
+
Distinct recorded text hashes
{{ audit.unique_content|number }}
+ {% for kind, count in audit.requests_by_kind.items() %}
{{ kind|title }} HTTP requests
{{ count }}
{% endfor %} + {% for origin, delay in audit.robots_delays.items() %}
Applied robots crawl delay — {{ origin }}
{{ delay|number(2, ' s') }}
{% endfor %} + {% if audit.config %} +
Configured concurrent requests
{{ audit.config.get('concurrent_requests')|number }}
+ {% if audit.config.get('max_depth') is not none %}
Configured link depth limit
{{ audit.config.max_depth }}
{% endif %} +
Enabled analyzers
{{ audit.config.get('enabled_analyzers', [])|join(', ') }}
+ {% endif %} +
+

Completion: + {% if audit.completion_reason == 'queue_exhausted' %}No more eligible URLs remained in the discovered queue. This does not prove that every page on the website was found. + {% elif audit.completion_reason == 'input_processed' %}The supplied URL list was processed. + {% elif audit.completion_reason == 'limits_reached' %}A configured limit stopped coverage. + {% elif audit.completion_reason == 'discovery_errors' %}The discovered queue finished with discovery gaps; review the details below. + {% else %}The crawl completion reason was not recorded in this report.{% endif %} +

+ {% if audit.failed or audit.skipped or audit.partial or audit.limits or audit.discovery_errors %} +
+ Coverage needs review. Failed, skipped, partial, and undiscovered pages are not successful full analyses. + {% if audit.limits %}

Limits reached: {{ audit.limits|join(', ') }}

{% endif %} + {% if audit.discovery_errors %}
Discovery gaps ({{ audit.discovery_errors|length }}) +
    {% for item in audit.discovery_errors %}
  • {{ item.url }} — {{ item.error }}
  • {% endfor %}
+
{% endif %} +
+ {% endif %} +

Elapsed time includes fetching, robots pacing, discovery, and analysis; it excludes report assembly and export. + Parallel requests overlap, so adding per-page timings does not give the run's elapsed time.

+
diff --git a/tfq0seo/templates/enhanced_report.html b/tfq0seo/templates/enhanced_report.html index a857f7a..841d414 100644 --- a/tfq0seo/templates/enhanced_report.html +++ b/tfq0seo/templates/enhanced_report.html @@ -476,7 +476,8 @@

🚀 TFQ0SEO Enhanced Analysis Report

- {{ rule_overview(scoring_policies, scoring_versions, rule_coverage) }} + {% include "audit_summary.html" %} + {{ rule_overview(scoring_policies, scoring_versions, rule_coverage) }} {% include "site_analysis.html" %}
@@ -676,20 +677,7 @@

{{ severity|title }} Issues ({{ issues_list|length }})

- {% if pages_summary|length > 1 or summary %} -
-

Pages ({{ pages_summary|length }})

- - - {% for page in pages_summary %} - - - - - {% endfor %} -
URLScoreStatusLoad timeIssuesAnalysis status
{{ page.url }}{{ page.score|number }}{{ page.status_code if page.status_code is not none else 'Unavailable' }}{{ page.load_time|number(2, 's') }}{{ page.issue_count }}{{ page.error or page.status or '' }}
-
- {% endif %} + {% include "page_inventory.html" %} +
+

Pages & response times ({{ pages_summary|length }})

+

Search every recorded URL, including failures and skips. Open a page's details for metadata, category scores, findings, and timing breakdowns.

+
+
+
+
+
+

+
+ + + {% for page in pages_summary[:20] %} + + + + {% endfor %} +
Page / titleOutcomeHTTPHTML fetchScoreFindingsWords
{{ page.url }}{{ page.title }}{{ page.status }}{{ page.status_code if page.status_code else 'No response' }}{{ page.load_time|number(3, ' s') }}{{ page.score|number }}{{ page.issue_count }}{{ page.word_count|number }}
+ +

HTML fetch is recorded network time for the HTML request, including redirects/retries, excluding pacing and analysis. + Details separate final-response headers and body download from total fetch elapsed time (which includes waiting). + These are HTTP observations, not browser load time, TTFB, or Core Web Vitals. Missing timings remain “Not measured”.

+ +
+ + diff --git a/tfq0seo/templates/report.html b/tfq0seo/templates/report.html index b489876..48b982f 100644 --- a/tfq0seo/templates/report.html +++ b/tfq0seo/templates/report.html @@ -527,6 +527,7 @@

TFQ0SEO Analysis Report

Generated: {{ timestamp }}
+ {% include "audit_summary.html" %} {{ rule_overview(scoring_policies, scoring_versions, rule_coverage) }} {% include "site_analysis.html" %} @@ -626,20 +627,7 @@

Recommendations

{% endif %} - {% if pages_summary|length > 1 or summary %} -
-

Pages ({{ pages_summary|length }})

- - - {% for page in pages_summary %} - - - - - {% endfor %} -
URLScoreStatusLoad timeIssuesAnalysis status
{{ page.url }}{{ page.score|number }}{{ page.status_code if page.status_code is not none else 'Unavailable' }}{{ page.load_time|number(2, 's') }}{{ page.issue_count }}{{ page.error or page.status or '' }}
-
- {% endif %} + {% include "page_inventory.html" %}