everydaytok commited on
Commit
ec4bf69
Β·
verified Β·
1 Parent(s): c4e353c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -11
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  """
2
  ╔══════════════════════════════════════════════════════════════════════════════╗
3
  β•‘ ISOMORPHIC SUBSTRATE SYSTEM β€” V8.9 (THE REAL-TIME ENGINE) β•‘
@@ -16,6 +17,7 @@ from enum import Enum
16
  from contextlib import asynccontextmanager
17
 
18
  import numpy as np
 
19
  from fastapi import FastAPI, Request
20
  from fastapi.responses import HTMLResponse, JSONResponse
21
  import uvicorn
@@ -26,7 +28,7 @@ try:
26
  from sentence_transformers import SentenceTransformer
27
  from llama_cpp import Llama
28
  except ImportError:
29
- print("Please ensure: pip install sentence-transformers llama-cpp-python wikipedia-api huggingface_hub fastapi uvicorn")
30
 
31
  # ══════════════════════════════════════════════════════════════════════
32
  # TUNABLE CONSTANTS
@@ -252,7 +254,7 @@ class DualModelManager:
252
  return scores_list, list(normed)
253
 
254
  # ══════════════════════════════════════════════════════════════════════
255
- # 3. WIKIPEDIA FETCHER (MACRO / MICRO RESTORED)
256
  # ══════════════════════════════════════════════════════════════════════
257
 
258
  def fetch_wikipedia_chunks(topics: List[str]) -> List[Dict]:
@@ -260,16 +262,26 @@ def fetch_wikipedia_chunks(topics: List[str]) -> List[Dict]:
260
  Dynamically pulls from Wikipedia and utilizes the MACRO/MICRO
261
  Sliding Window chunking to ensure zero context loss.
262
  """
263
- wiki = wikipediaapi.Wikipedia(user_agent="IsomorphicEngine/8.9", language="en", extract_format=wikipediaapi.ExtractFormat.WIKI)
264
- import requests
 
265
  all_titles = set()
 
266
 
267
  for term in topics:
268
  try:
269
- resp = requests.get("https://en.wikipedia.org/w/api.php", params={"action": "query", "list": "search", "srsearch": term, "srlimit": 2, "format": "json"}, timeout=5)
 
 
 
 
 
 
 
270
  results = resp.json().get("query", {}).get("search", [])
271
  for r in results: all_titles.add(r["title"])
272
- except: pass
 
273
 
274
  chunks = []
275
  for title in list(all_titles)[:CANDIDATES_TO_FETCH]:
@@ -305,7 +317,7 @@ def fetch_wikipedia_chunks(topics: List[str]) -> List[Dict]:
305
  micro_count += 1
306
  idx += 100 # Shift by 100 ensures a 50-word overlap
307
  except Exception as e:
308
- log(f"Wiki parse error on {title}: {e}")
309
  pass
310
 
311
  return chunks
@@ -420,7 +432,7 @@ MANAGER = DualModelManager()
420
 
421
  @asynccontextmanager
422
  async def lifespan(app: FastAPI):
423
- log("=== V8.9 Booting (Dual-Model + Macro/Micro Chunking) ===")
424
  MANAGER.load_st()
425
  threading.Thread(target=MANAGER.pre_cache_models, daemon=True).start()
426
  yield
