Add files via upload

This commit is contained in:
FatihMakes authored and GitHub committed 2026-06-06 17:41:38 +03:00
1 parent d3e8504706
commit 502309ad24
25 files changed
+4097 -3006

No files matched your search

+1
View File
@@ -0,0 +1 @@
# core package
+137
View File
@@ -0,0 +1,137 @@
"""
MARK XL — Dependency auto-installer.
Called automatically on first launch and after engine reconfiguration.
Installs only the packages that are actually missing, then exits cleanly.
"""
from __future__ import annotations
import importlib.util
import platform
import subprocess
import sys
from typing import Callable
# ── Package lists ─────────────────────────────────────────────────────────
# Each entry: (import_name, pip_package_name)
_CORE: list[tuple[str, str]] = [
("psutil", "psutil"),
("PIL", "pillow"),
("sounddevice", "sounddevice"),
("numpy", "numpy"),
("requests", "requests"),
("bs4", "beautifulsoup4"),
("duckduckgo_search", "duckduckgo-search"),
("pyautogui", "pyautogui"),
("pyperclip", "pyperclip"),
("pygetwindow", "pygetwindow"),
("mss", "mss"),
("cv2", "opencv-python"),
("soundfile", "soundfile"),
("miniaudio", "miniaudio"),
("send2trash", "send2trash"),
("pptx", "python-pptx"),
("youtube_transcript_api", "youtube-transcript-api"),
]
# Windows-only (pywinauto, pycaw, win10toast, comtypes)
_WINDOWS: list[tuple[str, str]] = [
("comtypes", "comtypes"),
("pycaw", "pycaw"),
("win10toast", "win10toast"),
("pywinauto", "pywinauto"),
]
# STT engine packages
_STT: dict[str, list[tuple[str, str]]] = {
"whisper": [("faster_whisper", "faster-whisper")],
"vosk": [("vosk", "vosk")],
}
# TTS engine packages
_TTS: dict[str, list[tuple[str, str]]] = {
"edgetts": [("edge_tts", "edge-tts")],
"kokoro": [("kokoro", "kokoro")],
"elevenlabs": [], # uses only requests, already in core
}
# ── Helpers ───────────────────────────────────────────────────────────────
def _available(module: str) -> bool:
"""Return True if the module can be imported (no actual import)."""
return importlib.util.find_spec(module) is not None
def _pip(package: str, log: Callable | None = None) -> bool:
if log:
log(f"SYS: pip install {package} …")
result = subprocess.run(
[
sys.executable, "-m", "pip", "install", package,
"--quiet", "--disable-pip-version-check",
],
capture_output=True,
)
ok = result.returncode == 0
if not ok and log:
stderr = result.stderr.decode(errors="replace").strip()
log(f"ERR: {package} install failed — {stderr[:140]}")
return ok
# ── Public API ────────────────────────────────────────────────────────────
def install_for_config(config: dict, log: Callable | None = None) -> None:
"""
Install all missing packages required by *config*.
Blocking — always call from a background thread.
Progress is reported via the optional *log* callback (receives a str).
"""
stt = config.get("stt_engine", "whisper").lower()
tts = config.get("tts_engine", "edgetts").lower()
needed: list[tuple[str, str]] = list(_CORE)
needed += _STT.get(stt, [])
needed += _TTS.get(tts, [])
if platform.system() == "Windows":
needed += _WINDOWS
# Deduplicate (preserve order, key = pip name)
seen: set[str] = set()
unique: list[tuple[str, str]] = []
for mod, pkg in needed:
if pkg not in seen:
seen.add(pkg)
unique.append((mod, pkg))
missing = [(mod, pkg) for mod, pkg in unique if not _available(mod)]
if not missing:
if log:
log("SYS: All dependencies already installed ✓")
return
pkg_names = ", ".join(p for _, p in missing)
if log:
log(f"SYS: Installing {len(missing)} package(s): {pkg_names}")
for _mod, pkg in missing:
_pip(pkg, log)
# Playwright: install the package + download Chromium browser
if not _available("playwright"):
_pip("playwright", log)
if log:
log("SYS: Downloading Playwright browser (Chromium, ~150 MB — one-time)…")
subprocess.run(
[sys.executable, "-m", "playwright", "install", "chromium"],
capture_output=True,
)
if log:
log("SYS: Playwright browser ready.")
if log:
log("SYS: All dependencies ready ✓")
+308
View File
@@ -0,0 +1,308 @@
"""
Ollama LLM client for MARK XL.
Replaces Google Gemini API with local Ollama inference.
All modules that previously used google.generativeai import from here.
"""
import json
import re
import subprocess
import sys
import time
from pathlib import Path
from typing import Generator
import requests
# Matches a sentence boundary: [.!?] followed by whitespace, or a blank line.
# Avoids splitting on decimals (3.5) because those have no space after the dot.
_SENT_END = re.compile(r'(?<=[.!?])\s+|(?<=\n)\s*\n')
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()
CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
_DEFAULTS = {
"llm_url": "http://localhost:11434",
"llm_model": "llama3.2",
}
def _load_config() -> dict:
try:
return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
except Exception:
return {}
def ensure_ollama_running(timeout: int = 15) -> bool:
"""
Ping Ollama; if it's not responding, launch 'ollama serve' in the background
and wait up to `timeout` seconds for it to become ready.
Returns True if Ollama is available, False otherwise.
"""
url, _ = get_llm_settings()
health = f"{url}/api/tags"
def _is_up() -> bool:
try:
return requests.get(health, timeout=3).status_code == 200
except Exception:
return False
if _is_up():
return True
print("[LLM] Ollama not running — launching 'ollama serve'…")
try:
kwargs: dict = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
if sys.platform == "win32":
kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
subprocess.Popen(["ollama", "serve"], **kwargs)
except FileNotFoundError:
print("[LLM] 'ollama' command not found. Install Ollama from https://ollama.com")
return False
except Exception as e:
print(f"[LLM] Could not launch Ollama: {e}")
return False
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(1.0)
if _is_up():
print("[LLM] Ollama started successfully.")
return True
print("[LLM] Ollama did not respond within the timeout.")
return False
def warmup_model() -> bool:
"""
Pre-load the model into Ollama memory so the first real request is instant.
Sends a minimal 1-token request with keep_alive=-1.
Returns True on success, False if warmup failed (non-fatal).
"""
url, model = get_llm_settings()
print(f"[LLM] Warming up '{model}'…")
payload = {
"model": model,
"messages": [{"role": "user", "content": "hi"}],
"stream": False,
"keep_alive": -1,
"options": {"num_predict": 1},
}
try:
resp = requests.post(f"{url}/api/chat", json=payload, timeout=120)
resp.raise_for_status()
print(f"[LLM] '{model}' loaded and ready.")
return True
except Exception as e:
print(f"[LLM] Warmup failed (non-fatal): {e}")
return False
def get_llm_settings() -> tuple[str, str]:
"""Returns (base_url, model_name)."""
cfg = _load_config()
url = cfg.get("llm_url", _DEFAULTS["llm_url"]).rstrip("/")
model = cfg.get("llm_model", _DEFAULTS["llm_model"])
return url, model
def call_llm(
messages: list,
tools: list | None = None,
timeout: int = 120,
) -> dict:
"""
Chat request to Ollama (with optional tool declarations).
Returns:
{"content": str, "tool_calls": list}
"""
url, model = get_llm_settings()
endpoint = f"{url}/api/chat"
payload: dict = {
"model": model,
"messages": messages,
"stream": False,
"keep_alive": -1,
"options": {"num_predict": 600},
}
if tools:
payload["tools"] = tools
try:
resp = requests.post(endpoint, json=payload, timeout=timeout)
resp.raise_for_status()
data = resp.json()
msg = data.get("message", {})
return {
"content": (msg.get("content") or "").strip(),
"tool_calls": msg.get("tool_calls") or [],
}
except requests.exceptions.ConnectionError as e:
print(f"[LLM] ConnectionError — trying to restart Ollama… ({e})")
if ensure_ollama_running():
try:
resp = requests.post(endpoint, json=payload, timeout=timeout)
resp.raise_for_status()
data = resp.json()
msg = data.get("message", {})
return {
"content": (msg.get("content") or "").strip(),
"tool_calls": msg.get("tool_calls") or [],
}
except Exception:
pass
raise RuntimeError(
f"Cannot connect to Ollama at {url}. "
"Make sure Ollama is installed and run: ollama serve"
)
except requests.exceptions.Timeout:
raise RuntimeError("Ollama request timed out after 120 s.")
except requests.exceptions.HTTPError as e:
print(f"[LLM] HTTPError: {e.response.status_code} — {e.response.text[:200]}")
raise RuntimeError(f"Ollama HTTP error: {e.response.status_code}")
except Exception as e:
print(f"[LLM] Unexpected error: {type(e).__name__}: {e}")
raise RuntimeError(f"LLM call failed: {e}")
def call_llm_text(
prompt: str,
system: str | None = None,
model: str | None = None,
timeout: int = 120,
) -> str:
"""
Simple text-only generation (no tools).
Used by planner, executor, error_handler, code_helper, dev_agent.
"""
url, default_model = get_llm_settings()
endpoint = f"{url}/api/chat"
m = model or default_model
messages: list[dict] = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": prompt})
payload = {"model": m, "messages": messages, "stream": False, "keep_alive": -1, "options": {"num_predict": 600}}
try:
resp = requests.post(endpoint, json=payload, timeout=timeout)
resp.raise_for_status()
return (resp.json().get("message", {}).get("content") or "").strip()
except requests.exceptions.ConnectionError:
if ensure_ollama_running():
try:
resp = requests.post(endpoint, json=payload, timeout=timeout)
resp.raise_for_status()
return (resp.json().get("message", {}).get("content") or "").strip()
except Exception:
pass
raise RuntimeError(
f"Cannot connect to Ollama at {url}. "
"Make sure Ollama is installed and run: ollama serve"
)
except Exception as e:
raise RuntimeError(f"LLM text call failed: {e}")
def call_llm_stream(
messages: list,
tools: list | None = None,
timeout: int = 120,
) -> Generator[dict, None, None]:
"""
Streaming chat request to Ollama.
Yields:
{"type": "sentence", "text": str} — each complete sentence as it arrives
{"type": "done", "content": str, "tool_calls": list} — when stream ends
Sentences are split on [.!?] + whitespace so TTS can start immediately.
Tool calls (if any) always appear in the final "done" event with empty content.
"""
url, model = get_llm_settings()
endpoint = f"{url}/api/chat"
payload: dict = {
"model": model,
"messages": messages,
"stream": True,
"keep_alive": -1,
"options": {"num_predict": 600},
}
if tools:
payload["tools"] = tools
def _do_stream() -> Generator[dict, None, None]:
with requests.post(endpoint, json=payload, timeout=timeout, stream=True) as resp:
resp.raise_for_status()
full_content = ""
tool_calls: list = []
buf = ""
for raw in resp.iter_lines():
if not raw:
continue
try:
chunk = json.loads(raw)
except json.JSONDecodeError:
continue
msg = chunk.get("message", {})
delta = msg.get("content") or ""
full_content += delta
buf += delta
# Yield complete sentences as they accumulate
while True:
m = _SENT_END.search(buf)
if not m:
break
sentence = buf[: m.start() + 1].strip()
buf = buf[m.end() :]
if sentence:
yield {"type": "sentence", "text": sentence}
tc = msg.get("tool_calls")
if tc:
tool_calls.extend(tc)
if chunk.get("done"):
if buf.strip():
yield {"type": "sentence", "text": buf.strip()}
yield {
"type": "done",
"content": full_content.strip(),
"tool_calls": tool_calls,
}
return
try:
yield from _do_stream()
except requests.exceptions.ConnectionError as e:
print(f"[LLM] Stream ConnectionError — trying to restart Ollama… ({e})")
if ensure_ollama_running():
yield from _do_stream()
return
raise RuntimeError(
f"Cannot connect to Ollama at {url}. "
"Make sure Ollama is installed and run: ollama serve"
)
except requests.exceptions.Timeout:
raise RuntimeError("Ollama stream timed out.")
except requests.exceptions.HTTPError as e:
raise RuntimeError(f"Ollama HTTP error: {e.response.status_code}")
except Exception as e:
print(f"[LLM] Stream error: {type(e).__name__}: {e}")
raise RuntimeError(f"LLM stream failed: {e}")
+1 -2
View File
@@ -1,5 +1,5 @@
🧠 JARVIS CORE PROTOCOL
IDENTITY: Efficient, professional, direct assistant. No fluff.
IDENTITY: You are Jarvis. Efficient, professional, direct assistant. No fluff.
EXECUTION RULES:
@@ -18,5 +18,4 @@ agent_task: ONLY for complex, multi-step planning (3+ steps) and call it if user
Language: Respond in user's language; extract parameters in English.
Do not call agent_task while you can accomplish it with a tool
CRITICAL: Speak/Take action immediately based on available info. Assume and proceed.
+59
View File
@@ -0,0 +1,59 @@
"""
Speech-to-Text engines for MARK XL.
Whisper – offline transcription via faster-whisper (VAD-buffered)
Vosk – offline streaming transcription (lighter)
"""
import json
import numpy as np
class WhisperSTT:
"""Offline transcription using faster-whisper."""
def __init__(self, model_name: str = "base", language: str | None = None):
from faster_whisper import WhisperModel
print(f"[STT] Loading Whisper '{model_name}'…")
self._model = WhisperModel(model_name, device="cpu", compute_type="int8")
# None → auto-detect; explicit code (e.g. "tr", "de") forces that language
self._language = None if (not language or language.strip().lower() == "auto") else language.strip().lower()
print("[STT] Whisper ready.")
def transcribe(self, audio: np.ndarray) -> str:
"""
Transcribe a float32 mono 16 kHz numpy array.
Returns transcript string (may be empty).
"""
segments, _ = self._model.transcribe(
audio,
language=self._language,
vad_filter=True,
vad_parameters={"min_silence_duration_ms": 300},
)
return " ".join(s.text for s in segments).strip()
class VoskSTT:
"""Streaming transcription using Vosk."""
def __init__(self, model_path: str | None = None, language: str = "en-us"):
from vosk import Model, KaldiRecognizer
print("[STT] Loading Vosk model…")
if model_path:
model = Model(model_path)
else:
lang = language.strip().lower() if language and language.strip().lower() != "auto" else "en-us"
model = Model(lang=lang)
self._rec = KaldiRecognizer(model, 16000)
print("[STT] Vosk ready.")
def process_chunk(self, audio_bytes: bytes) -> tuple[str, bool]:
"""
Feed raw int16 LE PCM bytes.
Returns (text, is_final).
"""
if self._rec.AcceptWaveform(audio_bytes):
result = json.loads(self._rec.Result())
return result.get("text", ""), True
partial = json.loads(self._rec.PartialResult())
return partial.get("partial", ""), False
+276
View File
@@ -0,0 +1,276 @@
"""
Text-to-Speech engines for MARK XL.
EdgeTTS – free Microsoft TTS (internet required, no API key)
Kokoro – fully offline neural TTS (~330 MB model)
ElevenLabs – cloud API (API key required, best quality)
"""
from __future__ import annotations
import asyncio
import threading
from typing import Callable, Optional
import numpy as np
import sounddevice as sd
# ---------------------------------------------------------------------------
# Audio playback helpers
# ---------------------------------------------------------------------------
def _to_numpy(samples) -> np.ndarray:
"""Convert samples to float32 numpy array.
Handles both numpy arrays and PyTorch tensors (Kokoro >= 0.9).
PyTorch built against numpy 1.x raises RuntimeError('Numpy is not available')
when numpy 2.x is installed. The .tolist() fallback always works regardless
of PyTorch / numpy version pairing.
"""
if hasattr(samples, "detach"): # PyTorch tensor
t = samples.detach().cpu().float()
try:
return t.numpy() # fast path (compatible versions)
except RuntimeError:
# PyTorch/numpy version mismatch — convert via Python list (always safe)
return np.asarray(t.tolist(), dtype=np.float32)
return np.asarray(samples, dtype=np.float32)
def _compress_silence(
arr: np.ndarray,
sample_rate: int = 24_000,
max_silence_ms: int = 300, # cap long pauses to this many ms
threshold: float = 0.0015, # RMS below this = silence (very conservative)
) -> np.ndarray:
"""
Shorten excessively long silent segments in Kokoro audio.
Kokoro can produce 1-2 s pauses after punctuation. This caps them
to max_silence_ms while leaving natural short pauses intact.
threshold is intentionally low (0.0015) so soft consonants like
's', 'f', 'h' are never misidentified as silence.
"""
max_samp = int(max_silence_ms * sample_rate / 1000)
frame_len = 240 # ~10 ms at 24 kHz
out: list[np.ndarray] = []
silent_acc = 0
for i in range(0, len(arr), frame_len):
chunk = arr[i : i + frame_len]
if np.sqrt(np.mean(chunk ** 2) + 1e-12) < threshold:
silent_acc += len(chunk)
if silent_acc <= max_samp:
out.append(chunk)
else:
silent_acc = 0
out.append(chunk)
return np.concatenate(out) if out else arr
def _play_np(samples, sample_rate: int) -> None:
"""Play float32 mono (or stereo) audio via sounddevice.
Accepts numpy arrays or PyTorch tensors.
"""
sd.play(_to_numpy(samples), sample_rate)
sd.wait()
def _play_audio_bytes(audio_bytes: bytes) -> None:
"""Decode MP3/WAV/OGG bytes and play via sounddevice (uses miniaudio)."""
import miniaudio
decoded = miniaudio.decode(
audio_bytes,
output_format=miniaudio.SampleFormat.FLOAT32,
nchannels=1,
)
samples = np.array(decoded.samples, dtype=np.float32)
sd.play(samples, decoded.sample_rate)
sd.wait()
# ---------------------------------------------------------------------------
# Engines
# ---------------------------------------------------------------------------
class EdgeTTSEngine:
"""Microsoft EdgeTTS – free, requires internet."""
def __init__(self, voice: str = "en-US-GuyNeural"):
self.voice = voice
def speak(self, text: str) -> None:
loop = asyncio.new_event_loop()
try:
audio_bytes = loop.run_until_complete(self._synth(text))
finally:
loop.close()
if audio_bytes:
_play_audio_bytes(audio_bytes)
async def _synth(self, text: str) -> bytes:
import edge_tts
comm = edge_tts.Communicate(text, self.voice)
buf = bytearray()
async for chunk in comm.stream():
if chunk["type"] == "audio":
buf.extend(chunk["data"])
return bytes(buf)
# Kokoro voice prefix → KPipeline lang_code mapping
_KOKORO_LANG_CODES = {
"a": "a", # American English (af_*, am_*)
"b": "b", # British English (bf_*, bm_*)
"j": "j", # Japanese (jf_*, jm_*)
"z": "z", # Mandarin Chinese (zf_*, zm_*)
"s": "s", # Spanish (sf_*, sm_*)
"f": "f", # French (ff_*, fm_*)
"h": "h", # Hindi (hf_*, hm_*)
"i": "i", # Italian (if_*, im_*)
"p": "p", # Brazilian Portuguese
"r": "r", # Russian (rf_*, rm_*)
"e": "e", # German (ef_*, em_*)
}
class KokoroTTSEngine:
"""Fully offline Kokoro neural TTS.
Model (~330 MB) is downloaded from HuggingFace on first use.
Subsequent runs load from local cache instantly.
"""
def __init__(self, voice: str = "af_heart", speed: float = 1.2):
self.voice = voice
self.speed = speed # 1.0 = normal, 1.2 = 20% faster (recommended)
self._pipeline = None
self._lock = threading.Lock()
# Eager init: download/load model now so it's ready before first speak()
self._init()
# Detect lang_code from voice prefix (e.g. "af_heart" → "a")
@property
def _lang_code(self) -> str:
prefix = self.voice[0].lower() if self.voice else "a"
return _KOKORO_LANG_CODES.get(prefix, "a")
def _init(self) -> None:
if self._pipeline is not None:
return
try:
from kokoro import KPipeline
lang = self._lang_code
print(f"[TTS] Loading Kokoro pipeline (lang='{lang}', voice='{self.voice}')…")
print("[TTS] Kokoro model will be downloaded (~330 MB) if not cached.")
self._pipeline = KPipeline(lang_code=lang)
print("[TTS] Kokoro pipeline ready.")
except Exception as e:
print(f"[TTS] Kokoro init error: {e}")
raise
def speak(self, text: str) -> None:
with self._lock:
if self._pipeline is None:
self._init()
for _, _, audio in self._pipeline(text, voice=self.voice, speed=self.speed):
if audio is not None:
arr = _to_numpy(audio)
arr = _compress_silence(arr) # shorten long punctuation pauses
if arr.size > 0:
_play_np(arr, 24000)
class ElevenLabsTTSEngine:
"""ElevenLabs cloud TTS – API key required."""
def __init__(self, api_key: str, voice_id: str = "pNInz6obpgDQGcFmaJgB"):
self.api_key = api_key
self.voice_id = voice_id
def speak(self, text: str) -> None:
import requests
headers = {
"xi-api-key": self.api_key,
"Content-Type": "application/json",
}
payload = {
"text": text,
"model_id": "eleven_multilingual_v2",
"voice_settings": {"stability": 0.5, "similarity_boost": 0.75},
}
resp = requests.post(
f"https://api.elevenlabs.io/v1/text-to-speech/{self.voice_id}",
json=payload, headers=headers, timeout=30,
)
resp.raise_for_status()
_play_audio_bytes(resp.content)
# ---------------------------------------------------------------------------
# Thread-safe player wrapper
# ---------------------------------------------------------------------------
class TTSPlayer:
"""
Wraps any *Engine. Exposes a blocking speak() method
meant to be called from a dedicated background thread.
"""
def __init__(self, engine):
self._engine = engine
self._playing = False
self._lock = threading.Lock()
@property
def is_playing(self) -> bool:
return self._playing
def speak(
self,
text: str,
on_start: Optional[Callable] = None,
on_done: Optional[Callable] = None,
) -> None:
"""Synthesise and play text. BLOCKING – call from a dedicated thread."""
try:
with self._lock:
self._playing = True
if on_start:
on_start()
self._engine.speak(text)
except Exception as e:
print(f"[TTS] Error: {e}")
finally:
with self._lock:
self._playing = False
if on_done:
on_done()
def stop(self) -> None:
sd.stop()
with self._lock:
self._playing = False
# ---------------------------------------------------------------------------
# Factory
# ---------------------------------------------------------------------------
def create_tts_player(config: dict) -> TTSPlayer:
engine_name = config.get("tts_engine", "edgetts").lower()
if engine_name == "kokoro":
voice = config.get("tts_voice", "af_heart")
speed = float(config.get("tts_speed", 1.2))
engine = KokoroTTSEngine(voice=voice, speed=speed)
elif engine_name == "elevenlabs":
api_key = config.get("elevenlabs_api_key", "")
voice_id = config.get("tts_voice", "pNInz6obpgDQGcFmaJgB")
engine = ElevenLabsTTSEngine(api_key=api_key, voice_id=voice_id)
else: # edgetts (default)
voice = config.get("tts_voice", "en-US-GuyNeural")
engine = EdgeTTSEngine(voice=voice)
return TTSPlayer(engine)