Spaces:
Running on Zero
Running on Zero
File size: 10,403 Bytes
d58c800 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 | """
Utility functions for Nova AI - ChatGPT Astra Edition.
Hardware inspection, Astra prompt enhancement, latency profiling, and chat exporters (MD, JSON, HTML).
"""
import os
import sys
import time
import json
import html
import psutil
from pathlib import Path
from typing import List, Dict, Any, Tuple
# Ensure UTF-8 output on Windows consoles
if sys.platform == "win32":
try:
if sys.stdout and hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8")
if sys.stderr and hasattr(sys.stderr, "reconfigure"):
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
from rich.console import Console
console = Console(legacy_windows=False)
def get_system_hardware_info() -> Dict[str, Any]:
"""Inspect and return current CPU, RAM, NVIDIA GPU, and Hugging Face ZeroGPU capabilities."""
info: Dict[str, Any] = {
"cpu_count_physical": psutil.cpu_count(logical=False) or 1,
"cpu_count_logical": psutil.cpu_count(logical=True) or 1,
"total_ram_gb": round(psutil.virtual_memory().total / (1024 ** 3), 2),
"available_ram_gb": round(psutil.virtual_memory().available / (1024 ** 3), 2),
"has_cuda": False,
"is_zero_gpu": False,
"device_name": "CPU (Intel / AMD Multi-Core)",
"recommended_device": "cpu",
"cuda_device_count": 0,
"cuda_vram_gb": 0.0,
"cuda_version": None,
"compute_capability": None,
"hardware_badge": "⚡ Multi-Core CPU Accelerated"
}
# Check for Hugging Face Spaces ZeroGPU environment
if os.getenv("SPACES_ZERO_GPU") == "true" or "spaces" in sys.modules:
info["is_zero_gpu"] = True
info["hardware_badge"] = "🟢 NVIDIA A100 ZeroGPU Dynamic Allocation Active"
try:
import torch
if torch.cuda.is_available():
info["has_cuda"] = True
info["cuda_device_count"] = torch.cuda.device_count()
dev_name = torch.cuda.get_device_name(0)
info["device_name"] = dev_name
info["recommended_device"] = "cuda"
vram = round(torch.cuda.get_device_properties(0).total_memory / (1024 ** 3), 2)
info["cuda_vram_gb"] = vram
info["cuda_version"] = torch.version.cuda
cap = torch.cuda.get_device_capability(0)
info["compute_capability"] = f"{cap[0]}.{cap[1]}"
if info["is_zero_gpu"]:
info["hardware_badge"] = f"🟢 NVIDIA ZeroGPU ({dev_name}) Active"
else:
info["hardware_badge"] = f"🟢 NVIDIA CUDA ({dev_name} • {vram}GB VRAM • CC {cap[0]}.{cap[1]})"
elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available():
info["device_name"] = "Apple Silicon MPS Metal"
info["recommended_device"] = "mps"
info["hardware_badge"] = "🍎 Apple Silicon Metal MPS Accelerated"
except ImportError:
pass
return info
def enhance_prompt_with_astra(prompt: str) -> str:
"""
Astra Spark Prompt Enhancer:
Transforms a concise prompt into a structured, high-yield ChatGPT Astra prompt.
"""
cleaned = prompt.strip()
if not cleaned:
return prompt
# If it's already a very detailed prompt, don't over-wrap it
if len(cleaned) > 250 and ("###" in cleaned or "Requirements:" in cleaned):
return cleaned
# Generate an elevated Astra prompt template
enhanced = (
f"{cleaned}\n\n"
f"--- Astra Guidance ---\n"
f"Please provide an in-depth, structured response covering:\n"
f"1. Core concept and fundamental explanation.\n"
f"2. Practical real-world examples or code implementation with best practices.\n"
f"3. Key trade-offs, common pitfalls, and edge cases to consider.\n"
f"4. Summary checklist or actionable next steps."
)
return enhanced
def format_chat_as_markdown(history: List[Dict[str, str]], title: str = "Nova AI - Conversation Record") -> str:
"""Format conversation list into structured Markdown text."""
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
md = [
f"# 🌟 {title}\n",
f"*Generated by Nova AI (ChatGPT Astra Edition) on: {timestamp}*\n\n",
"---\n\n"
]
for msg in history:
role = msg.get("role", "user").lower()
content = msg.get("content", "").strip()
if role == "system":
md.append(f"> 🧠 **Astra System Persona:**\n> {content}\n\n")
elif role == "user":
md.append(f"### 👤 User:\n{content}\n\n")
else:
md.append(f"### 🌟 Nova Astra:\n{content}\n\n")
return "".join(md)
def format_chat_as_json(history: List[Dict[str, str]]) -> str:
"""Format conversation history into rich JSON string."""
return json.dumps({
"generator": "Nova AI - ChatGPT Astra Edition",
"version": "2.5.0-Astra",
"timestamp": time.time(),
"date": time.strftime("%Y-%m-%d %H:%M:%S"),
"total_messages": len(history),
"messages": history
}, indent=2, ensure_ascii=False)
def format_chat_as_html(history: List[Dict[str, str]], title: str = "Nova AI Conversation") -> str:
"""Format conversation into an exportable standalone cosmic dark-mode HTML document."""
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
messages_html = []
for msg in history:
role = msg.get("role", "user").lower()
content = html.escape(msg.get("content", "").strip()).replace("\n", "<br/>")
if role == "system":
card = f"""
<div class="msg-box system">
<div class="msg-header">🧠 Astra Persona Directive</div>
<div class="msg-body">{content}</div>
</div>
"""
elif role == "user":
card = f"""
<div class="msg-box user">
<div class="msg-header">👤 User</div>
<div class="msg-body">{content}</div>
</div>
"""
else:
card = f"""
<div class="msg-box astra">
<div class="msg-header">🌟 Nova Astra</div>
<div class="msg-body">{content}</div>
</div>
"""
messages_html.append(card)
html_content = f"""<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{html.escape(title)} - Nova AI</title>
<style>
:root {{
--bg-color: #0b0f19;
--card-bg: #111827;
--text-main: #f3f4f6;
--text-dim: #9ca3af;
--accent-purple: #8b5cf6;
--accent-cyan: #06b6d4;
--border-color: #1f2937;
}}
body {{
background-color: var(--bg-color);
color: var(--text-main);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
line-height: 1.6;
margin: 0;
padding: 30px 15px;
}}
.container {{
max-width: 900px;
margin: 0 auto;
}}
.header {{
background: linear-gradient(135deg, #1e1b4b 0%, #312e81 50%, #4338ca 100%);
padding: 24px 30px;
border-radius: 16px;
margin-bottom: 24px;
box-shadow: 0 10px 25px -5px rgba(49, 46, 129, 0.4);
}}
.header h1 {{
margin: 0 0 6px 0;
font-size: 26px;
color: #fff;
}}
.header p {{
margin: 0;
color: #c7d2fe;
font-size: 14px;
}}
.msg-box {{
margin-bottom: 16px;
padding: 16px 20px;
border-radius: 14px;
background: var(--card-bg);
border: 1px solid var(--border-color);
}}
.msg-box.user {{
border-left: 4px solid var(--accent-cyan);
}}
.msg-box.astra {{
border-left: 4px solid var(--accent-purple);
background: #141c2e;
}}
.msg-box.system {{
border-left: 4px solid #f59e0b;
font-size: 13px;
color: var(--text-dim);
}}
.msg-header {{
font-weight: 700;
font-size: 13px;
text-transform: uppercase;
letter-spacing: 0.05em;
margin-bottom: 8px;
color: #e0e7ff;
}}
.msg-body {{
white-space: pre-wrap;
word-break: break-word;
}}
.footer {{
text-align: center;
color: var(--text-dim);
font-size: 13px;
margin-top: 30px;
}}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🌟 Nova AI (ChatGPT Astra Edition)</h1>
<p>Exported Transcript • {timestamp}</p>
</div>
{''.join(messages_html)}
<div class="footer">Generated by Nova AI • Next-Gen Conversational Intelligence</div>
</div>
</body>
</html>"""
return html_content
class LatencyTracker:
"""High-resolution latency, time-to-first-token, and throughput tracker."""
def __init__(self):
self.start_time: float = 0.0
self.first_token_time: float = 0.0
self.end_time: float = 0.0
self.token_count: int = 0
def start(self):
self.start_time = time.perf_counter()
self.first_token_time = 0.0
self.end_time = 0.0
self.token_count = 0
def record_token(self, count: int = 1):
self.token_count += count
if self.first_token_time == 0.0:
self.first_token_time = time.perf_counter()
def stop(self) -> Dict[str, float]:
self.end_time = time.perf_counter()
total_time = max(self.end_time - self.start_time, 0.0001)
ttft = max(self.first_token_time - self.start_time, 0.0) if self.first_token_time > 0 else 0.0
tps = self.token_count / total_time if self.token_count > 0 else 0.0
return {
"total_latency_seconds": round(total_time, 3),
"time_to_first_token_ms": round(ttft * 1000, 1),
"tokens_generated": self.token_count,
"tokens_per_second": round(tps, 1)
}
|