@@ -485,11 +497,17 @@ textarea, select, input{width:100%; background:var(--bg); border:1px solid var(-
485
  let lastData = null;
486
  let lastTime = null;
487
 
 
 
 
 
 
 
 
488
  async function poll(){
489
  try{
490
  const d = await fetch("/api/status").then(r=>r.json());
491
 
492
- // Update logs
493
  if(d.build_log){
494
  const lb = document.getElementById("eng-log");
495
  lb.innerHTML = d.build_log.map(l => `<div>${l.replace(/&/g,"&amp;").replace(/</g,"&lt;")}</div>`).join("");
@@ -510,12 +528,14 @@ async function poll(){
510
  }
511
  }catch(e){}
512
  }
513
- setInterval(poll, 1500); poll();
514
 
515
  async function run(){
 
 
516
  document.getElementById("res").innerHTML = `<div style="color:var(--yel); text-align:center; padding:30px;">⟳ Initiating Real-Time Pipeline...</div>`;
517
  await fetch("/api/search", {
518
- method:"POST", body:JSON.stringify({query_text:document.getElementById("q").value, objective:document.getElementById("obj").value})
519
  });
520
  }
521
 
 
1
+
2
  """
3
  ╔══════════════════════════════════════════════════════════════════════════════╗
4
  β•‘ ISOMORPHIC SUBSTRATE SYSTEM β€” V8.9 (THE REAL-TIME ENGINE) β•‘
 
17
  from contextlib import asynccontextmanager
18
 
19
  import numpy as np
20
+ import requests
21
  from fastapi import FastAPI, Request
22
  from fastapi.responses import HTMLResponse, JSONResponse
23
  import uvicorn
 
28
  from sentence_transformers import SentenceTransformer
29
  from llama_cpp import Llama
30
  except ImportError:
31
+ print("Please ensure: pip install sentence-transformers llama-cpp-python wikipedia-api huggingface_hub fastapi uvicorn requests")
32
 
33
  # ══════════════════════════════════════════════════════════════════════
34
  # TUNABLE CONSTANTS
 
254
  return scores_list, list(normed)
255
 
256
  # ══════════════════════════════════════════════════════════════════════
257
+ # 3. WIKIPEDIA FETCHER (USER-AGENT PATCH & MACRO/MICRO)
258
  # ══════════════════════════════════════════════════════════════════════
259
 
260
  def fetch_wikipedia_chunks(topics: List[str]) -> List[Dict]:
 
262
  Dynamically pulls from Wikipedia and utilizes the MACRO/MICRO
263
  Sliding Window chunking to ensure zero context loss.
264
  """
265
+ user_agent = "IsomorphicEngine/8.9 (research_bot@example.com)"
266
+ wiki = wikipediaapi.Wikipedia(user_agent=user_agent, language="en", extract_format=wikipediaapi.ExtractFormat.WIKI)
267
+
268
  all_titles = set()
269
+ headers = {"User-Agent": user_agent}
270
 
271
  for term in topics:
272
  try:
273
+ clean_term = term.replace("_", " ")
274
+ resp = requests.get(
275
+ "https://en.wikipedia.org/w/api.php",
276
+ params={"action": "query", "list": "search", "srsearch": clean_term, "srlimit": 2, "format": "json"},
277
+ headers=headers,
278
+ timeout=5
279
+ )
280
+ resp.raise_for_status()
281
  results = resp.json().get("query", {}).get("search", [])
282
  for r in results: all_titles.add(r["title"])
283
+ except Exception as e:
284
+ log(f"Search API Error for '{term}': {e}")
285
 
286
  chunks = []
287
  for title in list(all_titles)[:CANDIDATES_TO_FETCH]:
 
317
  micro_count += 1
318
  idx += 100 # Shift by 100 ensures a 50-word overlap
319
  except Exception as e:
320
+ log(f"Wiki page parse error on '{title}': {e}")
321
  pass
322
 
323
  return chunks
 
432
 
433
  @asynccontextmanager
434
  async def lifespan(app: FastAPI):
435
+ log("=== V8.9 Booting (Dual-Model + Macro/Micro + Safe Web Fetch) ===")
436
  MANAGER.load_st()
437
  threading.Thread(target=MANAGER.pre_cache_models, daemon=True).start()
438
  yield
 
497
  let lastData = null;
498
  let lastTime = null;
499
 
500
+ // Recover user query input on refresh
501
+ window.onload = function() {
502
+ const savedQuery = localStorage.getItem("iso_query");
503
+ if (savedQuery) document.getElementById("q").value = savedQuery;
504
+ poll(); // Force immediate status check
505
+ };
506
+
507
  async function poll(){
508
  try{
509
  const d = await fetch("/api/status").then(r=>r.json());
510
 
 
511
  if(d.build_log){
512
  const lb = document.getElementById("eng-log");
513
  lb.innerHTML = d.build_log.map(l => `<div>${l.replace(/&/g,"&amp;").replace(/</g,"&lt;")}</div>`).join("");
 
528
  }
529
  }catch(e){}
530
  }
531
+ setInterval(poll, 1500);
532
 
533
  async function run(){
534
+ const query = document.getElementById("q").value;
535
+ localStorage.setItem("iso_query", query); // Save for page refreshes
536
  document.getElementById("res").innerHTML = `<div style="color:var(--yel); text-align:center; padding:30px;">⟳ Initiating Real-Time Pipeline...</div>`;
537
  await fetch("/api/search", {
538
+ method:"POST", body:JSON.stringify({query_text:query, objective:document.getElementById("obj").value})
539
  });
540
  }
541