Spaces:
Sleeping
Sleeping
Update app.py
Browse files1234567133 unmodified lines1411421431441451461476 unmodified lines15415515615715815916014 unmodified lines17517617717817918018110 unmodified lines19219319419519619719820 unmodified lines21922022122222322422553 unmodified lines27928028128228328428528628728828910 unmodified lines30030130230330430530630718 unmodified lines32632732832933033133233333433533633733833934034134234334434534632 unmodified lines37938038138238338438511 unmodified lines3973983994004014024035 unmodified lines40941041141241341441541646 unmodified lines463464465466467468469470"""================================================================================SCRIPT 2: THE HYSE SERVER (HUGGINGFACE SPACE NATIVE) - V9.7 1-SHOT ONTOLOGY1-Shot Semantic Scrubbing | Anti-History Forcing | Comma-Separated BrainstormsRequires: pip install llama-cpp-python sentence-transformers fastapi uvicorn requests================================================================================"""133 unmodified linesgc.collect()def run_7b_extract(self, text: str) -> str:""" V9.7: 1-Shot De-Semanticization explicitly showing how to strip nouns """prompt = (f"<|im_start|>system\nYou translate specific problems into pure abstract geometry and systems dynamics. "f"CRITICAL: Strip ALL domain nouns (e.g., biology, finance). Output exactly 1 sentence.<|im_end|>\n"6 unmodified linesexcept: return "Extraction failed."def run_7b_blind_brainstorm(self, abstract_mechanism: str, axioms_dict: Dict[str, str], mode: str) -> List[str]:""" V9.7: 1-Shot Comma-Separated Output to guarantee robust Wikipedia targeting """axiom_str = "\n".join([f"- {k}: {v}" for k, v in axioms_dict.items()])prompts = {14 unmodified linesoutput = self.active_llm(prompt, max_tokens=150, temperature=0.6, stop=["<|im_end|>"])text = output['choices'][0]['text'].strip()# Simple, bulletproof parsingtopics = [t.strip().replace('"', '').replace("'", "") for t in text.split(',')]topics = [t for t in topics if len(t) > 3 and not "Here are" in t]10 unmodified linesreturn fallbacks.get(mode, fallbacks["mirrors"])def run_3b_extract(self, text: str) -> str:""" V9.7: 1-Shot Anti-History and Name Stripping """prompt = (f"<|im_start|>system\nYou translate textbook descriptions into abstract structural mechanisms. "f"CRITICAL: IGNORE ALL HUMAN NAMES (e.g., Ilya Prigogine, Lev Landau), dates, and historical filler. Focus ONLY on the math/physics. Output exactly 1 sentence.<|im_end|>\n"20 unmodified lineschunks = []session = requests.Session()session.headers.update({'User-Agent': 'IsomorphicEngineBot/9.7 (https://huggingface.co/spaces/everydaytok/Small_llm; contact@example.com)'})for q in set(search_queries):53 unmodified linesclass Substrate:doc_id: str; title: str; text: str; radii: Dict[str, float]; embedding: np.ndarraydef r(self, a: str) -> float: return self.radii.get(a, 0.0)def dominant(self, t: float = 0.70) -> List[str]: return [a for a in self.radii if self.r(a) >= t]def calculate_gaps(q: Substrate, c: Substrate) -> Dict:g1 = [{"axiom": a, "direction": "gain" if c.r(a)-q.r(a) > 0 else "release", "delta": round(c.r(a)-q.r(a), 3)} for a in q.radii if abs(c.r(a)-q.r(a)) >= 0.15]return {"G1_gains": [f"{s['axiom']} (+{s['delta']})" for s in g1 if s["direction"] == "gain"][:3], "G1_releases": [f"{s['axiom']} ({s['delta']})" for s in g1 if s["direction"] == "release"][:3]}# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# THE HySE PIPELINE10 unmodified linesq_rad, q_emb = MANAGER.score_mechanism(q_mech)q_sub = Substrate("QUERY", "User Query", q_mech, q_rad, q_emb)top_axiom_names = q_sub.dominant(0.70)[:5]if not top_axiom_names: top_axiom_names = sorted(q_rad, key=q_rad.get, reverse=True)[:5]blindfold_dict = {name: SEED_AXIOMS[name] for name in top_axiom_names}set_status("7B Generating Wikipedia Targets (Named Laws/Models)...")18 unmodified linesfor chunk in chunks:mech = MANAGER.run_3b_extract(chunk["text"])if mech == "Extraction failed.": continuerad, emb = MANAGER.score_mechanism(mech)sub = Substrate(chunk["doc_id"], chunk["title"], mech, rad, emb)vec_score = max(0.0, float(np.dot(q_sub.embedding, sub.embedding)))# V9.7: Opposites shouldn't be penalized for lacking the original query's axiomsif mode == "opposites":score = vec_scoreelse:gate = sum(1 for a in top_axiom_names if sub.r(a) >= 0.35) / max(len(top_axiom_names), 1)score = vec_score * 0.6 + gate * 0.4gaps = calculate_gaps(q_sub, sub)results.append({"title": sub.title, "score": round(score, 3), "mechanism": mech, **gaps})results.sort(key=lambda x: x["score"], reverse=True)unique_results = []32 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):log("Booting HySE Engine V9.7 (1-Shot Prompting)...")MANAGER.load_st()def pre_fetch():11 unmodified linesapp = FastAPI(title="HySE Reverse Engineering Engine", lifespan=lifespan)HTML = r"""<!DOCTYPE html><html><head><title>HySE V9.7 - 1-Shot Ontology</title><style>body{background:#070707;color:#e0e0e0;font-family:monospace;display:flex;height:100vh;margin:0;}.side{width:320px;background:#0b0b0b;padding:15px;border-right:1px solid #1a1a1a;overflow-y:auto;}5 unmodified lines.log{font-size:10px;color:#606060;height:150px;overflow-y:auto;border:1px solid #1a1a1a;padding:5px;}</style></head><body><div class="side"><h2 style="color:#7ec8e3;">HySE V9.7</h2><div style="font-size:10px;color:#606060;margin-bottom:15px;">1-Shot LLM Anti-Leakage | Strict Law Fetching</div><textarea id="q" rows="5">A virus infects a host, rapidly replicating and jumping to new hosts until immunity acts as a wall causing collapse.</textarea><button onclick="run()">βΆ Start Reverse Engineering</button><div id="prog" style="margin:15px 0;color:#7ee37e;">Idle</div>46 unmodified lines<div style="display:flex;justify-content:space-between;font-weight:bold;"><span>π ${r.title}</span><span style="color:#e3c07e;">Score: ${(r.score*100).toFixed(1)}%</span></div><div style="color:#7ee3c8;margin:8px 0;font-style:italic;">${r.mechanism}</div><div style="font-size:10px;color:#606060;"><span style="color:#7ee37e">Gains: ${r.G1_gains.join(', ') || 'None'}</span> |<span style="color:#e37e7e">Releases: ${r.G1_releases.join(', ') || 'None'}</span></div></div>`;}1234567133 unmodified lines1411421431441451461476 unmodified lines15415515615715815916014 unmodified lines17517617717817918010 unmodified lines19119219319419519619720 unmodified lines21821922022122222322453 unmodified lines27827928028128228328428528628728828929029129229329429529629710 unmodified lines30830931031131231331431531631731831932018 unmodified lines33934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037132 unmodified lines40440540640740840941011 unmodified lines4224234244254264274285 unmodified lines43443543643743843944044146 unmodified lines488489490491492493494495496497"""================================================================================SCRIPT 2: THE HYSE SERVER (HUGGINGFACE SPACE NATIVE) - V9.8 TRUE ONTOLOGYDynamic Axiom Gates | SR4 Complement Scoring | 1-Shot Semantic ScrubbingRequires: pip install llama-cpp-python sentence-transformers fastapi uvicorn requests================================================================================"""133 unmodified linesgc.collect()def run_7b_extract(self, text: str) -> str:""" V9.8: 1-Shot De-Semanticization explicitly showing how to strip nouns """prompt = (f"<|im_start|>system\nYou translate specific problems into pure abstract geometry and systems dynamics. "f"CRITICAL: Strip ALL domain nouns (e.g., biology, finance). Output exactly 1 sentence.<|im_end|>\n"6 unmodified linesexcept: return "Extraction failed."def run_7b_blind_brainstorm(self, abstract_mechanism: str, axioms_dict: Dict[str, str], mode: str) -> List[str]:""" V9.8: 1-Shot Comma-Separated Output to guarantee robust Wikipedia targeting """axiom_str = "\n".join([f"- {k}: {v}" for k, v in axioms_dict.items()])prompts = {14 unmodified linesoutput = self.active_llm(prompt, max_tokens=150, temperature=0.6, stop=["<|im_end|>"])text = output['choices'][0]['text'].strip()topics = [t.strip().replace('"', '').replace("'", "") for t in text.split(',')]topics = [t for t in topics if len(t) > 3 and not "Here are" in t]10 unmodified linesreturn fallbacks.get(mode, fallbacks["mirrors"])def run_3b_extract(self, text: str) -> str:""" V9.8: 1-Shot Anti-History and Name Stripping """prompt = (f"<|im_start|>system\nYou translate textbook descriptions into abstract structural mechanisms. "f"CRITICAL: IGNORE ALL HUMAN NAMES (e.g., Ilya Prigogine, Lev Landau), dates, and historical filler. Focus ONLY on the math/physics. Output exactly 1 sentence.<|im_end|>\n"20 unmodified lineschunks = []session = requests.Session()session.headers.update({'User-Agent': 'IsomorphicEngineBot/9.8 (https://huggingface.co/spaces/everydaytok/Small_llm; contact@example.com)'})for q in set(search_queries):53 unmodified linesclass Substrate:doc_id: str; title: str; text: str; radii: Dict[str, float]; embedding: np.ndarraydef r(self, a: str) -> float: return self.radii.get(a, 0.0)def dominant(self, t: float = 0.55) -> List[str]: return [a for a in self.radii if self.r(a) >= t]def calculate_gaps(q: Substrate, c: Substrate) -> Dict:g1 = [{"axiom": a, "direction": "gain" if c.r(a)-q.r(a) > 0 else "release", "delta": round(c.r(a)-q.r(a), 3)} for a in q.radii if abs(c.r(a)-q.r(a)) >= 0.15]q_dom = set(q.dominant(0.55)) or set(sorted(q.radii, key=q.radii.get, reverse=True)[:4])c_dom = set(c.dominant(0.55)) or set(sorted(c.radii, key=c.radii.get, reverse=True)[:4])return {"G1_gains": [f"{s['axiom']} (+{s['delta']})" for s in g1 if s["direction"] == "gain"][:3],"G1_releases": [f"{s['axiom']} ({s['delta']})" for s in g1 if s["direction"] == "release"][:3],"G4_shared": sorted(list(q_dom & c_dom)),"G4_borrow": sorted(list(c_dom - q_dom))}# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ# THE HySE PIPELINE10 unmodified linesq_rad, q_emb = MANAGER.score_mechanism(q_mech)q_sub = Substrate("QUERY", "User Query", q_mech, q_rad, q_emb)# V9.8 FIX 1: Robust Dominant Axis Extractiontop_axiom_names = [a for a in q_rad if q_rad[a] >= 0.55]if len(top_axiom_names) < 4:top_axiom_names = sorted(q_rad, key=q_rad.get, reverse=True)[:5]else:top_axiom_names = top_axiom_names[:6]blindfold_dict = {name: SEED_AXIOMS[name] for name in top_axiom_names}set_status("7B Generating Wikipedia Targets (Named Laws/Models)...")18 unmodified linesfor chunk in chunks:mech = MANAGER.run_3b_extract(chunk["text"])if mech == "Extraction failed.": continuerad, emb = MANAGER.score_mechanism(mech)sub = Substrate(chunk["doc_id"], chunk["title"], mech, rad, emb)gaps = calculate_gaps(q_sub, sub)vec_score = max(0.0, float(np.dot(q_sub.embedding, sub.embedding)))gate = sum(1 for a in top_axiom_names if sub.r(a) >= 0.45) / max(len(top_axiom_names), 1)# V9.8 FIX 2 & 3: Dynamic Scoring and Gatesscore = 0.0if mode == "mirrors":score = vec_score * 0.6 + gate * 0.4elif mode == "more_completes":if len(gaps["G4_borrow"]) == 0:score = 0.0 # Must add something newelse:score = vec_score * 0.5 + gate * 0.5elif mode == "opposites":if len(gaps["G4_shared"]) == 0:score = 0.0 # Must share a foundation to be an oppositeelse:# SR4 Complement Logiccomplement = sum((1.0 - q_sub.r(a)) * sub.r(a) for a in AXIOM_NAMES) / N_AXIOMSscore = complement * 0.7 + (1.0 - vec_score) * 0.3if score > 0.05:results.append({"title": sub.title, "score": round(score, 3), "mechanism": mech, **gaps})results.sort(key=lambda x: x["score"], reverse=True)unique_results = []32 unmodified lines@asynccontextmanagerasync def lifespan(app: FastAPI):log("Booting HySE Engine V9.8 (True Ontology)...")MANAGER.load_st()def pre_fetch():11 unmodified linesapp = FastAPI(title="HySE Reverse Engineering Engine", lifespan=lifespan)HTML = r"""<!DOCTYPE html><html><head><title>HySE V9.8 - True Ontology</title><style>body{background:#070707;color:#e0e0e0;font-family:monospace;display:flex;height:100vh;margin:0;}.side{width:320px;background:#0b0b0b;padding:15px;border-right:1px solid #1a1a1a;overflow-y:auto;}5 unmodified lines.log{font-size:10px;color:#606060;height:150px;overflow-y:auto;border:1px solid #1a1a1a;padding:5px;}</style></head><body><div class="side"><h2 style="color:#7ec8e3;">HySE V9.8</h2><div style="font-size:10px;color:#606060;margin-bottom:15px;">Dynamic Axiom Gates | SR4 Complement Scores</div><textarea id="q" rows="5">A virus infects a host, rapidly replicating and jumping to new hosts until immunity acts as a wall causing collapse.</textarea><button onclick="run()">βΆ Start Reverse Engineering</button><div id="prog" style="margin:15px 0;color:#7ee37e;">Idle</div>46 unmodified lines<div style="display:flex;justify-content:space-between;font-weight:bold;"><span>π ${r.title}</span><span style="color:#e3c07e;">Score: ${(r.score*100).toFixed(1)}%</span></div><div style="color:#7ee3c8;margin:8px 0;font-style:italic;">${r.mechanism}</div><div style="font-size:10px;color:#606060;"><div style="color:#7ec8e3; margin-bottom:2px;">Shared: ${r.G4_shared.join(', ') || 'None'}</div><div style="color:#e3c07e; margin-bottom:4px;">Borrow: ${r.G4_borrow.join(', ') || 'None'}</div><span style="color:#7ee37e">G1 Gains: ${r.G1_gains.join(', ') || 'None'}</span> |<span style="color:#e37e7e">G1 Releases: ${r.G1_releases.join(', ') || 'None'}</span></div></div>`;}
app.py+53-26