Download scripts/filter.py from Jl-wei/DesignSpecs: direct link, hf CLI and curl.
- Browser
- Download file 15.9 kB
-
https://huggingface.co/datasets/Jl-wei/DesignSpecs/resolve/main/scripts/filter.py
- Command line
-
hf download hf://datasets/Jl-wei/DesignSpecs/scripts/filter.py
-
curl -L -o filter.py https://huggingface.co/datasets/Jl-wei/DesignSpecs/resolve/main/scripts/filter.py
15.9 kB
| #!/usr/bin/env python3 | |
| """Select DESIGN.md specifications and write three JSONL files to a new directory. | |
| Requires Node.js and the external public @google/design.md 0.4.0 linter. | |
| Original bytes must round-trip through UTF-8; raw files that cannot are counted | |
| separately and omitted. No source files or existing output directories are changed. | |
| """ | |
| import argparse | |
| import hashlib | |
| import json | |
| import os | |
| import re | |
| import subprocess | |
| import sys | |
| import tempfile | |
| from pathlib import Path | |
| from urllib.parse import unquote, urlsplit | |
| FILE_FIELDS = ("sha256", "repo_id", "content", "path", "commit_sha", "source_url") | |
| REPOSITORY_FIELDS = ( | |
| "repo_id", "full_name", "storage_full_name", "default_branch", "commit_sha", | |
| "pinned_at", "metadata_fetched_at", "primary_language", "license_spdx_id", | |
| "license_name", "stars", "created_at", "pushed_at", "languages", "description", "topics", | |
| ) | |
| # One persistent Node process evaluates each distinct content. The public API's | |
| # findings are serialized directly, preserving their order and optional fields. | |
| NODE_LINTER = r""" | |
| import fs from 'node:fs'; | |
| import path from 'node:path'; | |
| import { createHash } from 'node:crypto'; | |
| import { pathToFileURL } from 'node:url'; | |
| import { createInterface } from 'node:readline'; | |
| const digest = bytes => createHash('sha256').update(bytes).digest('hex'); | |
| const modulePath = fs.realpathSync(process.argv[1]); | |
| const moduleHash = digest(fs.readFileSync(modulePath)); | |
| const metadata = { | |
| module_path: modulePath, module_sha256: moduleHash, | |
| official_package: '@google/design.md', official_package_version: '0.4.0', | |
| public_api: '@google/design.md/linter:lint', | |
| }; | |
| if (moduleHash === '6aaa4fd8bb979fa6d95d856ab72baf2d3643522e569f21eef9a9b91f5af37247') { | |
| metadata.identity_check = 'historical_bundle_sha256'; | |
| metadata.source_commit = '6e5da5382f41edbba9d73b2c62f33f32e9971f15'; | |
| } else { | |
| const packageRoot = path.resolve(path.dirname(modulePath), '../..'); | |
| const manifestPath = path.join(packageRoot, 'package.json'); | |
| const entrypoint = path.join(packageRoot, 'dist/linter/index.js'); | |
| const manifest = fs.existsSync(manifestPath) | |
| ? JSON.parse(fs.readFileSync(manifestPath, 'utf8')) : null; | |
| if (manifest?.name !== '@google/design.md' || manifest.version !== '0.4.0' || | |
| !fs.existsSync(entrypoint) || modulePath !== fs.realpathSync(entrypoint)) { | |
| throw new Error('Expected @google/design.md@0.4.0/dist/linter/index.js or the verified historical bundle.'); | |
| } | |
| metadata.identity_check = 'npm_package_manifest_and_public_entrypoint'; | |
| metadata.package_manifest = manifestPath; | |
| metadata.package_manifest_sha256 = digest(fs.readFileSync(manifestPath)); | |
| } | |
| const { lint } = await import(pathToFileURL(modulePath).href); | |
| if (typeof lint !== 'function') throw new Error('The official module must export public lint().'); | |
| console.log(JSON.stringify(metadata)); | |
| const groups = ['colors', 'typography', 'spacing', 'rounded', 'components']; | |
| for await (const line of createInterface({ input: process.stdin, crlfDelay: Infinity })) { | |
| const content = JSON.parse(line); | |
| const lines = content.replace(/^\uFEFF/, '').split(/\r?\n/); | |
| const header = lines[0] === '---' && lines.slice(1).includes('---'); | |
| try { | |
| const report = lint(content); | |
| if (!report || !Array.isArray(report.findings) || !report.summary || | |
| ['errors', 'warnings', 'infos'].some(key => | |
| !Number.isSafeInteger(report.summary[key]) || report.summary[key] < 0)) { | |
| throw new Error('Official lint() returned an invalid report.'); | |
| } | |
| const design = report.designSystem ?? {}; | |
| const named = typeof design.name === 'string' && design.name.trim().length > 0; | |
| const tokens = groups.some(group => design[group] instanceof Map && design[group].size > 0); | |
| const accepted = header && named && tokens && report.summary.errors === 0; | |
| console.log(JSON.stringify({ accepted, findings: accepted ? report.findings : [] })); | |
| } catch (error) { | |
| console.log(JSON.stringify({ accepted: false, findings: [], exception: String(error.message ?? error) })); | |
| } | |
| } | |
| """ | |
| def read_jsonl(path): | |
| with path.open(encoding="utf-8") as stream: | |
| for number, line in enumerate(stream, 1): | |
| try: | |
| row = json.loads(line) | |
| if not isinstance(row, dict): | |
| raise ValueError("Expected a JSON object") | |
| except ValueError as error: | |
| raise ValueError(f"{path}:{number}: {error}") from error | |
| yield row | |
| def read_json(path): | |
| return json.loads(path.read_text(encoding="utf-8")) | |
| def require(condition, message): | |
| if not condition: | |
| raise ValueError(message) | |
| def safe_parts(value): | |
| require(isinstance(value, str) and value and "\x00" not in value, "Invalid repository path") | |
| parts = value.split("/") | |
| require(all(part not in ("", ".", "..") for part in parts), "Unsafe repository path") | |
| return parts | |
| def raw_candidates(root): | |
| """Read verified downloads, including successful files from partial snapshots.""" | |
| require((root / "_metadata").is_dir(), "Raw collection has no _metadata directory") | |
| for snapshot_path in sorted((root / "_metadata").glob("*/*/snapshot.json")): | |
| snapshot = read_json(snapshot_path) | |
| if (snapshot.get("status") == "excluded_fork" or snapshot.get("public") is not True | |
| or snapshot.get("fork") is not False): | |
| continue | |
| storage = safe_parts(snapshot["storage_full_name"]) | |
| require(len(storage) == 2 and snapshot_path.parent == root / "_metadata" / Path(*storage), | |
| "Snapshot storage name does not match its location") | |
| metadata = read_json(snapshot_path.parent / "repository.json") | |
| require(metadata["id"] == snapshot["repo_id"], "Repository metadata identity mismatch") | |
| if metadata.get("private") is not False or metadata.get("fork") is not False: | |
| continue | |
| license_info = metadata.get("license") or {} | |
| languages_path = snapshot_path.parent / "languages.json" | |
| repository = { | |
| "repo_id": snapshot["repo_id"], "full_name": snapshot["canonical_full_name"], | |
| "storage_full_name": snapshot["storage_full_name"], | |
| "default_branch": snapshot.get("default_branch"), "commit_sha": snapshot.get("commit_sha"), | |
| "pinned_at": snapshot.get("pinned_at"), | |
| "metadata_fetched_at": snapshot.get("repository_metadata_fetched_at"), | |
| "primary_language": metadata.get("language"), "license_spdx_id": license_info.get("spdx_id"), | |
| "license_name": license_info.get("name"), "stars": metadata.get("stargazers_count"), | |
| "created_at": metadata.get("created_at"), "pushed_at": metadata.get("pushed_at"), | |
| "languages": read_json(languages_path) if languages_path.exists() else {}, | |
| "description": metadata.get("description"), "topics": metadata.get("topics") or [], | |
| } | |
| records_path = snapshot_path.parent / "files.jsonl" | |
| if not records_path.exists(): | |
| continue | |
| for record in read_jsonl(records_path): | |
| if record.get("status") != "downloaded": | |
| continue | |
| path = safe_parts(record["path"]) | |
| expected_path = "data/" + "/".join(storage + path) | |
| require(record["data_path"] == expected_path, "Download path does not match its provenance") | |
| target = root / expected_path | |
| require(target.resolve().is_relative_to(root.resolve()), "Download resolves outside collection root") | |
| data = target.read_bytes() | |
| blob = hashlib.sha1(b"blob " + str(len(data)).encode("ascii") + b"\0" + data).hexdigest() | |
| require(record["size"] == len(data) and record["blob_sha"] == blob, | |
| f"Downloaded byte size or Git blob hash mismatch: {target}") | |
| yield {"sha256": record["sha256"], "repo_id": record["repo_id"], | |
| "path": record["path"], "commit_sha": record["commit_sha"], | |
| "source_url": record.get("source_url")}, repository, data | |
| def dataset_candidates(root): | |
| """Re-evaluate a materialized dataset while preserving its recorded metadata.""" | |
| repositories = {} | |
| for record in read_jsonl(root / "repositories.jsonl"): | |
| repository = {field: record[field] for field in REPOSITORY_FIELDS} | |
| require(repository["repo_id"] not in repositories, "Duplicate repository ID") | |
| repositories[repository["repo_id"]] = repository | |
| contents = {} | |
| for record in read_jsonl(root / "contents.jsonl"): | |
| data = record["content"].encode("utf-8", errors="strict") | |
| require(hashlib.sha256(data).hexdigest() == record["sha256"], "Content SHA-256 mismatch") | |
| require(record["sha256"] not in contents, "Duplicate content SHA-256") | |
| contents[record["sha256"]] = record["content"] | |
| for record in read_jsonl(root / "files.jsonl"): | |
| row = {field: record[field] for field in FILE_FIELDS} | |
| require(row["repo_id"] in repositories, "File refers to an unknown repository") | |
| require(row["sha256"] in contents and contents[row["sha256"]] == row["content"], | |
| "File does not match its content record") | |
| row["content"] = contents[row["sha256"]] | |
| yield row, repositories[row["repo_id"]], row["content"].encode("utf-8", errors="strict") | |
| def node_reply(process): | |
| line = process.stdout.readline() | |
| if not line: | |
| raise RuntimeError("The official linter process stopped; see its error above") | |
| return json.loads(line) | |
| def filter_dataset(mode, source, output, module): | |
| require(not output.exists(), f"Output already exists: {output}") | |
| rows = raw_candidates(source) if mode == "raw" else dataset_candidates(source) | |
| counts = {"input_files": 0, "selected_files": 0, "rejected_files": 0, | |
| "invalid_utf8_files": 0, "linter_invocation_failures": 0} | |
| decisions, contents, repositories, files, identities = {}, {}, {}, [], set() | |
| with subprocess.Popen(["node", "--input-type=module", "-e", NODE_LINTER, str(module)], | |
| stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, | |
| encoding="utf-8") as process: | |
| linter = node_reply(process) | |
| try: | |
| for row, repository, data in rows: | |
| counts["input_files"] += 1 | |
| if counts["input_files"] % 2000 == 0: | |
| print(f"Checked {counts['input_files']} files", file=sys.stderr) | |
| sha = row["sha256"] | |
| require(hashlib.sha256(data).hexdigest() == sha, "File SHA-256 mismatch") | |
| require(type(row["repo_id"]) is int and row["repo_id"] == repository["repo_id"], | |
| "File repository identity mismatch") | |
| require(row["commit_sha"] == repository["commit_sha"] | |
| and re.fullmatch(r"[0-9a-f]{40}", row["commit_sha"]), "File commit mismatch") | |
| require(safe_parts(row["path"])[-1].casefold() == "design.md", "Unexpected filename") | |
| if row["source_url"] is not None: | |
| url = urlsplit(row["source_url"]) | |
| names = {repository["full_name"], repository["storage_full_name"]} | |
| expected = {f"/{name}/blob/{row['commit_sha']}/{row['path']}" for name in names} | |
| require(url.scheme == "https" and url.netloc == "github.com" | |
| and not url.query and not url.fragment and unquote(url.path) in expected, | |
| "File source URL does not match its repository, commit and path") | |
| identity = (row["repo_id"], row["commit_sha"], row["path"]) | |
| require(identity not in identities, f"Duplicate file identity: {identity}") | |
| identities.add(identity) | |
| try: | |
| content = row.get("content") | |
| if content is None: | |
| content = data.decode("utf-8", errors="strict") | |
| except UnicodeDecodeError: | |
| if mode != "raw": | |
| raise | |
| counts["invalid_utf8_files"] += 1 | |
| continue | |
| if sha not in decisions: | |
| # An exact header is necessary. Skip unrelated Markdown | |
| # before invoking the linter, without changing the rule. | |
| start = content.removeprefix("\ufeff") | |
| if not start.startswith(("---\n", "---\r\n")): | |
| result = {"accepted": False, "findings": []} | |
| else: | |
| process.stdin.write(json.dumps(content, ensure_ascii=False) + "\n") | |
| process.stdin.flush() | |
| result = node_reply(process) | |
| decisions[sha] = result | |
| counts["linter_invocation_failures"] += "exception" in result | |
| result = decisions[sha] | |
| if not result["accepted"]: | |
| counts["rejected_files"] += 1 | |
| continue | |
| if sha in contents: | |
| require(contents[sha] == content, "Different contents have the same SHA-256") | |
| else: | |
| contents[sha] = content | |
| if row["repo_id"] in repositories: | |
| require(repositories[row["repo_id"]] == repository, "Inconsistent repository metadata") | |
| repositories[row["repo_id"]] = repository | |
| row["content"] = contents[sha] | |
| row["linter_diagnostics"] = result["findings"] | |
| files.append(row) | |
| counts["selected_files"] += 1 | |
| finally: | |
| process.stdin.close() | |
| require(process.wait() == 0, "The official linter process failed") | |
| # Publish only after all input and linter checks finish. Reserve a new empty | |
| # destination so even an output created during filtering is never replaced. | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| with tempfile.TemporaryDirectory(prefix=".designspecs-filter-", dir=output.parent) as temporary: | |
| stage = Path(temporary) | |
| tables = { | |
| "contents": ({"sha256": sha, "content": contents[sha]} for sha in sorted(contents)), | |
| "files": sorted(files, key=lambda row: (row["repo_id"], row["commit_sha"], row["path"])), | |
| "repositories": (repositories[key] for key in sorted(repositories)), | |
| } | |
| for table, records in tables.items(): | |
| with (stage / f"{table}.jsonl").open("x", encoding="utf-8", newline="\n") as stream: | |
| for record in records: | |
| stream.write(json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":")) + "\n") | |
| output.mkdir() | |
| os.replace(stage, output) | |
| return {**counts, "unique_contents": len(contents), "repositories": len(repositories), | |
| "linter": linter, "output": str(output)} | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("mode", choices=("raw", "dataset"), help="Input is a raw collection or three JSONL files") | |
| parser.add_argument("source", type=Path) | |
| parser.add_argument("--output", type=Path, required=True, help="New directory for the three JSONL files") | |
| parser.add_argument("--linter-module", type=Path, default=os.environ.get("DESIGNMD_LINTER_MODULE"), | |
| help="Official 0.4.0 dist/linter/index.js or verified historical bundle; defaults to DESIGNMD_LINTER_MODULE") | |
| args = parser.parse_args() | |
| if args.linter_module is None: | |
| parser.error("Set --linter-module or DESIGNMD_LINTER_MODULE") | |
| result = filter_dataset(args.mode, args.source.resolve(), args.output.resolve(), args.linter_module) | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |