spanofzero commited on
Commit
2e8bbbb
·
verified ·
1 Parent(s): addd714

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +35 -16
app.py CHANGED
@@ -4,12 +4,12 @@ from array import array
4
  from functools import lru_cache
5
  import os, re, time, asyncio
6
 
7
- # 1. API Configuration - Switched to 1.5B for 4x faster cloud responses
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
- MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct" # Faster, leaner, demo-optimized
10
  client = AsyncInferenceClient(MODEL_ID, token=HF_TOKEN)
11
 
12
- # 2. T3 High-Speed Logic Kernel (Local CPU Execution)
13
  class StateController:
14
  __slots__ = ("_state", "_rom60", "_symbols", "_rendered")
15
  def __init__(self):
@@ -18,7 +18,7 @@ class StateController:
18
  self._symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"
19
  self._rendered = "".join(" [NODE_120] " if i == 120 else ("<" if i % 10 == 0 else ".") for i in range(121))
20
 
21
- @lru_cache(maxsize=128) # Optimization from your refactor
22
  def compute_distribution(self, total, nodes) -> str:
23
  if nodes <= 0: return "Error: Node count must be positive."
24
  base, rem = divmod(total, nodes)
@@ -36,20 +36,21 @@ def format_telemetry(seconds: float) -> str:
36
  if seconds < 0.001: return f"{seconds * 1_000_000:.2f} \u03BCs"
37
  return f"{seconds * 1_000:.2f} ms" if seconds < 1 else f"{seconds:.2f} s"
38
 
39
- # 3. Hardened Dual-Response Logic (Async Optimized)
40
  async def generate_responses(user_message, p_hist, c_hist):
41
  msg = user_message.strip()
42
  if not msg: yield p_hist or [], c_hist or [], ""; return
43
 
44
  p_hist, c_hist = p_hist or [], c_hist or []
45
- p_hist.append({"role": "user", "content": msg}); p_hist.append({"role": "assistant", "content": ""})
46
- c_hist.append({"role": "user", "content": msg}); c_hist.append({"role": "assistant", "content": ""})
 
 
47
  yield p_hist, c_hist, ""
48
 
49
  start_time = time.perf_counter()
50
 
51
- # --- HARDENED LOCAL INTERCEPTORS ---
52
- # Using the refined regex from your refactor
53
  dist_match = re.search(r"(?P<units>\d{1,9})\s+units\s+across\s+(?P<nodes>\d{1,4})\s+nodes", msg, re.I)
54
  diag_match = any(kw in msg.lower() for kw in ["diagnostic", "grid"])
55
 
@@ -63,30 +64,46 @@ async def generate_responses(user_message, p_hist, c_hist):
63
  p_hist[-1]["content"] = f"{res}\n\n---\n*Telemetry: {format_telemetry(elapsed)} | Source: LOCAL T3 KERNEL*"
64
  yield p_hist, c_hist, ""
65
  else:
66
- # ASYNC PRIMARY STREAM
67
  try:
68
  res_text = ""
69
- async for chunk in client.chat_completion(messages=[{"role":"system","content":"Logic Engine"}] + p_hist[:-1], max_tokens=512, stream=True, temperature=0.1):
 
 
 
 
 
 
 
70
  res_text += (chunk.choices[0].delta.content or "")
71
  p_hist[-1]["content"] = res_text
72
  yield p_hist, c_hist, ""
73
  p_hist[-1]["content"] += f"\n\n---\n*Telemetry: {format_telemetry(time.perf_counter()-start_time)} | Source: AUGMENTED CLOUD*"
 
74
  except Exception as e:
75
  p_hist[-1]["content"] = f"Primary Error: {str(e)}"
76
- yield p_hist, c_hist, ""
77
 
78
- # ASYNC VANILLA STREAM
79
  comp_start = time.perf_counter()
80
  c_hist[-1]["content"] = "*Routing...*"
81
  yield p_hist, c_hist, ""
82
 
83
  try:
84
  res_text = ""
85
- async for chunk in client.chat_completion(messages=[{"role":"system","content":"Standard AI"}] + c_hist[:-1], max_tokens=512, stream=True, temperature=0.7):
 
 
 
 
 
 
 
86
  res_text += (chunk.choices[0].delta.content or "")
87
  c_hist[-1]["content"] = res_text
88
  yield p_hist, c_hist, ""
89
  c_hist[-1]["content"] += f"\n\n---\n*Telemetry: {format_telemetry(time.perf_counter()-comp_start)} | Source: VANILLA CLOUD*"
 
90
  except Exception as e:
91
  c_hist[-1]["content"] = f"Competitor Error: {str(e)}"
92
  yield p_hist, c_hist, ""
@@ -99,12 +116,14 @@ with gr.Blocks() as demo:
99
  p_chat = gr.Chatbot(label="Augmented Logic Kernel (T3 Architecture)", height=350)
100
  with gr.Row():
101
  msg_in = gr.Textbox(label="Message", placeholder="Test P vs NP or Logistics Distribution...", scale=8)
102
- btn = gr.Button("Execute", scale=1, variant="primary")
 
103
  gr.Examples(examples=["Define P vs. NP. Then validate a 120-unit distribution across 3 nodes.", "Run grid diagnostic"], inputs=msg_in)
 
104
  c_chat = gr.Chatbot(label="Vanilla Qwen 2.5 (Standard Infrastructure)", height=350)
105
 
106
  msg_in.submit(generate_responses, [msg_in, p_chat, c_chat], [p_chat, c_chat, msg_in])
107
- btn.click(generate_responses, [msg_in, p_chat, c_chat], [p_chat, c_chat, msg_in])
108
 
109
  if __name__ == "__main__":
