Spaces:
Paused
Paused
Download glyphforge.py from josephrw/afc-protocol: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/josephrw/afc-protocol/resolve/main/glyphforge.py
- Command line
-
hf download hf://spaces/josephrw/afc-protocol/glyphforge.py
-
curl -L -o glyphforge.py https://huggingface.co/spaces/josephrw/afc-protocol/resolve/main/glyphforge.py
12.3 kB
| """ | |
| GlyphForge β Recursive Glyph Production Engine | |
| ============================================== | |
| Seed β Grammar β Mutation β Receipt β Score β Archive β New Seed | |
| A glyph is not just a symbol. It is a compressed executable concept. | |
| The engine generates infinite descendants from a master glyph, | |
| scoring each by compression, meaning density, executability, proof strength, | |
| transferability, novelty, and commercial usefulness. | |
| Master glyph: β§β@L β H@L Γ R Γ Ξ»β»ΒΉ = β β $ | |
| """ | |
| import json | |
| import time | |
| import hashlib | |
| import random | |
| import os | |
| from dataclasses import dataclass, field, asdict | |
| from typing import Optional | |
| from pathlib import Path | |
| # --- Glyph Alphabet --- | |
| ALPHABET = { | |
| "β‘": "file", | |
| "β": "artifact", | |
| "β§": "stationary_object", | |
| "H": "hash_identity", | |
| "L": "location_anchor", | |
| "R": "receipt", | |
| "Ξ»": "friction", | |
| "Ξ»β»ΒΉ": "transferability_force", | |
| "T": "time_anchor", | |
| "Ξ£": "shard_set", | |
| "M": "merkle_root", | |
| "ZK": "zero_knowledge_proof", | |
| "Γ": "bind", | |
| "β": "derive_transfer", | |
| "Ξ": "change_delta", | |
| "β": "verified", | |
| "β": "invalid", | |
| "$": "financeable_value", | |
| "Ξ©": "canonical_source", | |
| "β²": "recursive_loop", | |
| } | |
| # --- Grammar Rules --- | |
| GRAMMAR = [ | |
| {"pattern": "{obj}@{loc}", "expansion": "object anchored at location", "produces": ["β‘@L", "β@L"]}, | |
| {"pattern": "{obj}@{loc} β {id}@{loc}", "expansion": "anchored object derives identity", "produces": ["β‘@L β H@L"]}, | |
| {"pattern": "{id} Γ {rec}", "expansion": "identity binds to receipt", "produces": ["H Γ R", "H@L Γ R"]}, | |
| {"pattern": "{rec} Γ {trans}", "expansion": "receipt binds to transferability", "produces": ["R Γ Ξ»β»ΒΉ"]}, | |
| {"pattern": "{bound} = {ver}", "expansion": "binding achieves verification", "produces": ["H@L Γ R Γ Ξ»β»ΒΉ = β"]}, | |
| {"pattern": "{ver} β {val}", "expansion": "verified becomes financeable", "produces": ["β β $"]}, | |
| {"pattern": "{shards} β {merkle}", "expansion": "shards aggregate to merkle root", "produces": ["Ξ£H β M"]}, | |
| {"pattern": "{merkle} Γ {zk}", "expansion": "merkle root binds to ZK proof", "produces": ["M Γ ZK"]}, | |
| {"pattern": "{time} Γ {delta}", "expansion": "time binds to file delta", "produces": ["TββTβ Γ Ξβ‘"]}, | |
| {"pattern": "{art} Γ {val}", "expansion": "artifact becomes financeable", "produces": ["β Γ $"]}, | |
| {"pattern": "{file} stays @ {loc} ; {rec} travels β", "expansion": "zero-copy transfer", "produces": ["β‘ stays @L ; R travels β"]}, | |
| {"pattern": "{lambda}β β {trans}β", "expansion": "lower friction increases transferability", "produces": ["Ξ»β β Tβ"]}, | |
| {"pattern": "{art} = {id}@{loc} Γ {rec} Γ {trans} Γ {val}", "expansion": "full financeable artifact", "produces": ["β = H@L Γ R Γ Ξ»β»ΒΉ Γ $"]}, | |
| {"pattern": "{delta_file} β {delta_hash} Γ {time}", "expansion": "file change produces delta hash bound to time", "produces": ["Ξβ‘ β HΞ Γ T"]}, | |
| {"pattern": "{build} β {rec} Γ {ver}", "expansion": "build passes and receipt verifies", "produces": ["Build β β R Γ β"]}, | |
| ] | |
| MASTER_GLYPH = "β§β@L β H@L Γ R Γ Ξ»β»ΒΉ = β β $" | |
| MUTATION_OPS = [ | |
| "bind_two", "split_shards", "invert_lambda", "attach_time", | |
| "attach_location", "attach_receipt", "attach_value", | |
| "replace_copy_with_zerocopy", "compress_to_symbol", "expand_to_schema", | |
| ] | |
| class ForgedGlyph: | |
| glyph_id: str = "" | |
| symbol: str = "" | |
| plain_english: str = "" | |
| role: str = "" | |
| parents: list = field(default_factory=list) | |
| mutation: str = "" | |
| hash: str = "" | |
| score: float = 0.0 | |
| score_breakdown: dict = field(default_factory=dict) | |
| created_at: float = 0.0 | |
| machine_payload: dict = field(default_factory=dict) | |
| generation: int = 0 | |
| def to_dict(self) -> dict: | |
| return asdict(self) | |
| def score_glyph(symbol: str, plain_english: str, role: str, machine_payload: dict) -> tuple[float, dict]: | |
| """Score a glyph by compression, meaning, executability, proof, transferability, novelty.""" | |
| breakdown = { | |
| "compression": 0.0, | |
| "meaning_density": 0.0, | |
| "machine_executability": 0.0, | |
| "proof_strength": 0.0, | |
| "transferability": 0.0, | |
| "novelty": 0.0, | |
| "commercial_usefulness": 0.0, | |
| "ambiguity_penalty": 0.0, | |
| "decorative_noise_penalty": 0.0, | |
| } | |
| token_count = len(symbol.replace(" ", "").split("Γ")) + symbol.count("β") + 1 | |
| meaning_tokens = sum(1 for t in ALPHABET if t in symbol) | |
| breakdown["compression"] = min(10, meaning_tokens / max(token_count, 1) * 5) | |
| breakdown["meaning_density"] = min(10, meaning_tokens * 1.5) | |
| if machine_payload: | |
| executable_keys = sum(1 for k in machine_payload if k in ("object", "anchor", "proof", "state", "metric")) | |
| breakdown["machine_executability"] = min(10, executable_keys * 2) | |
| proof_tokens = sum(1 for t in ["H", "R", "M", "ZK", "β"] if t in symbol) | |
| breakdown["proof_strength"] = min(10, proof_tokens * 2.5) | |
| if "Ξ»β»ΒΉ" in symbol or "Ξ»β" in symbol: | |
| breakdown["transferability"] = 8.0 | |
| elif "Ξ»" in symbol: | |
| breakdown["transferability"] = 4.0 | |
| if "$" in symbol: | |
| breakdown["commercial_usefulness"] = 9.0 | |
| elif "β" in symbol: | |
| breakdown["commercial_usefulness"] = 6.0 | |
| unique_chars = len(set(symbol.replace(" ", ""))) | |
| breakdown["novelty"] = min(10, unique_chars / 3) | |
| decorative = sum(1 for c in symbol if c in "β¦ββββ§β©βͺ") | |
| breakdown["decorative_noise_penalty"] = decorative * 2 | |
| if meaning_tokens < 2: | |
| breakdown["ambiguity_penalty"] = 5.0 | |
| total = sum(v for k, v in breakdown.items() if not k.endswith("penalty")) | |
| total -= sum(v for k, v in breakdown.items() if k.endswith("penalty")) | |
| return round(total, 2), breakdown | |
| def mutate_glyph(parent_symbol: str, parent_english: str, mutation: str) -> tuple[str, str, str, dict]: | |
| """Apply a mutation operation to a parent glyph.""" | |
| mutations = { | |
| "bind_two": lambda s, e: (s + " Γ R", e + " bound to receipt", "receipt_binding", {"object": "file", "proof": "receipt"}), | |
| "split_shards": lambda s, e: ("Ξ£" + s.replace("β", "").replace("β‘", ""), e + " sharded into pieces", "shard_split", {"shards": True, "merkle": True}), | |
| "invert_lambda": lambda s, e: (s.replace("Ξ»", "Ξ»β»ΒΉ") if "Ξ»" in s and "Ξ»β»ΒΉ" not in s else s + " Γ Ξ»β»ΒΉ", e + " with transferability force", "lambda_inversion", {"metric": "inverse_lambda"}), | |
| "attach_time": lambda s, e: (s + " Γ T", e + " anchored in time", "time_anchor", {"time": True}), | |
| "attach_location": lambda s, e: (s + " @L" if "@L" not in s else s, e + " anchored at location", "location_anchor", {"anchor": "location"}), | |
| "attach_receipt": lambda s, e: (s + " Γ R" if "R" not in s else s, e + " with receipt proof", "receipt_attach", {"proof": "receipt"}), | |
| "attach_value": lambda s, e: (s + " β $", e + " becomes financeable", "value_attach", {"economic_target": "paid"}), | |
| "replace_copy_with_zerocopy": lambda s, e: (s.replace("β β‘", "β R") if "β β‘" in s else "β‘ stays @L ; R travels β", e + " (zero-copy: file stays, receipt travels)", "zero_copy", {"zero_copy": True}), | |
| "compress_to_symbol": lambda s, e: ("β=H@LΓRΓΞ»β»ΒΉ=ββ$" if len(s) > 20 else s, "compressed: " + e, "compression", {"compressed": True}), | |
| "expand_to_schema": lambda s, e: (s, e + " expanded to machine schema", "schema_expansion", {"object": "artifact", "anchor": "location", "proof": "receipt", "metric": "lambda", "state": "verified"}), | |
| } | |
| op = mutations.get(mutation, mutations["bind_two"]) | |
| new_symbol, new_english, role, payload = op(parent_symbol, parent_english) | |
| return new_symbol, new_english, role, payload | |
| class GlyphForge: | |
| """Recursive glyph production engine.""" | |
| def __init__(self, max_generations: int = 10, min_score: float = 20.0): | |
| self.max_generations = max_generations | |
| self.min_score = min_score | |
| self.ledger: list[ForgedGlyph] = [] | |
| self.archive: dict[str, ForgedGlyph] = {} | |
| self.seed_glyph = MASTER_GLYPH | |
| self.seed_english = "A stationary artifact at location becomes hash-bound, receipt-bound, transferable, verified, and financeable." | |
| def forge(self, seed_symbol: str = None, seed_english: str = None, generations: int = None) -> list[ForgedGlyph]: | |
| """Run the forge loop: seed β mutate β score β archive β new seed.""" | |
| gens = generations or self.max_generations | |
| current_symbol = seed_symbol or self.seed_glyph | |
| current_english = seed_english or self.seed_english | |
| # Seed glyph | |
| seed = self._create_glyph(current_symbol, current_english, "master_seed", [], "seed", {}, gen=0) | |
| self.ledger.append(seed) | |
| self.archive[seed.glyph_id] = seed | |
| frontier = [seed] | |
| all_glyphs = [seed] | |
| for gen in range(1, gens + 1): | |
| next_frontier = [] | |
| for parent in frontier: | |
| for mutation in MUTATION_OPS: | |
| new_symbol, new_english, role, payload = mutate_glyph( | |
| parent.symbol, parent.plain_english, mutation | |
| ) | |
| if new_symbol == parent.symbol and new_english == parent.plain_english: | |
| continue | |
| child = self._create_glyph( | |
| new_symbol, new_english, role, | |
| [parent.glyph_id], mutation, payload, gen | |
| ) | |
| if child.score >= self.min_score: | |
| self.ledger.append(child) | |
| self.archive[child.glyph_id] = child | |
| all_glyphs.append(child) | |
| next_frontier.append(child) | |
| if not next_frontier: | |
| break | |
| # Keep top 5 per generation to prevent explosion | |
| next_frontier.sort(key=lambda g: g.score, reverse=True) | |
| frontier = next_frontier[:5] | |
| return all_glyphs | |
| def _create_glyph(self, symbol: str, english: str, role: str, | |
| parents: list, mutation: str, payload: dict, gen: int) -> ForgedGlyph: | |
| score, breakdown = score_glyph(symbol, english, role, payload) | |
| glyph_id = hashlib.sha256((symbol + str(time.time()) + str(gen)).encode()).hexdigest()[:12] | |
| return ForgedGlyph( | |
| glyph_id=glyph_id, | |
| symbol=symbol, | |
| plain_english=english, | |
| role=role, | |
| parents=parents, | |
| mutation=mutation, | |
| hash=hashlib.sha256(symbol.encode()).hexdigest(), | |
| score=score, | |
| score_breakdown=breakdown, | |
| created_at=time.time(), | |
| machine_payload=payload, | |
| generation=gen, | |
| ) | |
| def top_glyphs(self, n: int = 10) -> list[dict]: | |
| """Get the top N glyphs by score.""" | |
| sorted_glyphs = sorted(self.ledger, key=lambda g: g.score, reverse=True) | |
| return [g.to_dict() for g in sorted_glyphs[:n]] | |
| def by_generation(self) -> dict[int, list[dict]]: | |
| """Group glyphs by generation.""" | |
| gens: dict[int, list[dict]] = {} | |
| for g in self.ledger: | |
| gens.setdefault(g.generation, []).append(g.to_dict()) | |
| return gens | |
| def stream(self, n: int = 20) -> list[dict]: | |
| """Simulate a live production ticker.""" | |
| results = [] | |
| t = time.time() | |
| for i, g in enumerate(sorted(self.ledger, key=lambda x: x.created_at)[:n]): | |
| results.append({ | |
| "timestamp": time.strftime("%H:%M:%S", time.localtime(g.created_at)), | |
| "symbol": g.symbol, | |
| "score": g.score, | |
| "role": g.role, | |
| "gen": g.generation, | |
| }) | |
| return results | |
| def to_json(self) -> str: | |
| return json.dumps({ | |
| "master_glyph": self.seed_glyph, | |
| "total_glyphs": len(self.ledger), | |
| "generations": max(g.generation for g in self.ledger) if self.ledger else 0, | |
| "top": self.top_glyphs(10), | |
| "ledger": [g.to_dict() for g in self.ledger], | |
| }, indent=2) | |