Add files via upload
This commit is contained in:
1 parent
3956ddf808
commit
ef6fd7a5f6
6 files changed
+770
-167
No files matched your search
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
System Monitor — background metric checks with voice alert support.
|
||||
Works on Windows, macOS, and Linux without external APIs.
|
||||
"""
|
||||
import platform
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import psutil
|
||||
|
||||
_OS = platform.system() # "Windows" | "Darwin" | "Linux"
|
||||
|
||||
DEFAULT_THRESHOLDS = {
|
||||
"cpu": 90.0, # % — fires after _CPU_STREAK consecutive readings
|
||||
"ram": 90.0, # %
|
||||
"temp": 85.0, # °C
|
||||
"gpu": 95.0, # %
|
||||
}
|
||||
|
||||
_COOLDOWN = 300 # seconds between same-type alerts (5 min)
|
||||
_CPU_STREAK = 3 # consecutive high readings required before CPU alert
|
||||
|
||||
|
||||
def _get_gpu_usage() -> float:
|
||||
# NVIDIA
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["nvidia-smi", "--query-gpu=utilization.gpu", "--format=csv,noheader,nounits"],
|
||||
capture_output=True, text=True, timeout=2,
|
||||
)
|
||||
if r.returncode == 0:
|
||||
vals = [float(v.strip()) for v in r.stdout.strip().split("\n") if v.strip()]
|
||||
return sum(vals) / len(vals) if vals else -1.0
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# AMD (Linux)
|
||||
if _OS == "Linux":
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["rocm-smi", "--showuse", "--csv"],
|
||||
capture_output=True, text=True, timeout=2,
|
||||
)
|
||||
if r.returncode == 0:
|
||||
for line in r.stdout.strip().split("\n"):
|
||||
parts = line.split(",")
|
||||
if len(parts) >= 2:
|
||||
try:
|
||||
return float(parts[1].strip().replace("%", ""))
|
||||
except ValueError:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return -1.0
|
||||
|
||||
|
||||
def _get_cpu_temp() -> float:
|
||||
# psutil sensors (Linux + some Windows drivers)
|
||||
try:
|
||||
temps = psutil.sensors_temperatures()
|
||||
for name in ["coretemp", "k10temp", "cpu_thermal", "acpitz",
|
||||
"cpu-thermal", "zenpower", "it8688"]:
|
||||
if name in temps and temps[name]:
|
||||
return temps[name][0].current
|
||||
for entries in temps.values():
|
||||
if entries:
|
||||
return entries[0].current
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Windows — WMI thermal zone
|
||||
if _OS == "Windows":
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["powershell", "-Command",
|
||||
"(Get-WmiObject MSAcpi_ThermalZoneTemperature "
|
||||
"-Namespace root/wmi).CurrentTemperature"],
|
||||
capture_output=True, text=True, timeout=3,
|
||||
)
|
||||
if r.returncode == 0 and r.stdout.strip():
|
||||
raw = float(r.stdout.strip().split("\n")[0])
|
||||
return (raw / 10.0) - 273.15
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# macOS — osx-cpu-temp (optional CLI tool)
|
||||
if _OS == "Darwin":
|
||||
try:
|
||||
r = subprocess.run(
|
||||
["osx-cpu-temp"], capture_output=True, text=True, timeout=2,
|
||||
)
|
||||
if r.returncode == 0:
|
||||
import re
|
||||
m = re.search(r"([\d.]+)", r.stdout)
|
||||
if m:
|
||||
return float(m.group(1))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return -1.0
|
||||
|
||||
|
||||
def get_system_status() -> dict:
|
||||
"""
|
||||
Snapshot of current system metrics.
|
||||
Used by the system_status tool so the user can ask verbally.
|
||||
"""
|
||||
cpu = psutil.cpu_percent(interval=0.2)
|
||||
ram = psutil.virtual_memory()
|
||||
temp = _get_cpu_temp()
|
||||
gpu = _get_gpu_usage()
|
||||
|
||||
boot_time = psutil.boot_time()
|
||||
uptime_secs = time.time() - boot_time
|
||||
uptime_h = int(uptime_secs // 3600)
|
||||
uptime_m = int((uptime_secs % 3600) // 60)
|
||||
|
||||
return {
|
||||
"cpu_percent": round(cpu, 1),
|
||||
"ram_percent": round(ram.percent, 1),
|
||||
"ram_used_gb": round(ram.used / 1024 ** 3, 1),
|
||||
"ram_total_gb": round(ram.total / 1024 ** 3, 1),
|
||||
"cpu_temp_c": round(temp, 1) if temp > 0 else None,
|
||||
"gpu_percent": round(gpu, 1) if gpu >= 0 else None,
|
||||
"uptime": f"{uptime_h}h {uptime_m}m",
|
||||
"process_count": len(psutil.pids()),
|
||||
}
|
||||
|
||||
|
||||
class SystemMonitor:
|
||||
"""
|
||||
Stateful monitor — cooldown state persists across session reconnections.
|
||||
Call check() periodically; it returns a [SYSTEM_ALERT] string when a
|
||||
threshold is exceeded, or None when everything is fine.
|
||||
"""
|
||||
|
||||
def __init__(self, thresholds: dict | None = None):
|
||||
self.thresholds = {**DEFAULT_THRESHOLDS, **(thresholds or {})}
|
||||
self._last_alert: dict[str, float] = {}
|
||||
self._cpu_streak = 0
|
||||
|
||||
def _can_alert(self, key: str) -> bool:
|
||||
return (time.monotonic() - self._last_alert.get(key, 0)) > _COOLDOWN
|
||||
|
||||
def _record(self, key: str):
|
||||
self._last_alert[key] = time.monotonic()
|
||||
|
||||
def check(self) -> str | None:
|
||||
"""
|
||||
Reads current metrics synchronously.
|
||||
Returns an instruction string for Jarvis to speak, or None.
|
||||
"""
|
||||
try:
|
||||
cpu = psutil.cpu_percent(interval=None)
|
||||
ram = psutil.virtual_memory().percent
|
||||
temp = _get_cpu_temp()
|
||||
gpu = _get_gpu_usage()
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
alerts: list[str] = []
|
||||
|
||||
# CPU — require consecutive readings to avoid transient spikes
|
||||
if cpu >= self.thresholds["cpu"]:
|
||||
self._cpu_streak += 1
|
||||
if self._cpu_streak >= _CPU_STREAK and self._can_alert("cpu"):
|
||||
alerts.append(
|
||||
f"[SYSTEM_ALERT] CPU usage has been critically high ({cpu:.0f}%) "
|
||||
"for several seconds. Warn the user in their language and suggest "
|
||||
"closing heavy applications."
|
||||
)
|
||||
self._record("cpu")
|
||||
self._cpu_streak = 0
|
||||
else:
|
||||
self._cpu_streak = 0
|
||||
|
||||
if ram >= self.thresholds["ram"] and self._can_alert("ram"):
|
||||
alerts.append(
|
||||
f"[SYSTEM_ALERT] RAM is at {ram:.0f}% — nearly exhausted. "
|
||||
"Warn the user in their language and suggest freeing memory."
|
||||
)
|
||||
self._record("ram")
|
||||
|
||||
if temp > 0 and temp >= self.thresholds["temp"] and self._can_alert("temp"):
|
||||
alerts.append(
|
||||
f"[SYSTEM_ALERT] CPU temperature is {temp:.0f}°C — above the safe limit. "
|
||||
"Warn the user in their language and advise reducing system load "
|
||||
"or checking cooling."
|
||||
)
|
||||
self._record("temp")
|
||||
|
||||
if gpu >= 0 and gpu >= self.thresholds["gpu"] and self._can_alert("gpu"):
|
||||
alerts.append(
|
||||
f"[SYSTEM_ALERT] GPU load is at {gpu:.0f}%. "
|
||||
"Briefly inform the user in their language."
|
||||
)
|
||||
self._record("gpu")
|
||||
|
||||
return " ".join(alerts) if alerts else None
|
||||
+228
-141
@@ -1,141 +1,228 @@
|
||||
#web_search.py
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
def _get_base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
BASE_DIR = _get_base_dir()
|
||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _gemini_search(query: str) -> str:
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
response = client.models.generate_content(
|
||||
model="gemini-2.5-flash",
|
||||
contents=query,
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
)
|
||||
|
||||
text = ""
|
||||
for part in response.candidates[0].content.parts:
|
||||
if hasattr(part, "text") and part.text:
|
||||
text += part.text
|
||||
|
||||
text = text.strip()
|
||||
if not text:
|
||||
raise ValueError("Gemini returned an empty response.")
|
||||
return text
|
||||
|
||||
|
||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
except ImportError:
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
results = []
|
||||
with DDGS() as ddgs:
|
||||
for r in ddgs.text(query, max_results=max_results):
|
||||
results.append({
|
||||
"title": r.get("title", ""),
|
||||
"snippet": r.get("body", ""),
|
||||
"url": r.get("href", ""),
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
def _format_ddg(query: str, results: list[dict]) -> str:
|
||||
if not results:
|
||||
return f"No results found for: {query}"
|
||||
|
||||
lines = [f"Search results for: {query}\n"]
|
||||
for i, r in enumerate(results, 1):
|
||||
if r.get("title"): lines.append(f"{i}. {r['title']}")
|
||||
if r.get("snippet"): lines.append(f" {r['snippet']}")
|
||||
if r.get("url"): lines.append(f" {r['url']}")
|
||||
lines.append("")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
def _compare(items: list[str], aspect: str) -> str:
|
||||
query = (
|
||||
f"Compare {', '.join(items)} in terms of {aspect}. "
|
||||
"Give specific facts and data."
|
||||
)
|
||||
try:
|
||||
return _gemini_search(query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini compare failed: {e} — falling back to DDG")
|
||||
|
||||
# DDG fallback: fetch results per item and merge
|
||||
all_results: dict[str, list] = {}
|
||||
for item in items:
|
||||
try:
|
||||
all_results[item] = _ddg_search(f"{item} {aspect}", max_results=3)
|
||||
except Exception:
|
||||
all_results[item] = []
|
||||
|
||||
lines = [f"Comparison — {aspect.upper()}", "─" * 40]
|
||||
for item in items:
|
||||
lines.append(f"\n▸ {item}")
|
||||
for r in all_results.get(item, [])[:2]:
|
||||
if r.get("snippet"):
|
||||
lines.append(f" • {r['snippet']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
def web_search(
|
||||
parameters: dict,
|
||||
response=None,
|
||||
player=None,
|
||||
session_memory=None,
|
||||
) -> str:
|
||||
params = parameters or {}
|
||||
query = params.get("query", "").strip()
|
||||
mode = params.get("mode", "search").lower().strip()
|
||||
items = params.get("items", [])
|
||||
aspect = params.get("aspect", "general").strip() or "general"
|
||||
|
||||
if not query and not items:
|
||||
return "Please provide a search query, sir."
|
||||
|
||||
if items and mode != "compare":
|
||||
mode = "compare"
|
||||
|
||||
if player:
|
||||
player.write_log(f"[Search] {query or ', '.join(items)}")
|
||||
|
||||
print(f"[WebSearch] 🔍 Query: {query!r} Mode: {mode}")
|
||||
|
||||
try:
|
||||
if mode == "compare" and items:
|
||||
print(f"[WebSearch] 📊 Comparing: {items}")
|
||||
result = _compare(items, aspect)
|
||||
print("[WebSearch] ✅ Compare done.")
|
||||
return result
|
||||
|
||||
print("[WebSearch] 🌐 Trying Gemini...")
|
||||
try:
|
||||
result = _gemini_search(query)
|
||||
print("[WebSearch] ✅ Gemini OK.")
|
||||
return result
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini failed ({e}) — trying DDG...")
|
||||
results = _ddg_search(query)
|
||||
result = _format_ddg(query, results)
|
||||
print(f"[WebSearch] ✅ DDG: {len(results)} result(s).")
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ❌ All backends failed: {e}")
|
||||
return f"Search failed, sir: {e}"
|
||||
#web_search.py
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
def _get_base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
BASE_DIR = _get_base_dir()
|
||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _gemini_search(query: str) -> str:
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
response = client.models.generate_content(
|
||||
model="gemini-2.5-flash",
|
||||
contents=query,
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
)
|
||||
|
||||
text = ""
|
||||
for part in response.candidates[0].content.parts:
|
||||
if hasattr(part, "text") and part.text:
|
||||
text += part.text
|
||||
|
||||
text = text.strip()
|
||||
if not text:
|
||||
raise ValueError("Gemini returned an empty response.")
|
||||
return text
|
||||
|
||||
|
||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
except ImportError:
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
results = []
|
||||
with DDGS() as ddgs:
|
||||
for r in ddgs.text(query, max_results=max_results):
|
||||
results.append({
|
||||
"title": r.get("title", ""),
|
||||
"snippet": r.get("body", ""),
|
||||
"url": r.get("href", ""),
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
def _format_ddg(query: str, results: list[dict]) -> str:
|
||||
if not results:
|
||||
return f"No results found for: {query}"
|
||||
|
||||
lines = [f"Search results for: {query}\n"]
|
||||
for i, r in enumerate(results, 1):
|
||||
if r.get("title"): lines.append(f"{i}. {r['title']}")
|
||||
if r.get("snippet"): lines.append(f" {r['snippet']}")
|
||||
if r.get("url"): lines.append(f" Source: {r['url']}")
|
||||
lines.append("")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
# ── Briefing helper ────────────────────────────────────────────────────────────
|
||||
|
||||
def _gemini_headlines(n: int = 5) -> tuple[list[str], str]:
|
||||
"""
|
||||
Fetches current headlines via Gemini grounded search.
|
||||
Optimised for speed: minimal prompt + strict token cap.
|
||||
Returns (headline_list, raw_text_for_display).
|
||||
"""
|
||||
import re
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
response = client.models.generate_content(
|
||||
model="gemini-2.5-flash",
|
||||
contents=f"Current world news: {n} headlines. Numbered list, titles only.",
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
)
|
||||
|
||||
raw = ""
|
||||
for part in response.candidates[0].content.parts:
|
||||
if hasattr(part, "text") and part.text:
|
||||
raw += part.text
|
||||
|
||||
headlines = []
|
||||
for line in raw.strip().split("\n"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
# Only accept lines that begin with a number — skips preamble/closing sentences
|
||||
if not re.match(r'^[\d]+[.\)\-]', line):
|
||||
continue
|
||||
clean = re.sub(r'^[\d]+[.\)\-]\s*', '', line)
|
||||
clean = re.sub(r'^\*+\s*', '', clean).strip()
|
||||
if clean and len(clean) > 10:
|
||||
headlines.append(clean)
|
||||
|
||||
return headlines[:n], raw.strip()
|
||||
|
||||
|
||||
# ── Modes ──────────────────────────────────────────────────────────────────────
|
||||
|
||||
def _search(query: str) -> str:
|
||||
"""Default search — Gemini grounded, DDG fallback."""
|
||||
try:
|
||||
return _gemini_search(query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini failed ({e}) — trying DDG...")
|
||||
results = _ddg_search(query)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
|
||||
def _news(query: str) -> str:
|
||||
"""Latest news — forces recency in the query."""
|
||||
news_query = f"latest news today: {query}" if query else "top world news today"
|
||||
try:
|
||||
return _gemini_search(news_query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ News Gemini failed ({e}) — DDG fallback...")
|
||||
results = _ddg_search(news_query, max_results=8)
|
||||
return _format_ddg(news_query, results)
|
||||
|
||||
|
||||
def _research(query: str) -> str:
|
||||
"""
|
||||
Deep dive — asks Gemini for a comprehensive answer with context.
|
||||
Falls back to a wider DDG fetch.
|
||||
"""
|
||||
research_query = (
|
||||
f"Comprehensive, detailed explanation of: {query}. "
|
||||
"Include background context, key facts, current state, and important nuances."
|
||||
)
|
||||
try:
|
||||
return _gemini_search(research_query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Research Gemini failed ({e}) — DDG fallback...")
|
||||
results = _ddg_search(query, max_results=10)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
|
||||
def _price(query: str) -> str:
|
||||
"""Product price lookup — searches for current market prices."""
|
||||
price_query = f"current price of {query} — how much does it cost today"
|
||||
try:
|
||||
return _gemini_search(price_query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Price Gemini failed ({e}) — DDG fallback...")
|
||||
results = _ddg_search(f"{query} price buy", max_results=6)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
|
||||
def _compare(items: list[str], aspect: str) -> str:
|
||||
query = (
|
||||
f"Compare {', '.join(items)} in terms of {aspect}. "
|
||||
"Give specific facts and data."
|
||||
)
|
||||
try:
|
||||
return _gemini_search(query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini compare failed: {e} — falling back to DDG")
|
||||
|
||||
all_results: dict[str, list] = {}
|
||||
for item in items:
|
||||
try:
|
||||
all_results[item] = _ddg_search(f"{item} {aspect}", max_results=3)
|
||||
except Exception:
|
||||
all_results[item] = []
|
||||
|
||||
lines = [f"Comparison — {aspect.upper()}", "─" * 40]
|
||||
for item in items:
|
||||
lines.append(f"\n▸ {item}")
|
||||
for r in all_results.get(item, [])[:2]:
|
||||
if r.get("snippet"):
|
||||
lines.append(f" • {r['snippet']}")
|
||||
if r.get("url"):
|
||||
lines.append(f" {r['url']}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
# ── Public entry point ─────────────────────────────────────────────────────────
|
||||
|
||||
def web_search(
|
||||
parameters: dict,
|
||||
response=None,
|
||||
player=None,
|
||||
session_memory=None,
|
||||
) -> str:
|
||||
params = parameters or {}
|
||||
query = params.get("query", "").strip()
|
||||
mode = params.get("mode", "search").lower().strip()
|
||||
items = params.get("items", [])
|
||||
aspect = params.get("aspect", "general").strip() or "general"
|
||||
|
||||
if not query and not items:
|
||||
return "Please provide a search query."
|
||||
|
||||
if items and mode not in ("compare",):
|
||||
mode = "compare"
|
||||
|
||||
if player:
|
||||
player.write_log(f"[Search:{mode}] {query or ', '.join(items)}")
|
||||
|
||||
print(f"[WebSearch] 🔍 mode={mode!r} query={query!r}")
|
||||
|
||||
try:
|
||||
if mode == "compare" and items:
|
||||
return _compare(items, aspect)
|
||||
if mode == "news":
|
||||
return _news(query)
|
||||
if mode == "research":
|
||||
return _research(query)
|
||||
if mode == "price":
|
||||
return _price(query)
|
||||
return _search(query)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ❌ All backends failed: {e}")
|
||||
return f"Search failed: {e}"
|
||||
Reference in new issue
Block a user