110
  demo.queue().launch(theme=gr.themes.Soft(primary_hue="orange"), css=custom_css)
 
4
  from functools import lru_cache
5
  import os, re, time, asyncio
6
 
7
+ # 1. API Configuration
8
  HF_TOKEN = os.getenv("HF_TOKEN")
9
+ MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
10
  client = AsyncInferenceClient(MODEL_ID, token=HF_TOKEN)
11
 
12
+ # 2. T3 High-Speed Logic Kernel
13
  class StateController:
14
  __slots__ = ("_state", "_rom60", "_symbols", "_rendered")
15
  def __init__(self):
 
18
  self._symbols = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567"
19
  self._rendered = "".join(" [NODE_120] " if i == 120 else ("<" if i % 10 == 0 else ".") for i in range(121))
20
 
21
+ @lru_cache(maxsize=128)
22
  def compute_distribution(self, total, nodes) -> str:
23
  if nodes <= 0: return "Error: Node count must be positive."
24
  base, rem = divmod(total, nodes)
 
36
  if seconds < 0.001: return f"{seconds * 1_000_000:.2f} \u03BCs"
37
  return f"{seconds * 1_000:.2f} ms" if seconds < 1 else f"{seconds:.2f} s"
38
 
39
+ # 3. Core Response Logic (Async Corrected)
40
  async def generate_responses(user_message, p_hist, c_hist):
41
  msg = user_message.strip()
42
  if not msg: yield p_hist or [], c_hist or [], ""; return
43
 
44
  p_hist, c_hist = p_hist or [], c_hist or []
45
+ p_hist.append({"role": "user", "content": msg})
46
+ p_hist.append({"role": "assistant", "content": ""})
47
+ c_hist.append({"role": "user", "content": msg})
48
+ c_hist.append({"role": "assistant", "content": ""})
49
  yield p_hist, c_hist, ""
50
 
51
  start_time = time.perf_counter()
52
 
53
+ # --- LOCAL INTERCEPTORS ---
 
54
  dist_match = re.search(r"(?P<units>\d{1,9})\s+units\s+across\s+(?P<nodes>\d{1,4})\s+nodes", msg, re.I)
55
  diag_match = any(kw in msg.lower() for kw in ["diagnostic", "grid"])
56
 
 
64
  p_hist[-1]["content"] = f"{res}\n\n---\n*Telemetry: {format_telemetry(elapsed)} | Source: LOCAL T3 KERNEL*"
65
  yield p_hist, c_hist, ""
66
  else:
67
+ # ASYNC PRIMARY STREAM (Corrected with 'await' for the stream object)
68
  try:
69
  res_text = ""
70
+ # FIX: We must await the chat_completion call to get the AsyncIterable
71
+ stream = await client.chat_completion(
72
+ messages=[{"role":"system","content":"Logic Engine"}] + p_hist[:-1],
73
+ max_tokens=512,
74
+ stream=True,
75
+ temperature=0.1
76
+ )
77
+ async for chunk in stream:
78
  res_text += (chunk.choices[0].delta.content or "")
79
  p_hist[-1]["content"] = res_text
80
  yield p_hist, c_hist, ""
81
  p_hist[-1]["content"] += f"\n\n---\n*Telemetry: {format_telemetry(time.perf_counter()-start_time)} | Source: AUGMENTED CLOUD*"
82
+ yield p_hist, c_hist, ""
83
  except Exception as e:
84
  p_hist[-1]["content"] = f"Primary Error: {str(e)}"
85
+ yield p_hist, c_hist, ""
86
 
87
+ # ASYNC VANILLA STREAM (Corrected with 'await' for the stream object)
88
  comp_start = time.perf_counter()
89
  c_hist[-1]["content"] = "*Routing...*"
90
  yield p_hist, c_hist, ""
91
 
92
  try:
93
  res_text = ""
94
+ # FIX: We must await the chat_completion call to get the AsyncIterable
95
+ stream = await client.chat_completion(
96
+ messages=[{"role":"system","content":"Standard AI"}] + c_hist[:-1],
97
+ max_tokens=512,
98
+ stream=True,
99
+ temperature=0.7
100
+ )
101
+ async for chunk in stream:
102
  res_text += (chunk.choices[0].delta.content or "")
103
  c_hist[-1]["content"] = res_text
104
  yield p_hist, c_hist, ""
105
  c_hist[-1]["content"] += f"\n\n---\n*Telemetry: {format_telemetry(time.perf_counter()-comp_start)} | Source: VANILLA CLOUD*"
106
+ yield p_hist, c_hist, ""
107
  except Exception as e:
108
  c_hist[-1]["content"] = f"Competitor Error: {str(e)}"
109
  yield p_hist, c_hist, ""
 
116
  p_chat = gr.Chatbot(label="Augmented Logic Kernel (T3 Architecture)", height=350)
117
  with gr.Row():
118
  msg_in = gr.Textbox(label="Message", placeholder="Test P vs NP or Logistics Distribution...", scale=8)
119
+ submit_btn = gr.Button("Execute", scale=1, variant="primary")
120
+
121
  gr.Examples(examples=["Define P vs. NP. Then validate a 120-unit distribution across 3 nodes.", "Run grid diagnostic"], inputs=msg_in)
122
+
123
  c_chat = gr.Chatbot(label="Vanilla Qwen 2.5 (Standard Infrastructure)", height=350)
124
 
125
  msg_in.submit(generate_responses, [msg_in, p_chat, c_chat], [p_chat, c_chat, msg_in])
126
+ submit_btn.click(generate_responses, [msg_in, p_chat, c_chat], [p_chat, c_chat, msg_in])
127
 
128
  if __name__ == "__main__":
129
  demo.queue().launch(theme=gr.themes.Soft(primary_hue="orange"), css=custom_css)