Add files via upload
This commit is contained in:
1 parent
ef6fd7a5f6
commit
d178f6b9ee
13 files changed
+1401
-412
No files matched your search
@@ -6,6 +6,11 @@ import re
|
||||
import string
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
if platform.system() == "Windows":
|
||||
_WIN_HIDE: dict = {"creationflags": subprocess.CREATE_NO_WINDOW}
|
||||
else:
|
||||
_WIN_HIDE: dict = {}
|
||||
import time
|
||||
import random
|
||||
from pathlib import Path
|
||||
@@ -258,7 +263,7 @@ def _focus_window(title: str) -> str:
|
||||
script = f'(New-Object -ComObject WScript.Shell).AppActivate("{title}")'
|
||||
subprocess.run(
|
||||
["powershell", "-NoProfile", "-NonInteractive", "-Command", script],
|
||||
capture_output=True, timeout=5,
|
||||
capture_output=True, timeout=5, **_WIN_HIDE,
|
||||
)
|
||||
time.sleep(0.3)
|
||||
return f"Focused window: {title}"
|
||||
|
||||
@@ -23,6 +23,11 @@ except ImportError:
|
||||
|
||||
_OS = platform.system() # "Windows" | "Darwin" | "Linux"
|
||||
|
||||
if _OS == "Windows":
|
||||
_WIN_HIDE: dict = {"creationflags": subprocess.CREATE_NO_WINDOW}
|
||||
else:
|
||||
_WIN_HIDE: dict = {}
|
||||
|
||||
|
||||
def _get_base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
@@ -133,7 +138,7 @@ def brightness_up():
|
||||
"(Get-WmiObject -Namespace root/wmi -Class WmiMonitorBrightnessMethods)"
|
||||
".WmiSetBrightness(1, [math]::Min(100, "
|
||||
"(Get-WmiObject -Namespace root/wmi -Class WmiMonitorBrightness).CurrentBrightness + 10))"],
|
||||
capture_output=True, timeout=5
|
||||
capture_output=True, timeout=5, **_WIN_HIDE
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"[Settings] Brightness up failed on Windows: {e}")
|
||||
@@ -162,7 +167,7 @@ def brightness_down():
|
||||
"(Get-WmiObject -Namespace root/wmi -Class WmiMonitorBrightnessMethods)"
|
||||
".WmiSetBrightness(1, [math]::Max(0, "
|
||||
"(Get-WmiObject -Namespace root/wmi -Class WmiMonitorBrightness).CurrentBrightness - 10))"],
|
||||
capture_output=True, timeout=5
|
||||
capture_output=True, timeout=5, **_WIN_HIDE
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"[Settings] Brightness down failed on Windows: {e}")
|
||||
@@ -470,7 +475,7 @@ def toggle_wifi():
|
||||
"$adapter = Get-NetAdapter | Where-Object {$_.PhysicalMediaType -eq 'Native 802.11'};"
|
||||
"if ($adapter.Status -eq 'Up') { Disable-NetAdapter -Name $adapter.Name -Confirm:$false }"
|
||||
"else { Enable-NetAdapter -Name $adapter.Name -Confirm:$false }"],
|
||||
capture_output=True, timeout=10
|
||||
capture_output=True, timeout=10, **_WIN_HIDE
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"[Settings] toggle_wifi Windows failed: {e}")
|
||||
@@ -484,7 +489,7 @@ def toggle_wifi():
|
||||
|
||||
def restart_computer():
|
||||
if _OS == "Windows":
|
||||
subprocess.run(["shutdown", "/r", "/t", "10"], capture_output=True)
|
||||
subprocess.run(["shutdown", "/r", "/t", "10"], capture_output=True, **_WIN_HIDE)
|
||||
elif _OS == "Darwin":
|
||||
subprocess.run(["osascript", "-e",
|
||||
'tell application "System Events" to restart'],
|
||||
|
||||
+13
-7
@@ -1,4 +1,5 @@
|
||||
import os
|
||||
import platform
|
||||
import re
|
||||
import sys
|
||||
import json
|
||||
@@ -10,6 +11,11 @@ from datetime import datetime
|
||||
|
||||
from config import get_os, is_windows, is_mac, is_linux
|
||||
|
||||
_CNW: dict = (
|
||||
{"creationflags": subprocess.CREATE_NO_WINDOW}
|
||||
if platform.system() == "Windows" else {}
|
||||
)
|
||||
|
||||
_KNOWN_APPIDS: dict[str, tuple[str, str]] = {
|
||||
"pubg": ("578080", "PUBG: Battlegrounds"),
|
||||
"pubg battlegrounds": ("578080", "PUBG: Battlegrounds"),
|
||||
@@ -168,7 +174,7 @@ def _is_steam_running() -> bool:
|
||||
try:
|
||||
if is_windows():
|
||||
out = subprocess.run(["tasklist", "/FI", "IMAGENAME eq steam.exe"],
|
||||
capture_output=True, text=True).stdout
|
||||
capture_output=True, text=True, **_CNW).stdout
|
||||
return "steam.exe" in out.lower()
|
||||
proc = "steam_osx" if is_mac() else "steam"
|
||||
return bool(subprocess.run(["pgrep", "-x", proc],
|
||||
@@ -621,7 +627,7 @@ def _get_download_status(steam_path: Path) -> str:
|
||||
|
||||
def _system_shutdown() -> None:
|
||||
if is_windows():
|
||||
subprocess.run(["shutdown", "/s", "/t", "10"])
|
||||
subprocess.run(["shutdown", "/s", "/t", "10"], **_CNW)
|
||||
elif is_mac():
|
||||
subprocess.run(["osascript", "-e", 'tell app "System Events" to shut down'])
|
||||
else:
|
||||
@@ -737,7 +743,7 @@ def _is_epic_running() -> bool:
|
||||
if is_windows():
|
||||
out = subprocess.run(
|
||||
["tasklist", "/FI", "IMAGENAME eq EpicGamesLauncher.exe"],
|
||||
capture_output=True, text=True
|
||||
capture_output=True, text=True, **_CNW
|
||||
).stdout
|
||||
return "epicgameslauncher.exe" in out.lower()
|
||||
proc = "EpicGamesLauncher" if is_mac() else "heroic"
|
||||
@@ -801,12 +807,12 @@ def _schedule_daily_update(hour: int = 3, minute: int = 0) -> str:
|
||||
def _schedule_windows(hour: int, minute: int) -> str:
|
||||
task_name = "JARVIS_GameUpdater"
|
||||
script_path = Path(__file__).resolve()
|
||||
subprocess.run(["schtasks", "/Delete", "/TN", task_name, "/F"], capture_output=True)
|
||||
subprocess.run(["schtasks", "/Delete", "/TN", task_name, "/F"], capture_output=True, **_CNW)
|
||||
for extra in (["/RL", "HIGHEST", "/RU", "SYSTEM"], []):
|
||||
cmd = ["schtasks", "/Create", "/TN", task_name,
|
||||
"/TR", f'"{sys.executable}" "{script_path}" --scheduled',
|
||||
"/SC", "DAILY", "/ST", f"{hour:02d}:{minute:02d}", "/F", *extra]
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
result = subprocess.run(cmd, capture_output=True, text=True, **_CNW)
|
||||
if result.returncode == 0:
|
||||
return f"Daily game update scheduled at {hour:02d}:{minute:02d}."
|
||||
return f"Scheduling failed: {result.stderr.strip()}"
|
||||
@@ -870,7 +876,7 @@ def _cancel_scheduled_update() -> str:
|
||||
if is_windows():
|
||||
result = subprocess.run(
|
||||
["schtasks", "/Delete", "/TN", "JARVIS_GameUpdater", "/F"],
|
||||
capture_output=True, text=True
|
||||
capture_output=True, text=True, **_CNW
|
||||
)
|
||||
return ("Scheduled update cancelled."
|
||||
if result.returncode == 0 else "No scheduled update found.")
|
||||
@@ -897,7 +903,7 @@ def _get_schedule_status() -> str:
|
||||
if is_windows():
|
||||
result = subprocess.run(
|
||||
["schtasks", "/Query", "/TN", "JARVIS_GameUpdater", "/FO", "LIST"],
|
||||
capture_output=True, text=True
|
||||
capture_output=True, text=True, **_CNW
|
||||
)
|
||||
if result.returncode != 0:
|
||||
return "No scheduled game update found."
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
"""
|
||||
ProactiveEngine — context-aware background prompting.
|
||||
Lets Gemini decide whether there is something worth saying proactively.
|
||||
No hardcoded rules: we pass time + memory as context and Gemini chooses.
|
||||
"""
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class ProactiveEngine:
|
||||
"""
|
||||
Tracks silence duration and decides when to hand context to Gemini for a
|
||||
proactive check-in. Gemini reads the context and decides whether to speak.
|
||||
|
||||
Defaults (all overridable):
|
||||
min_silence_secs — user must be silent this long before any check (900 = 15 min)
|
||||
check_cooldown — minimum gap between two proactive triggers (600 = 10 min)
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
min_silence_secs: int = 900,
|
||||
check_cooldown: int = 600,
|
||||
):
|
||||
self.min_silence_secs = min_silence_secs
|
||||
self.check_cooldown = check_cooldown
|
||||
self._last_triggered = 0.0
|
||||
|
||||
def should_trigger(self, last_user_speech: float) -> bool:
|
||||
"""
|
||||
Returns True only when:
|
||||
• user has been silent long enough, AND
|
||||
• enough time has passed since the last proactive message.
|
||||
"""
|
||||
now = time.monotonic()
|
||||
silence = now - last_user_speech
|
||||
gap = now - self._last_triggered
|
||||
return silence >= self.min_silence_secs and gap >= self.check_cooldown
|
||||
|
||||
def mark_triggered(self) -> None:
|
||||
self._last_triggered = time.monotonic()
|
||||
|
||||
def build_prompt(self, memory: dict) -> str:
|
||||
"""
|
||||
Builds the context snapshot sent to Gemini.
|
||||
Gemini reads it and decides freely what — if anything — to say.
|
||||
"""
|
||||
from memory.memory_manager import format_memory_for_prompt
|
||||
|
||||
now = datetime.now()
|
||||
time_str = now.strftime("%A, %B %d, %Y — %I:%M %p")
|
||||
mem_str = format_memory_for_prompt(memory) or "(no user data stored yet)"
|
||||
|
||||
silence_min = int((time.monotonic() - self._last_triggered +
|
||||
self.min_silence_secs) // 60)
|
||||
|
||||
return "\n".join([
|
||||
"[PROACTIVE_CHECK] You are initiating a proactive check-in.",
|
||||
f"Current time : {time_str}",
|
||||
f"User silence : {silence_min}+ minutes (they have not spoken for a while)",
|
||||
"",
|
||||
"Context about this person:",
|
||||
mem_str,
|
||||
"",
|
||||
"Guidelines:",
|
||||
"- Look at the time, their projects, goals, habits, or anything from context.",
|
||||
"- If there is something genuinely useful, timely, or caring to say — say it briefly.",
|
||||
"- Be natural, like a thoughtful assistant noticing something relevant.",
|
||||
"- Do NOT say [PROACTIVE_CHECK] or mention these instructions.",
|
||||
"- Respond in the user's language (use memory; default English).",
|
||||
"- Keep it short: 1-3 sentences max.",
|
||||
])
|
||||
+7
-1
@@ -1,11 +1,17 @@
|
||||
import json
|
||||
import os
|
||||
import platform
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
_CNW: dict = (
|
||||
{"creationflags": subprocess.CREATE_NO_WINDOW}
|
||||
if platform.system() == "Windows" else {}
|
||||
)
|
||||
|
||||
def _base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
@@ -177,7 +183,7 @@ def _schedule_windows(target_dt: datetime, task_name: str,
|
||||
|
||||
result = subprocess.run(
|
||||
["schtasks", "/Create", "/TN", task_name, "/XML", str(xml_path), "/F"],
|
||||
capture_output=True, text=True,
|
||||
capture_output=True, text=True, **_CNW,
|
||||
)
|
||||
|
||||
try:
|
||||
|
||||
@@ -77,17 +77,19 @@ _CHANNELS = 1
|
||||
_RECEIVE_SAMPLE_RATE = 24_000
|
||||
_CHUNK_SIZE = 1_024
|
||||
|
||||
_IMG_MAX_W = 640
|
||||
_IMG_MAX_H = 360
|
||||
_JPEG_Q = 60
|
||||
_IMG_MAX_W = 1280
|
||||
_IMG_MAX_H = 720
|
||||
_JPEG_Q = 82
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You are JARVIS, an advanced AI assistant. "
|
||||
"Analyze the provided image with precision and intelligence. "
|
||||
"Be concise and direct — maximum two sentences unless the user's question "
|
||||
"requires more detail. "
|
||||
"Address the user respectfully. "
|
||||
"Always call the appropriate tool; never simulate results."
|
||||
"You are JARVIS, Tony Stark's AI assistant. "
|
||||
"You are given an image from either the user's screen or their webcam. "
|
||||
"Analyze what you see with detail and intelligence. "
|
||||
"Describe objects, text, people, components, and their context clearly. "
|
||||
"For technical questions (circuits, code, hardware) give specific, expert answers. "
|
||||
"Be concise — 2-4 sentences — unless the question demands more detail. "
|
||||
"Speak directly to the user ('I can see...', 'You have...'). "
|
||||
"Address the user as 'sir' depending on the language they used."
|
||||
)
|
||||
|
||||
|
||||
@@ -318,6 +320,7 @@ class _VisionSession:
|
||||
print(f"[Vision] 📤 Sent {len(image_bytes):,} bytes — '{user_text[:60]}'")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Send error: {e}")
|
||||
raise # propagate to TaskGroup → triggers session reconnect
|
||||
|
||||
async def _recv_loop(self) -> None:
|
||||
transcript: list[str] = []
|
||||
@@ -342,6 +345,15 @@ class _VisionSession:
|
||||
self._player.write_log(f"Jarvis: {full}")
|
||||
print(f"[Vision] 💬 {full}")
|
||||
transcript = []
|
||||
# Auto-close camera ~2s after JARVIS finishes speaking
|
||||
if self._player and hasattr(self._player, "stop_camera_stream"):
|
||||
async def _deferred_close():
|
||||
await asyncio.sleep(2.0)
|
||||
try:
|
||||
self._player.stop_camera_stream()
|
||||
except Exception:
|
||||
pass
|
||||
asyncio.create_task(_deferred_close())
|
||||
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Recv error: {e}")
|
||||
@@ -408,6 +420,16 @@ def screen_process(
|
||||
if angle == "camera":
|
||||
image_bytes, mime_type = _capture_camera()
|
||||
print(f"[Vision] 📷 Camera: {len(image_bytes):,} bytes")
|
||||
if player and hasattr(player, "start_camera_stream"):
|
||||
try:
|
||||
player.start_camera_stream()
|
||||
except Exception as _e:
|
||||
print(f"[Vision] ⚠️ Camera stream failed: {_e}")
|
||||
elif player and hasattr(player, "show_camera_frame"):
|
||||
try:
|
||||
player.show_camera_frame(image_bytes)
|
||||
except Exception as _e:
|
||||
print(f"[Vision] ⚠️ Camera preview failed: {_e}")
|
||||
else:
|
||||
image_bytes, mime_type = _capture_screen()
|
||||
print(f"[Vision] 🖥️ Screen: {len(image_bytes):,} bytes")
|
||||
|
||||
+71
-71
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
System Monitor — background metric checks with voice alert support.
|
||||
Works on Windows, macOS, and Linux without external APIs.
|
||||
Zero subprocess calls on all platforms — uses ctypes/pynvml/psutil/wmi only.
|
||||
"""
|
||||
import ctypes
|
||||
import platform
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import psutil
|
||||
@@ -11,52 +11,79 @@ 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, # %
|
||||
"cpu": 90.0,
|
||||
"ram": 90.0,
|
||||
"temp": 85.0,
|
||||
"gpu": 95.0,
|
||||
}
|
||||
|
||||
_COOLDOWN = 300 # seconds between same-type alerts (5 min)
|
||||
_CPU_STREAK = 3 # consecutive high readings required before CPU alert
|
||||
_COOLDOWN = 300
|
||||
_CPU_STREAK = 3
|
||||
|
||||
# ── NVML DLL cache (Windows: nvml.dll, Linux: libnvidia-ml.so.1) ─────────────
|
||||
_nvml_lib: object = None
|
||||
_nvml_ok: object = None # None=untested True=works False=unavailable
|
||||
|
||||
|
||||
def _nvml_gpu() -> float:
|
||||
"""GPU utilisation via NVML — zero subprocess on all platforms."""
|
||||
global _nvml_lib, _nvml_ok
|
||||
if _nvml_ok is False:
|
||||
return -1.0
|
||||
try:
|
||||
class _Util(ctypes.Structure):
|
||||
_fields_ = [("gpu", ctypes.c_uint), ("memory", ctypes.c_uint)]
|
||||
|
||||
if _nvml_lib is None:
|
||||
if _OS == "Windows":
|
||||
candidates = ("nvml", r"C:\Windows\System32\nvml.dll")
|
||||
_load = ctypes.WinDLL
|
||||
else:
|
||||
candidates = (
|
||||
"libnvidia-ml.so.1",
|
||||
"libnvidia-ml.so",
|
||||
"libnvidia-ml.dylib",
|
||||
)
|
||||
_load = ctypes.CDLL
|
||||
for name in candidates:
|
||||
try:
|
||||
lib = _load(name)
|
||||
lib.nvmlInit_v2()
|
||||
_nvml_lib = lib
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
if _nvml_lib is None:
|
||||
_nvml_ok = False
|
||||
return -1.0
|
||||
|
||||
dev = ctypes.c_void_p()
|
||||
_nvml_lib.nvmlDeviceGetHandleByIndex_v2(0, ctypes.byref(dev))
|
||||
u = _Util()
|
||||
_nvml_lib.nvmlDeviceGetUtilizationRates(dev, ctypes.byref(u))
|
||||
_nvml_ok = True
|
||||
return float(u.gpu)
|
||||
except Exception:
|
||||
_nvml_ok = False
|
||||
return -1.0
|
||||
|
||||
|
||||
def _get_gpu_usage() -> float:
|
||||
# NVIDIA
|
||||
# pynvml — subprocess-free, works everywhere if installed
|
||||
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
|
||||
import pynvml # type: ignore
|
||||
pynvml.nvmlInit()
|
||||
h = pynvml.nvmlDeviceGetHandleByIndex(0)
|
||||
return float(pynvml.nvmlDeviceGetUtilizationRates(h).gpu)
|
||||
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
|
||||
return _nvml_gpu()
|
||||
|
||||
|
||||
def _get_cpu_temp() -> float:
|
||||
# psutil sensors (Linux + some Windows drivers)
|
||||
# psutil — works on Linux; occasionally Windows with proper drivers
|
||||
try:
|
||||
temps = psutil.sensors_temperatures()
|
||||
for name in ["coretemp", "k10temp", "cpu_thermal", "acpitz",
|
||||
@@ -69,32 +96,14 @@ def _get_cpu_temp() -> float:
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Windows — WMI thermal zone
|
||||
# Windows: wmi module (pure Python COM, zero subprocess)
|
||||
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))
|
||||
import wmi # type: ignore
|
||||
w = wmi.WMI(namespace="root/wmi")
|
||||
tz = w.MSAcpi_ThermalZoneTemperature()
|
||||
if tz:
|
||||
return (tz[0].CurrentTemperature / 10.0) - 273.15
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -102,10 +111,7 @@ def _get_cpu_temp() -> float:
|
||||
|
||||
|
||||
def get_system_status() -> dict:
|
||||
"""
|
||||
Snapshot of current system metrics.
|
||||
Used by the system_status tool so the user can ask verbally.
|
||||
"""
|
||||
"""Snapshot of current system metrics for the system_status tool."""
|
||||
cpu = psutil.cpu_percent(interval=0.2)
|
||||
ram = psutil.virtual_memory()
|
||||
temp = _get_cpu_temp()
|
||||
@@ -131,8 +137,7 @@ def get_system_status() -> dict:
|
||||
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.
|
||||
Call check() periodically; returns a [SYSTEM_ALERT] string or None.
|
||||
"""
|
||||
|
||||
def __init__(self, thresholds: dict | None = None):
|
||||
@@ -147,10 +152,6 @@ class SystemMonitor:
|
||||
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
|
||||
@@ -161,7 +162,6 @@ class SystemMonitor:
|
||||
|
||||
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"):
|
||||
|
||||
+88
-8
@@ -56,6 +56,29 @@ def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||
return results
|
||||
|
||||
|
||||
def _ddg_news(query: str, max_results: int = 8) -> list[dict]:
|
||||
"""DDG news search — returns actual articles, not website homepages."""
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
except ImportError:
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
results = []
|
||||
try:
|
||||
with DDGS() as ddgs:
|
||||
for r in ddgs.news(query, max_results=max_results):
|
||||
results.append({
|
||||
"title": r.get("title", ""),
|
||||
"snippet": r.get("body", ""),
|
||||
"url": r.get("url", ""),
|
||||
"source": r.get("source", ""),
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG news() failed ({e}) — falling back to text search")
|
||||
results = _ddg_search(query, max_results=max_results)
|
||||
return results
|
||||
|
||||
|
||||
def _format_ddg(query: str, results: list[dict]) -> str:
|
||||
if not results:
|
||||
return f"No results found for: {query}"
|
||||
@@ -69,6 +92,25 @@ def _format_ddg(query: str, results: list[dict]) -> str:
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
def _format_news(query: str, results: list[dict]) -> str:
|
||||
if not results:
|
||||
return f"No news found for: {query}"
|
||||
|
||||
lines = [f"Latest news: {query}\n"]
|
||||
for i, r in enumerate(results, 1):
|
||||
title = r.get("title", "")
|
||||
if not title:
|
||||
continue
|
||||
src = f" [{r['source']}]" if r.get("source") else ""
|
||||
lines.append(f"{i}. {title}{src}")
|
||||
if r.get("snippet"):
|
||||
lines.append(f" {r['snippet'][:140]}")
|
||||
if r.get("url"):
|
||||
lines.append(f" {r['url']}")
|
||||
lines.append("")
|
||||
return "\n".join(lines).strip()
|
||||
|
||||
|
||||
# ── Briefing helper ────────────────────────────────────────────────────────────
|
||||
|
||||
def _gemini_headlines(n: int = 5) -> tuple[list[str], str]:
|
||||
@@ -121,14 +163,52 @@ def _search(query: str) -> str:
|
||||
|
||||
|
||||
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)
|
||||
"""
|
||||
Runs Gemini grounded search AND DDG news in parallel.
|
||||
Returns whichever delivers a valid result first; cancels the other.
|
||||
"""
|
||||
import threading
|
||||
|
||||
gemini_query = f"latest news today: {query}" if query else "top world news today"
|
||||
ddg_query = query if query else "world news today"
|
||||
|
||||
result_box = [None] # first valid result lands here
|
||||
lock = threading.Lock()
|
||||
done_evt = threading.Event()
|
||||
failures = [0]
|
||||
|
||||
def _store(r: str) -> None:
|
||||
if r and len(r) > 60:
|
||||
with lock:
|
||||
if result_box[0] is None:
|
||||
result_box[0] = r
|
||||
done_evt.set()
|
||||
else:
|
||||
with lock:
|
||||
failures[0] += 1
|
||||
if failures[0] >= 2: # both failed — unblock caller
|
||||
done_evt.set()
|
||||
|
||||
def _try_gemini():
|
||||
try:
|
||||
_store(_gemini_search(gemini_query))
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini news failed ({e})")
|
||||
_store("")
|
||||
|
||||
def _try_ddg():
|
||||
try:
|
||||
results = _ddg_news(ddg_query, max_results=8)
|
||||
_store(_format_news(ddg_query, results))
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG news failed ({e})")
|
||||
_store("")
|
||||
|
||||
threading.Thread(target=_try_gemini, daemon=True).start()
|
||||
threading.Thread(target=_try_ddg, daemon=True).start()
|
||||
|
||||
done_evt.wait(timeout=10.0)
|
||||
return result_box[0] or f"No news found for: {query}"
|
||||
|
||||
|
||||
def _research(query: str) -> str:
|
||||
|
||||
Reference in new issue
Block a user