Add files via upload
This commit is contained in:
1 parent
d3e8504706
commit
502309ad24
25 files changed
+4097
-3006
No files matched your search
+76
-125
@@ -12,21 +12,10 @@ def get_base_dir():
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
BASE_DIR = get_base_dir()
|
||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
||||
DESKTOP = Path.home() / "Desktop"
|
||||
MAX_BUILD_ATTEMPTS = 3
|
||||
GEMINI_MODEL = "gemini-2.5-flash"
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _get_gemini(model: str = GEMINI_MODEL):
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
return genai.GenerativeModel(model)
|
||||
from core.llm_client import call_llm_text as _llm
|
||||
|
||||
|
||||
def _clean_code(text: str) -> str:
|
||||
@@ -145,47 +134,28 @@ def _detect_intent(description: str, file_path: str, code: str) -> str:
|
||||
return "write"
|
||||
|
||||
def _write(description: str, language: str, output_path: str, player=None) -> tuple[str, Path]:
|
||||
lang = language or "python"
|
||||
model = _get_gemini()
|
||||
|
||||
prompt = f"""You are an expert {lang} developer.
|
||||
Write clean, working, well-commented {lang} code for the description below.
|
||||
|
||||
Rules:
|
||||
- Output ONLY the code. No explanation, no markdown, no backticks.
|
||||
- Add helpful inline comments.
|
||||
- Handle errors and edge cases properly.
|
||||
- Use modern best practices.
|
||||
|
||||
Description: {description}
|
||||
|
||||
Code:"""
|
||||
|
||||
response = model.generate_content(prompt)
|
||||
code = _clean_code(response.text)
|
||||
path = _resolve_save_path(output_path, lang)
|
||||
lang = language or "python"
|
||||
system = f"You are an expert {lang} developer. Output ONLY raw code, no markdown, no backticks, no explanations."
|
||||
prompt = (
|
||||
f"Write clean, working, well-commented {lang} code.\n"
|
||||
f"Handle errors and edge cases. Use modern best practices.\n\n"
|
||||
f"Description: {description}\n\nCode:"
|
||||
)
|
||||
code = _clean_code(_llm(prompt, system=system))
|
||||
path = _resolve_save_path(output_path, lang)
|
||||
_save_file(path, code)
|
||||
return code, path
|
||||
|
||||
|
||||
def _fix_code(code: str, error_output: str, description: str) -> str:
|
||||
model = _get_gemini()
|
||||
prompt = f"""You are an expert debugger.
|
||||
The code below failed with the following error. Fix it.
|
||||
Return ONLY the corrected code — no explanation, no markdown, no backticks.
|
||||
|
||||
Original goal: {description}
|
||||
|
||||
Error:
|
||||
{error_output[:2000]}
|
||||
|
||||
Broken code:
|
||||
{code}
|
||||
|
||||
Fixed code:"""
|
||||
|
||||
response = model.generate_content(prompt)
|
||||
return _clean_code(response.text)
|
||||
system = "You are an expert debugger. Return ONLY the corrected code — no explanation, no markdown, no backticks."
|
||||
prompt = (
|
||||
f"Fix the code below. It failed with this error.\n\n"
|
||||
f"Original goal: {description}\n\n"
|
||||
f"Error:\n{error_output[:2000]}\n\n"
|
||||
f"Broken code:\n{code}\n\nFixed code:"
|
||||
)
|
||||
return _clean_code(_llm(prompt, system=system))
|
||||
|
||||
|
||||
def _run_file(path: Path, args: list, timeout: int) -> str:
|
||||
@@ -303,21 +273,14 @@ def _edit_action(file_path, instruction, player) -> str:
|
||||
if player:
|
||||
player.write_log("[Code] Editing file...")
|
||||
|
||||
model = _get_gemini()
|
||||
prompt = f"""You are an expert code editor.
|
||||
Apply the following change to the code below.
|
||||
Return ONLY the complete updated code — no explanation, no markdown, no backticks.
|
||||
|
||||
Change: {instruction}
|
||||
|
||||
Original code:
|
||||
{content}
|
||||
|
||||
Updated code:"""
|
||||
|
||||
system = "You are an expert code editor. Return ONLY the complete updated code — no explanation, no markdown, no backticks."
|
||||
prompt = (
|
||||
f"Apply the following change to the code below.\n\n"
|
||||
f"Change: {instruction}\n\n"
|
||||
f"Original code:\n{content}\n\nUpdated code:"
|
||||
)
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
edited = _clean_code(response.text)
|
||||
edited = _clean_code(_llm(prompt, system=system))
|
||||
except Exception as e:
|
||||
return f"Could not edit code: {e}"
|
||||
|
||||
@@ -337,19 +300,13 @@ def _explain_action(file_path, code, player) -> str:
|
||||
if player:
|
||||
player.write_log("[Code] Analyzing code...")
|
||||
|
||||
model = _get_gemini()
|
||||
prompt = f"""Explain what this code does in simple, clear language.
|
||||
Focus on: what it does, how it works, and any important details.
|
||||
Be concise — 3 to 6 sentences maximum.
|
||||
|
||||
Code:
|
||||
{code[:4000]}
|
||||
|
||||
Explanation:"""
|
||||
|
||||
system = "You are an expert programmer. Explain code concisely in 3-6 sentences."
|
||||
prompt = (
|
||||
f"Explain what this code does — what it does, how it works, important details.\n\n"
|
||||
f"Code:\n{code[:4000]}\n\nExplanation:"
|
||||
)
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
return response.text.strip()
|
||||
return _llm(prompt, system=system)
|
||||
except Exception as e:
|
||||
return f"Could not explain code: {e}"
|
||||
|
||||
@@ -377,26 +334,15 @@ def _optimize_action(file_path, code, language, output_path, player) -> str:
|
||||
if player:
|
||||
player.write_log("[Code] Optimizing code...")
|
||||
|
||||
lang = language or "python"
|
||||
model = _get_gemini()
|
||||
|
||||
prompt = f"""You are an expert {lang} developer and code reviewer.
|
||||
Optimize the following code for:
|
||||
1. Performance — eliminate unnecessary operations, use efficient data structures
|
||||
2. Readability — clear variable names, proper formatting, logical structure
|
||||
3. Best practices — modern {lang} patterns, error handling, type hints if applicable
|
||||
4. Remove dead code, redundant comments, and unnecessary complexity
|
||||
|
||||
Return ONLY the optimized code — no explanation, no markdown, no backticks.
|
||||
|
||||
Original code:
|
||||
{code[:6000]}
|
||||
|
||||
Optimized code:"""
|
||||
|
||||
lang = language or "python"
|
||||
system = f"You are an expert {lang} developer. Return ONLY the optimized code — no explanation, no markdown, no backticks."
|
||||
prompt = (
|
||||
f"Optimize this {lang} code for performance, readability, and best practices. "
|
||||
f"Remove dead code and unnecessary complexity.\n\n"
|
||||
f"Original code:\n{code[:6000]}\n\nOptimized code:"
|
||||
)
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
optimized = _clean_code(response.text)
|
||||
optimized = _clean_code(_llm(prompt, system=system))
|
||||
except Exception as e:
|
||||
return f"Could not optimize code: {e}"
|
||||
|
||||
@@ -441,44 +387,51 @@ def _screen_debug_action(description, file_path, player, speak=None) -> str:
|
||||
print(f"[Code] ⚠️ Could not read file: {err}")
|
||||
|
||||
try:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
import base64, json as _json, requests as _req
|
||||
from pathlib import Path as _Path
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
cfg = {}
|
||||
cfg_file = _Path(__file__).resolve().parent.parent / "config" / "api_keys.json"
|
||||
try:
|
||||
cfg = _json.loads(cfg_file.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
image_bytes = screenshot_path.read_bytes()
|
||||
image_base64 = _image_to_base64(screenshot_path)
|
||||
ollama_url = cfg.get("llm_url", "http://localhost:11434").rstrip("/")
|
||||
vision_model = cfg.get("vision_model") or cfg.get("llm_model", "llava")
|
||||
|
||||
image_bytes = screenshot_path.read_bytes()
|
||||
b64 = base64.b64encode(image_bytes).decode("ascii")
|
||||
user_question = description or "What error or problem do you see on the screen? How can it be fixed?"
|
||||
|
||||
context = ""
|
||||
context = ""
|
||||
if file_content:
|
||||
context = f"\n\nAdditionally, here is the related file content:\n```\n{file_content[:4000]}\n```"
|
||||
context = f"\n\nRelated file content:\n```\n{file_content[:4000]}\n```"
|
||||
|
||||
analysis_prompt = f"""You are an expert programmer and debugger analyzing a screenshot.
|
||||
|
||||
User's question: {user_question}{context}
|
||||
|
||||
Please:
|
||||
1. Identify any errors, exceptions, or problems visible on the screen
|
||||
2. Explain what is causing the problem in simple terms
|
||||
3. Provide a concrete fix or solution
|
||||
4. If there's code visible, show the corrected version
|
||||
|
||||
Be specific and actionable. If you see an error message, quote it exactly."""
|
||||
|
||||
contents = [
|
||||
types.Part.from_bytes(data=image_bytes, mime_type="image/png"),
|
||||
analysis_prompt,
|
||||
]
|
||||
|
||||
response = client.models.generate_content(
|
||||
model="gemini-2.5-flash",
|
||||
contents=contents,
|
||||
analysis_prompt = (
|
||||
f"You are an expert programmer/debugger analyzing a screenshot.\n\n"
|
||||
f"User question: {user_question}{context}\n\n"
|
||||
f"Identify errors, explain the cause, and provide a fix. "
|
||||
f"If you see code, show the corrected version."
|
||||
)
|
||||
|
||||
analysis = response.text.strip()
|
||||
print(f"[Code] ✅ Screen analysis complete")
|
||||
resp = _req.post(
|
||||
f"{ollama_url}/api/chat",
|
||||
json={
|
||||
"model": vision_model,
|
||||
"stream": False,
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": analysis_prompt,
|
||||
"images": [b64],
|
||||
}
|
||||
],
|
||||
},
|
||||
timeout=60,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
analysis = (resp.json().get("message", {}).get("content") or "").strip()
|
||||
print("[Code] ✅ Screen analysis complete")
|
||||
|
||||
try:
|
||||
screenshot_path.unlink()
|
||||
@@ -486,7 +439,6 @@ Be specific and actionable. If you see an error message, quote it exactly."""
|
||||
pass
|
||||
|
||||
if file_path and file_content:
|
||||
|
||||
code_match = re.search(r"```[a-zA-Z]*\n(.*?)```", analysis, re.DOTALL)
|
||||
if code_match:
|
||||
fixed_code = code_match.group(1).strip()
|
||||
@@ -498,7 +450,6 @@ Be specific and actionable. If you see an error message, quote it exactly."""
|
||||
return analysis
|
||||
|
||||
except Exception as e:
|
||||
|
||||
try:
|
||||
screenshot_path.unlink()
|
||||
except Exception:
|
||||
|
||||
+28
-20
@@ -40,12 +40,13 @@ def _load_config() -> dict:
|
||||
return {}
|
||||
|
||||
def _get_os() -> str:
|
||||
return _load_config().get("os_system", "windows").lower()
|
||||
import platform
|
||||
s = platform.system().lower()
|
||||
if s == "darwin":
|
||||
return "mac"
|
||||
return s # "windows" or "linux"
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
return _load_config().get("gemini_api_key", "")
|
||||
|
||||
_SAFE_SCREENSHOT_ROOTS = (
|
||||
Path.home(),
|
||||
)
|
||||
@@ -297,23 +298,27 @@ def _focus_window(title: str) -> str:
|
||||
return f"focus_window: unknown OS '{os_name}'"
|
||||
|
||||
def _screen_find(description: str) -> tuple[int, int] | None:
|
||||
api_key = _get_api_key()
|
||||
if not api_key:
|
||||
print("[ComputerControl] ⚠️ No API key for screen_find")
|
||||
return None
|
||||
|
||||
try:
|
||||
from google import genai
|
||||
from google.genai import types as gtypes
|
||||
import base64
|
||||
import requests as _req
|
||||
import json as _json
|
||||
|
||||
cfg_path = Path(__file__).resolve().parent.parent / "config" / "api_keys.json"
|
||||
try:
|
||||
cfg = _json.loads(cfg_path.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
cfg = {}
|
||||
|
||||
ollama_url = cfg.get("llm_url", "http://localhost:11434").rstrip("/")
|
||||
vision_model = cfg.get("vision_model") or cfg.get("llm_model", "llava")
|
||||
|
||||
_require_pyautogui()
|
||||
w, h = pyautogui.size()
|
||||
img = pyautogui.screenshot()
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
image_bytes = buf.getvalue()
|
||||
b64 = base64.b64encode(buf.getvalue()).decode("ascii")
|
||||
|
||||
client = genai.Client(api_key=api_key)
|
||||
prompt = (
|
||||
f"This is a screenshot of a {w}×{h} pixel screen. "
|
||||
f"Locate the UI element described as: '{description}'. "
|
||||
@@ -321,15 +326,18 @@ def _screen_find(description: str) -> tuple[int, int] | None:
|
||||
f"If the element is not visible, reply: NOT_FOUND"
|
||||
)
|
||||
|
||||
response = client.models.generate_content(
|
||||
model="gemini-2.5-flash-lite",
|
||||
contents=[
|
||||
gtypes.Part.from_bytes(data=image_bytes, mime_type="image/png"),
|
||||
prompt,
|
||||
],
|
||||
resp = _req.post(
|
||||
f"{ollama_url}/api/chat",
|
||||
json={
|
||||
"model": vision_model,
|
||||
"stream": False,
|
||||
"messages": [{"role": "user", "content": prompt, "images": [b64]}],
|
||||
},
|
||||
timeout=30,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
text = (resp.json().get("message", {}).get("content") or "").strip()
|
||||
|
||||
text = (response.text or "").strip()
|
||||
if "NOT_FOUND" in text.upper():
|
||||
return None
|
||||
|
||||
|
||||
@@ -29,11 +29,6 @@ def _get_base_dir() -> Path:
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
def _get_api_key() -> str:
|
||||
path = _get_base_dir() / "config" / "api_keys.json"
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
def _get_macos_wifi_interface() -> str:
|
||||
try:
|
||||
result = subprocess.run(
|
||||
@@ -569,35 +564,24 @@ _DANGEROUS_ACTIONS = {"restart", "shutdown"}
|
||||
|
||||
|
||||
def _detect_action(description: str) -> dict:
|
||||
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel("gemini-2.5-flash-lite")
|
||||
from core.llm_client import call_llm_text
|
||||
|
||||
available = ", ".join(sorted(ACTION_MAP.keys())) + \
|
||||
", volume_set, type_text, press_key, reload_n"
|
||||
|
||||
prompt = f"""You are an intent detector for a computer control assistant.
|
||||
|
||||
The user issued a command (possibly in any language): "{description}"
|
||||
|
||||
Available actions: {available}
|
||||
|
||||
Return ONLY a valid JSON object:
|
||||
{{"action": "action_name", "value": null_or_value}}
|
||||
|
||||
Rules:
|
||||
- Pick the single best matching action from the available list.
|
||||
- For volume_set: value is an integer 0-100.
|
||||
- For type_text: value is the exact text to type.
|
||||
- For press_key: value is the key name (e.g. "f5", "tab", "enter").
|
||||
- For reload_n: value is an integer (number of times to reload).
|
||||
- If no clear match, pick the closest action.
|
||||
- Return ONLY the JSON, no explanation, no markdown."""
|
||||
|
||||
system = (
|
||||
"You are an intent detector. Return ONLY a valid JSON object — "
|
||||
"no explanation, no markdown."
|
||||
)
|
||||
prompt = (
|
||||
f'User command (any language): "{description}"\n\n'
|
||||
f"Available actions: {available}\n\n"
|
||||
f'Return: {{"action": "action_name", "value": null_or_value}}\n'
|
||||
f"Rules: volume_set→int 0-100; type_text→exact text; press_key→key name; reload_n→int."
|
||||
)
|
||||
try:
|
||||
resp = model.generate_content(prompt)
|
||||
text = re.sub(r"```(?:json)?", "", resp.text).strip().rstrip("`").strip()
|
||||
text = call_llm_text(prompt, system=system)
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
return json.loads(text)
|
||||
except Exception as e:
|
||||
print(f"[Settings] Intent detection failed: {e}")
|
||||
|
||||
+15
-40
@@ -23,11 +23,6 @@ def _get_base_dir() -> Path:
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
def _get_api_key() -> str:
|
||||
path = _get_base_dir() / "config" / "api_keys.json"
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
def _get_desktop() -> Path:
|
||||
if _OS == "Linux":
|
||||
xdg = os.environ.get("XDG_DESKTOP_DIR", "")
|
||||
@@ -102,49 +97,29 @@ def _execute_generated_code(code: str, player=None) -> str:
|
||||
|
||||
|
||||
def _ask_gemini_for_desktop_action(task: str) -> str:
|
||||
from core.llm_client import call_llm_text
|
||||
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel("gemini-2.5-flash")
|
||||
|
||||
desktop = str(_get_desktop())
|
||||
|
||||
desktop = str(_get_desktop())
|
||||
os_specific = ""
|
||||
if _OS == "Windows":
|
||||
os_specific = "- ctypes (Windows API calls, read-only)\n- winreg (registry READ only)"
|
||||
elif _OS == "Darwin":
|
||||
os_specific = "- subprocess is NOT available; use pyautogui or Path only"
|
||||
else:
|
||||
os_specific = "- subprocess is NOT available; use pyautogui or Path only"
|
||||
|
||||
prompt = f"""You are a desktop automation assistant.
|
||||
Current OS: {_OS}
|
||||
Desktop path: {desktop}
|
||||
|
||||
Generate safe Python code to accomplish the task below.
|
||||
Allowed modules ONLY:
|
||||
- pyautogui (mouse, keyboard — if needed)
|
||||
- pathlib.Path (file/folder inspection only, no deletion)
|
||||
- shutil.copy2, shutil.copytree, shutil.disk_usage (NO move, NO rmtree)
|
||||
- os_path (os.path equivalent, read-only)
|
||||
- time.sleep
|
||||
{os_specific}
|
||||
|
||||
Hard rules:
|
||||
- NO file deletion (no unlink, no rmtree, no remove)
|
||||
- NO subprocess calls
|
||||
- NO exec() or eval() inside the code
|
||||
- NO import statements (modules are pre-injected)
|
||||
- NO file write operations except explicitly requested
|
||||
- If task cannot be done safely with these tools, output exactly: UNSAFE
|
||||
|
||||
Output ONLY the Python code. No explanation, no markdown, no backticks.
|
||||
|
||||
Task: {task}"""
|
||||
|
||||
system = (
|
||||
"You are a desktop automation code generator. "
|
||||
"Output ONLY raw Python code — no explanation, no markdown, no backticks."
|
||||
)
|
||||
prompt = (
|
||||
f"Current OS: {_OS}\nDesktop path: {desktop}\n\n"
|
||||
f"Allowed modules: pyautogui, pathlib.Path, shutil.copy2, shutil.disk_usage, time.sleep\n"
|
||||
f"{os_specific}\n\n"
|
||||
f"Rules: NO deletion, NO subprocess, NO exec/eval, NO imports.\n"
|
||||
f"If unsafe, output exactly: UNSAFE\n\n"
|
||||
f"Task: {task}"
|
||||
)
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
code = response.text.strip()
|
||||
code = call_llm_text(prompt, system=system).strip()
|
||||
if code.startswith("```"):
|
||||
lines = code.split("\n")
|
||||
code = "\n".join(lines[1:-1]).strip()
|
||||
|
||||
+51
-130
@@ -13,21 +13,10 @@ def get_base_dir():
|
||||
|
||||
|
||||
BASE_DIR = get_base_dir()
|
||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
||||
PROJECTS_DIR = Path.home() / "Desktop" / "JarvisProjects"
|
||||
MAX_FIX_ATTEMPTS = 5
|
||||
MODEL_PLANNER = "gemini-2.5-flash"
|
||||
MODEL_WRITER = "gemini-2.5-flash"
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _get_model(model_name: str):
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
return genai.GenerativeModel(model_name)
|
||||
from core.llm_client import call_llm_text as _llm
|
||||
|
||||
|
||||
def _strip_fences(text: str) -> str:
|
||||
@@ -97,26 +86,28 @@ class RateLimitError(Exception):
|
||||
|
||||
|
||||
def _plan_project(description: str, language: str) -> dict:
|
||||
model = _get_model(MODEL_PLANNER)
|
||||
|
||||
prompt = f"""You are a senior software architect. Create a minimal, complete file plan for this project.
|
||||
system = (
|
||||
"You are a senior software architect. "
|
||||
"Return ONLY valid JSON — no markdown, no explanation."
|
||||
)
|
||||
prompt = f"""Create a minimal, complete file plan for this project.
|
||||
|
||||
Language: {language}
|
||||
Description: {description}
|
||||
|
||||
Return ONLY valid JSON — no markdown, no explanation:
|
||||
Return ONLY valid JSON:
|
||||
{{
|
||||
"project_name": "snake_case_name",
|
||||
"entry_point": "main.py",
|
||||
"files": [
|
||||
{{
|
||||
"path": "main.py",
|
||||
"description": "Entry point — what it does and which modules it imports",
|
||||
"imports": ["utils.helpers", "core.engine"]
|
||||
"description": "Entry point",
|
||||
"imports": ["utils.helpers"]
|
||||
}},
|
||||
{{
|
||||
"path": "utils/helpers.py",
|
||||
"description": "Helper utilities — what functions it exposes",
|
||||
"description": "Helpers",
|
||||
"imports": []
|
||||
}}
|
||||
],
|
||||
@@ -124,25 +115,16 @@ Return ONLY valid JSON — no markdown, no explanation:
|
||||
"dependencies": ["requests"]
|
||||
}}
|
||||
|
||||
Critical rules:
|
||||
1. List files in DEPENDENCY ORDER — files with no imports come first, entry point comes last.
|
||||
2. The "imports" field must list every other project module this file imports (dot-notation, e.g. "utils.helpers").
|
||||
3. Keep it minimal — only files truly needed.
|
||||
4. Entry point must be in the files list.
|
||||
5. Use relative paths only (e.g. "utils/helpers.py", not absolute paths).
|
||||
6. Standard library modules (os, sys, json, etc.) do NOT go in "dependencies".
|
||||
Rules: dependency order, relative paths, entry point last, stdlib NOT in dependencies.
|
||||
|
||||
JSON:"""
|
||||
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
raw = _strip_fences(response.text)
|
||||
raw = _strip_fences(_llm(prompt, system=system))
|
||||
return json.loads(raw)
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"Planner returned invalid JSON: {e}\nRaw: {response.text[:300]}")
|
||||
raise ValueError(f"Planner returned invalid JSON: {e}")
|
||||
except Exception as e:
|
||||
if _is_rate_limit(e):
|
||||
raise RateLimitError(str(e))
|
||||
raise
|
||||
|
||||
def _write_file(
|
||||
@@ -153,80 +135,43 @@ def _write_file(
|
||||
project_dir: Path,
|
||||
already_written: dict[str, str],
|
||||
) -> str:
|
||||
model = _get_model(MODEL_WRITER)
|
||||
|
||||
file_path = file_info["path"]
|
||||
file_desc = file_info.get("description", "")
|
||||
file_path = file_info["path"]
|
||||
file_desc = file_info.get("description", "")
|
||||
file_imports = file_info.get("imports", [])
|
||||
|
||||
file_list = "\n".join(
|
||||
f" [{i+1}] {f['path']}: {f.get('description', '')}"
|
||||
for i, f in enumerate(all_files)
|
||||
)
|
||||
|
||||
dependency_context = ""
|
||||
dep_ctx = ""
|
||||
for dep_dotted in file_imports:
|
||||
dep_path = dep_dotted.replace(".", "/") + ".py"
|
||||
if dep_path in already_written:
|
||||
code_snippet = already_written[dep_path][:2000]
|
||||
dependency_context += f"\n\n--- {dep_path} (you must import from this) ---\n{code_snippet}"
|
||||
dep_ctx += f"\n\n--- {dep_path} ---\n{already_written[dep_path][:2000]}"
|
||||
|
||||
lang_rules = ""
|
||||
if language.lower() == "python":
|
||||
lang_rules = """
|
||||
Python-specific rules:
|
||||
- Use type hints for all function signatures.
|
||||
- Add docstrings for all public functions and classes.
|
||||
- Use if __name__ == "__main__": guard in the entry point.
|
||||
- For relative imports within the project, use: from utils.helpers import foo (match the project structure exactly).
|
||||
- Do NOT use implicit relative imports (from . import ...) unless it's a proper package with __init__.py.
|
||||
- If this is a package subdirectory, create __init__.py files where needed."""
|
||||
elif language.lower() in ("javascript", "typescript", "js", "ts"):
|
||||
lang_rules = """
|
||||
JS/TS-specific rules:
|
||||
- Use ES modules (import/export), not CommonJS (require).
|
||||
- Add JSDoc comments for all exported functions.
|
||||
- Handle promise rejections with try/catch in async functions."""
|
||||
|
||||
prompt = f"""You are a senior {language} developer writing production-quality code for a real project.
|
||||
|
||||
Project goal: {project_description}
|
||||
|
||||
Complete project file structure (in dependency order):
|
||||
{file_list}
|
||||
|
||||
{f"Dependencies this file must import from other project files:{dependency_context}" if dependency_context else ""}
|
||||
|
||||
Your task: Write the complete, working code for: {file_path}
|
||||
Purpose of this file: {file_desc}
|
||||
{f"This file imports from: {', '.join(file_imports)}" if file_imports else "This file has no project-internal imports."}
|
||||
|
||||
{lang_rules}
|
||||
|
||||
General rules:
|
||||
- Output ONLY raw code. Absolutely no explanation, no markdown, no triple backticks.
|
||||
- Write COMPLETE, RUNNABLE code — no placeholders, no "# TODO", no "pass" stubs.
|
||||
- Every import must either be from the standard library, listed dependencies, or the project files shown above.
|
||||
- Match import paths EXACTLY to the file paths in the project structure (e.g. if file is "utils/helpers.py", import as "from utils.helpers import ...").
|
||||
- Use proper error handling (try/except) where I/O or network calls are made.
|
||||
- The code must work correctly when the project entry point is run from the project root directory.
|
||||
|
||||
Code for {file_path}:"""
|
||||
system = (
|
||||
f"You are a senior {language} developer. "
|
||||
"Output ONLY raw code — no explanation, no markdown, no backticks."
|
||||
)
|
||||
prompt = (
|
||||
f"Project goal: {project_description}\n\n"
|
||||
f"Files (dependency order):\n{file_list}\n"
|
||||
f"{dep_ctx}\n\n"
|
||||
f"Write complete code for: {file_path}\n"
|
||||
f"Purpose: {file_desc}\n"
|
||||
f"{'Imports from: ' + ', '.join(file_imports) if file_imports else 'No project-internal imports.'}\n\n"
|
||||
f"Rules: COMPLETE & RUNNABLE code, no placeholders, match import paths exactly.\n\n"
|
||||
f"Code for {file_path}:"
|
||||
)
|
||||
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
code = _strip_fences(response.text)
|
||||
|
||||
code = _strip_fences(_llm(prompt, system=system))
|
||||
full_path = project_dir / file_path
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
full_path.write_text(code, encoding="utf-8")
|
||||
|
||||
print(f"[DevAgent] ✅ Written: {file_path} ({len(code)} chars)")
|
||||
return code
|
||||
|
||||
except Exception as e:
|
||||
if _is_rate_limit(e):
|
||||
raise RateLimitError(str(e))
|
||||
raise
|
||||
|
||||
def _install_dependencies(dependencies: list[str], project_dir: Path) -> str:
|
||||
@@ -350,13 +295,10 @@ def _fix_files(
|
||||
entry_point: str,
|
||||
) -> dict[str, str]:
|
||||
|
||||
model = _get_model(MODEL_PLANNER)
|
||||
|
||||
error_file, error_line = _parse_traceback(error_output, list(file_codes.keys()))
|
||||
error_type = _classify_error(error_output)
|
||||
|
||||
files_to_fix: list[str] = []
|
||||
|
||||
if error_file:
|
||||
files_to_fix.append(error_file)
|
||||
if error_type == "import_error":
|
||||
@@ -370,61 +312,40 @@ def _fix_files(
|
||||
|
||||
updated_codes: dict[str, str] = {}
|
||||
|
||||
system = f"You are an expert {language} debugger. Return ONLY the complete fixed code — no explanation, no markdown, no backticks."
|
||||
|
||||
for fix_path in files_to_fix:
|
||||
current_code = file_codes.get(fix_path, "")
|
||||
|
||||
other_ctx = ""
|
||||
for fp, code in file_codes.items():
|
||||
if fp != fix_path and code:
|
||||
snippet = code[:1500] + ("..." if len(code) > 1500 else "")
|
||||
other_ctx += f"\n--- {fp} ---\n{snippet}\n"
|
||||
other_ctx += f"\n--- {fp} ---\n{code[:1500]}\n"
|
||||
|
||||
line_hint = f"\nError appears to be near line {error_line} in this file." if (
|
||||
error_line and fix_path == error_file
|
||||
) else ""
|
||||
line_hint = (
|
||||
f"\nError near line {error_line} in this file."
|
||||
if error_line and fix_path == error_file else ""
|
||||
)
|
||||
|
||||
prompt = f"""You are an expert {language} debugger. Fix the broken file below.
|
||||
|
||||
Project goal: {project_description}
|
||||
|
||||
All project files:
|
||||
{chr(10).join(f" - {f['path']}: {f.get('description', '')}" for f in all_files)}
|
||||
|
||||
Other files for context (read-only — fix only the target file):
|
||||
{other_ctx[:3500]}
|
||||
|
||||
File to fix: {fix_path}{line_hint}
|
||||
Error type: {error_type}
|
||||
|
||||
Error output:
|
||||
{error_output[:2500]}
|
||||
|
||||
Current (broken) code:
|
||||
{current_code}
|
||||
|
||||
Rules:
|
||||
- Output ONLY the complete fixed code. No explanation, no markdown, no backticks.
|
||||
- Fix ALL errors visible in the error output.
|
||||
- Keep all existing correct logic — do not remove working features.
|
||||
- Ensure import paths match the actual project file structure exactly.
|
||||
- Do NOT introduce new bugs or remove error handling.
|
||||
|
||||
Fixed code for {fix_path}:"""
|
||||
prompt = (
|
||||
f"Project goal: {project_description}\n\n"
|
||||
f"All files:\n"
|
||||
+ "\n".join(f" - {f['path']}: {f.get('description', '')}" for f in all_files)
|
||||
+ f"\n\nOther files (context):\n{other_ctx[:3500]}\n\n"
|
||||
f"File to fix: {fix_path}{line_hint}\n"
|
||||
f"Error type: {error_type}\n\n"
|
||||
f"Error output:\n{error_output[:2500]}\n\n"
|
||||
f"Current code:\n{current_code}\n\n"
|
||||
f"Fixed code for {fix_path}:"
|
||||
)
|
||||
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
fixed = _strip_fences(response.text)
|
||||
|
||||
fixed = _strip_fences(_llm(prompt, system=system))
|
||||
full_path = project_dir / fix_path
|
||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
full_path.write_text(fixed, encoding="utf-8")
|
||||
|
||||
updated_codes[fix_path] = fixed
|
||||
print(f"[DevAgent] 🔧 Fixed: {fix_path}")
|
||||
|
||||
except Exception as e:
|
||||
if _is_rate_limit(e):
|
||||
raise RateLimitError(str(e))
|
||||
print(f"[DevAgent] ⚠️ Could not fix {fix_path}: {e}")
|
||||
|
||||
return updated_codes
|
||||
|
||||
@@ -25,18 +25,19 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
import google.generativeai as genai
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
config_path = Path(__file__).resolve().parent.parent / "config" / "api_keys.json"
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
from core.llm_client import call_llm_text as _llm_text
|
||||
|
||||
|
||||
def _gemini_client():
|
||||
genai.configure(api_key=_get_api_key())
|
||||
return genai.GenerativeModel("gemini-2.5-flash")
|
||||
# Compatibility shim — returns an object with .generate_content()
|
||||
class _Shim:
|
||||
def generate_content(self, prompt: str) -> "_R":
|
||||
class _R:
|
||||
pass
|
||||
r = _R()
|
||||
r.text = _llm_text(prompt)
|
||||
return r
|
||||
return _Shim()
|
||||
|
||||
|
||||
def _detect_type(path: Path) -> str:
|
||||
|
||||
+14
-27
@@ -18,10 +18,6 @@ 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"]
|
||||
|
||||
_MONTH_MAP: dict[str, int] = {
|
||||
|
||||
"january": 1, "february": 2, "march": 3, "april": 4,
|
||||
@@ -62,19 +58,16 @@ def _parse_date(raw: str) -> str:
|
||||
return val.strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel("gemini-2.5-flash-lite")
|
||||
response = model.generate_content(
|
||||
from core.llm_client import call_llm_text
|
||||
result = call_llm_text(
|
||||
f"Today is {today.strftime('%Y-%m-%d')}. "
|
||||
f"Convert this date expression to YYYY-MM-DD: '{raw}'. "
|
||||
f"Return ONLY the date string, nothing else."
|
||||
)
|
||||
result = response.text.strip()
|
||||
).strip()
|
||||
if re.match(r"\d{4}-\d{2}-\d{2}", result):
|
||||
return result
|
||||
except Exception as e:
|
||||
print(f"[FlightFinder] ⚠️ Gemini date parse failed: {e}")
|
||||
print(f"[FlightFinder] ⚠️ LLM date parse failed: {e}")
|
||||
|
||||
for month_name, month_num in _MONTH_MAP.items():
|
||||
if month_name in lower:
|
||||
@@ -152,34 +145,28 @@ def _parse_flights_with_gemini(
|
||||
destination: str,
|
||||
date: str,
|
||||
) -> list[dict]:
|
||||
import google.generativeai as genai
|
||||
from core.llm_client import call_llm_text
|
||||
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(
|
||||
model_name="gemini-2.5-flash",
|
||||
system_instruction=(
|
||||
"You are a flight data extraction expert. "
|
||||
"Extract flight information from raw webpage text. "
|
||||
"Return ONLY valid JSON — no markdown, no explanation."
|
||||
),
|
||||
system = (
|
||||
"You are a flight data extraction expert. "
|
||||
"Extract flight information from raw webpage text. "
|
||||
"Return ONLY valid JSON — no markdown, no explanation."
|
||||
)
|
||||
|
||||
prompt = (
|
||||
f"Extract flight options from {origin} to {destination} on {date} "
|
||||
f"from this Google Flights page text:\n\n{raw_text[:12000]}\n\n"
|
||||
f"from this Google Flights page text:\n\n{raw_text[:8000]}\n\n"
|
||||
f"Return a JSON array of up to 5 flights:\n"
|
||||
f'[{{"airline":"...","departure":"HH:MM","arrival":"HH:MM",'
|
||||
f'"duration":"Xh Ym","stops":0,"price":"...","currency":"USD"}}]\n'
|
||||
f"If no flights found, return: []"
|
||||
)
|
||||
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
text = re.sub(r"```(?:json)?", "", response.text).strip().rstrip("`").strip()
|
||||
flights = json.loads(text)
|
||||
text = call_llm_text(prompt, system=system)
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
flights = json.loads(text)
|
||||
return flights if isinstance(flights, list) else []
|
||||
except Exception as e:
|
||||
print(f"[FlightFinder] ⚠️ Gemini parse failed: {e}")
|
||||
print(f"[FlightFinder] ⚠️ LLM parse failed: {e}")
|
||||
return []
|
||||
|
||||
def _format_spoken(
|
||||
|
||||
+272
-442
@@ -1,442 +1,272 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
import sounddevice as sd
|
||||
|
||||
try:
|
||||
import cv2
|
||||
_CV2 = True
|
||||
except ImportError:
|
||||
_CV2 = False
|
||||
|
||||
try:
|
||||
import mss
|
||||
import mss.tools
|
||||
_MSS = True
|
||||
except ImportError:
|
||||
_MSS = False
|
||||
|
||||
try:
|
||||
import PIL.Image
|
||||
_PIL = True
|
||||
except ImportError:
|
||||
_PIL = False
|
||||
|
||||
from google import genai
|
||||
from google.genai import types as gtypes
|
||||
|
||||
def _base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
_BASE = _base_dir()
|
||||
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
||||
|
||||
|
||||
def _load_config() -> dict:
|
||||
try:
|
||||
return json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_config_key(key: str, value) -> None:
|
||||
try:
|
||||
cfg = _load_config()
|
||||
cfg[key] = value
|
||||
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
key = _load_config().get("gemini_api_key", "")
|
||||
if not key:
|
||||
raise RuntimeError("gemini_api_key not found in config.")
|
||||
return key
|
||||
|
||||
|
||||
def _get_os() -> str:
|
||||
return _load_config().get("os_system", "windows").lower()
|
||||
|
||||
_LIVE_MODEL = "models/gemini-2.5-flash-native-audio-preview-12-2025"
|
||||
_CHANNELS = 1
|
||||
_RECEIVE_SAMPLE_RATE = 24_000
|
||||
_CHUNK_SIZE = 1_024
|
||||
|
||||
_IMG_MAX_W = 640
|
||||
_IMG_MAX_H = 360
|
||||
_JPEG_Q = 60
|
||||
|
||||
_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."
|
||||
)
|
||||
|
||||
|
||||
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
||||
if not _PIL:
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
|
||||
try:
|
||||
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
|
||||
def _capture_screen() -> tuple[bytes, str]:
|
||||
|
||||
if not _MSS:
|
||||
raise RuntimeError("mss is not installed. Run: pip install mss")
|
||||
|
||||
with mss.mss() as sct:
|
||||
monitors = sct.monitors # [0] = all combined, [1..n] = real screens
|
||||
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
||||
shot = sct.grab(target)
|
||||
png = mss.tools.to_png(shot.rgb, shot.size)
|
||||
|
||||
return _compress(png, "PNG")
|
||||
|
||||
|
||||
def _cv2_backend() -> int:
|
||||
"""Return the best OpenCV camera backend for the current OS."""
|
||||
if not _CV2:
|
||||
return 0
|
||||
os_name = _get_os()
|
||||
if os_name == "windows":
|
||||
return cv2.CAP_DSHOW
|
||||
if os_name == "mac":
|
||||
return cv2.CAP_AVFOUNDATION
|
||||
return cv2.CAP_ANY
|
||||
|
||||
|
||||
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
||||
|
||||
if not _CV2:
|
||||
return False
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
if not cap.isOpened():
|
||||
cap.release()
|
||||
return False
|
||||
for _ in range(warmup):
|
||||
cap.read()
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
if not ret or frame is None:
|
||||
return False
|
||||
return bool(np.mean(frame) > 8)
|
||||
|
||||
|
||||
def _detect_camera_index() -> int:
|
||||
|
||||
backend = _cv2_backend()
|
||||
print("[Vision] 🔍 Auto-detecting camera...")
|
||||
for idx in range(6):
|
||||
if _probe_camera(idx, backend):
|
||||
print(f"[Vision] ✅ Camera found at index {idx}")
|
||||
_save_config_key("camera_index", idx)
|
||||
return idx
|
||||
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
||||
|
||||
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
||||
_save_config_key("camera_index", 0)
|
||||
return 0
|
||||
|
||||
|
||||
def _get_camera_index() -> int:
|
||||
cfg = _load_config()
|
||||
if "camera_index" in cfg:
|
||||
return int(cfg["camera_index"])
|
||||
return _detect_camera_index()
|
||||
|
||||
|
||||
def _capture_camera() -> tuple[bytes, str]:
|
||||
if not _CV2:
|
||||
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
||||
|
||||
index = _get_camera_index()
|
||||
backend = _cv2_backend()
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
|
||||
if not cap.isOpened():
|
||||
raise RuntimeError(f"Camera index {index} could not be opened.")
|
||||
|
||||
for _ in range(10):
|
||||
cap.read()
|
||||
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
|
||||
if not ret or frame is None:
|
||||
raise RuntimeError("Camera returned no frame.")
|
||||
|
||||
if _PIL:
|
||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
img = PIL.Image.fromarray(rgb)
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
|
||||
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
||||
return buf.tobytes(), "image/jpeg"
|
||||
|
||||
class _VisionSession:
|
||||
def __init__(self):
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._session = None
|
||||
self._out_queue: Optional[asyncio.Queue] = None
|
||||
self._audio_in: Optional[asyncio.Queue] = None
|
||||
self._ready_evt: threading.Event = threading.Event()
|
||||
self._player = None
|
||||
self._lock: threading.Lock = threading.Lock()
|
||||
|
||||
def start(self, player=None, timeout: float = 25.0) -> None:
|
||||
with self._lock:
|
||||
if self._thread and self._thread.is_alive():
|
||||
if player is not None:
|
||||
self._player = player
|
||||
return
|
||||
self._player = player
|
||||
self._thread = threading.Thread(
|
||||
target=self._run_event_loop,
|
||||
daemon=True,
|
||||
name="VisionSessionThread",
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
if not self._ready_evt.wait(timeout=timeout):
|
||||
raise RuntimeError(f"Vision session did not connect within {timeout}s.")
|
||||
print("[Vision] ✅ Session ready")
|
||||
|
||||
def analyze(self, image_bytes: bytes, mime_type: str, user_text: str) -> None:
|
||||
if not self._loop or not self._out_queue:
|
||||
print("[Vision] ⚠️ Session not started — dropping request")
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self._out_queue.put((image_bytes, mime_type, user_text)),
|
||||
self._loop,
|
||||
)
|
||||
|
||||
def is_ready(self) -> bool:
|
||||
return self._session is not None
|
||||
|
||||
def _run_event_loop(self) -> None:
|
||||
self._loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._loop.run_until_complete(self._session_loop())
|
||||
|
||||
async def _session_loop(self) -> None:
|
||||
self._out_queue = asyncio.Queue(maxsize=30)
|
||||
self._audio_in = asyncio.Queue()
|
||||
|
||||
client = genai.Client(
|
||||
api_key=_get_api_key(),
|
||||
http_options={"api_version": "v1beta"},
|
||||
)
|
||||
config = gtypes.LiveConnectConfig(
|
||||
response_modalities=["AUDIO"],
|
||||
output_audio_transcription={},
|
||||
system_instruction=_SYSTEM_PROMPT,
|
||||
speech_config=gtypes.SpeechConfig(
|
||||
voice_config=gtypes.VoiceConfig(
|
||||
prebuilt_voice_config=gtypes.PrebuiltVoiceConfig(
|
||||
voice_name="Charon"
|
||||
)
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
backoff = 2.0
|
||||
while True:
|
||||
try:
|
||||
print("[Vision] 🔌 Connecting...")
|
||||
async with client.aio.live.connect(
|
||||
model=_LIVE_MODEL, config=config
|
||||
) as session:
|
||||
self._session = session
|
||||
self._ready_evt.set()
|
||||
backoff = 2.0
|
||||
print("[Vision] ✅ Connected")
|
||||
|
||||
async with asyncio.TaskGroup() as tg:
|
||||
tg.create_task(self._send_loop())
|
||||
tg.create_task(self._recv_loop())
|
||||
tg.create_task(self._play_loop())
|
||||
|
||||
except* Exception as eg:
|
||||
for exc in eg.exceptions:
|
||||
print(f"[Vision] ⚠️ Session error: {exc}")
|
||||
finally:
|
||||
self._session = None
|
||||
self._ready_evt.clear()
|
||||
|
||||
print(f"[Vision] 🔄 Reconnecting in {backoff:.0f}s...")
|
||||
await asyncio.sleep(backoff)
|
||||
backoff = min(backoff * 1.5, 30.0)
|
||||
self._ready_evt.set()
|
||||
|
||||
async def _send_loop(self) -> None:
|
||||
while True:
|
||||
image_bytes, mime_type, user_text = await self._out_queue.get()
|
||||
if not self._session:
|
||||
print("[Vision] ⚠️ No session — dropping image")
|
||||
continue
|
||||
try:
|
||||
b64 = base64.b64encode(image_bytes).decode("ascii")
|
||||
await self._session.send_client_content(
|
||||
turns={
|
||||
"parts": [
|
||||
{"inline_data": {"mime_type": mime_type, "data": b64}},
|
||||
{"text": user_text},
|
||||
]
|
||||
},
|
||||
turn_complete=True,
|
||||
)
|
||||
print(f"[Vision] 📤 Sent {len(image_bytes):,} bytes — '{user_text[:60]}'")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Send error: {e}")
|
||||
|
||||
async def _recv_loop(self) -> None:
|
||||
transcript: list[str] = []
|
||||
try:
|
||||
async for response in self._session.receive():
|
||||
if response.data:
|
||||
await self._audio_in.put(response.data)
|
||||
|
||||
sc = response.server_content
|
||||
if not sc:
|
||||
continue
|
||||
|
||||
if sc.output_transcription and sc.output_transcription.text:
|
||||
chunk = sc.output_transcription.text.strip()
|
||||
if chunk:
|
||||
transcript.append(chunk)
|
||||
|
||||
if sc.turn_complete:
|
||||
if transcript and self._player:
|
||||
full = re.sub(r"\s+", " ", " ".join(transcript)).strip()
|
||||
if full:
|
||||
self._player.write_log(f"Jarvis: {full}")
|
||||
print(f"[Vision] 💬 {full}")
|
||||
transcript = []
|
||||
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Recv error: {e}")
|
||||
raise
|
||||
|
||||
async def _play_loop(self) -> None:
|
||||
stream = sd.RawOutputStream(
|
||||
samplerate=_RECEIVE_SAMPLE_RATE,
|
||||
channels=_CHANNELS,
|
||||
dtype="int16",
|
||||
blocksize=_CHUNK_SIZE,
|
||||
)
|
||||
stream.start()
|
||||
try:
|
||||
while True:
|
||||
chunk = await self._audio_in.get()
|
||||
await asyncio.to_thread(stream.write, chunk)
|
||||
except Exception as e:
|
||||
print(f"[Vision] ❌ Play error: {e}")
|
||||
raise
|
||||
finally:
|
||||
stream.stop()
|
||||
stream.close()
|
||||
|
||||
_session = _VisionSession()
|
||||
_session_lock = threading.Lock()
|
||||
_session_up = False
|
||||
|
||||
|
||||
def _ensure_session(player=None) -> None:
|
||||
global _session_up
|
||||
with _session_lock:
|
||||
if not _session_up:
|
||||
_session.start(player=player)
|
||||
_session_up = True
|
||||
elif player is not None:
|
||||
_session._player = player
|
||||
|
||||
|
||||
def screen_process(
|
||||
parameters: dict,
|
||||
response=None,
|
||||
player=None,
|
||||
session_memory=None,
|
||||
) -> bool:
|
||||
|
||||
params = parameters or {}
|
||||
user_text = (params.get("text") or params.get("user_text") or "").strip()
|
||||
angle = params.get("angle", "screen").lower().strip()
|
||||
|
||||
if not user_text:
|
||||
print("[Vision] ⚠️ No question provided — aborting")
|
||||
return False
|
||||
|
||||
print(f"[Vision] ▶ angle={angle!r} question='{user_text[:80]}'")
|
||||
|
||||
try:
|
||||
_ensure_session(player=player)
|
||||
except Exception as e:
|
||||
print(f"[Vision] ❌ Could not start session: {e}")
|
||||
return False
|
||||
|
||||
try:
|
||||
if angle == "camera":
|
||||
image_bytes, mime_type = _capture_camera()
|
||||
print(f"[Vision] 📷 Camera: {len(image_bytes):,} bytes")
|
||||
else:
|
||||
image_bytes, mime_type = _capture_screen()
|
||||
print(f"[Vision] 🖥️ Screen: {len(image_bytes):,} bytes")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ❌ Capture error: {e}")
|
||||
return False
|
||||
|
||||
_session.analyze(image_bytes, mime_type, user_text)
|
||||
return True
|
||||
|
||||
|
||||
def warmup_session(player=None) -> None:
|
||||
try:
|
||||
_ensure_session(player=player)
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Warmup failed: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("[TEST] screen_processor.py")
|
||||
print("=" * 52)
|
||||
mode = input("angle — screen / camera (default: screen): ").strip().lower() or "screen"
|
||||
q = input("Question (Enter = default): ").strip() or "What do you see? Be brief."
|
||||
|
||||
t0 = time.perf_counter()
|
||||
warmup_session()
|
||||
print(f"Session ready in {time.perf_counter()-t0:.2f}s\n")
|
||||
|
||||
t1 = time.perf_counter()
|
||||
ok = screen_process({"angle": mode, "text": q})
|
||||
print(f"Queued in {time.perf_counter()-t1:.3f}s — waiting for audio...")
|
||||
time.sleep(10)
|
||||
print("Done." if ok else "Failed.")
|
||||
"""
|
||||
MARK XL — Screen / Camera Processor
|
||||
Replaces Gemini Live vision session with a direct Ollama vision-model call.
|
||||
The analysis text is returned (and optionally spoken via the `speak` callback).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Optional, Callable
|
||||
|
||||
try:
|
||||
import cv2
|
||||
_CV2 = True
|
||||
except ImportError:
|
||||
_CV2 = False
|
||||
|
||||
try:
|
||||
import mss
|
||||
import mss.tools
|
||||
_MSS = True
|
||||
except ImportError:
|
||||
_MSS = False
|
||||
|
||||
try:
|
||||
import PIL.Image
|
||||
_PIL = True
|
||||
except ImportError:
|
||||
_PIL = False
|
||||
|
||||
import platform
|
||||
|
||||
import requests
|
||||
|
||||
|
||||
def _base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
_BASE = _base_dir()
|
||||
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
||||
|
||||
_IMG_MAX_W = 640
|
||||
_IMG_MAX_H = 360
|
||||
_JPEG_Q = 60
|
||||
|
||||
|
||||
def _load_config() -> dict:
|
||||
try:
|
||||
return json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_config_key(key: str, value) -> None:
|
||||
try:
|
||||
cfg = _load_config()
|
||||
cfg[key] = value
|
||||
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
||||
|
||||
|
||||
def _get_os() -> str:
|
||||
s = platform.system().lower()
|
||||
if s == "darwin": return "mac"
|
||||
if s == "windows": return "windows"
|
||||
return "linux"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Image capture helpers (unchanged from original)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
||||
if not _PIL:
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
try:
|
||||
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
|
||||
|
||||
def _capture_screen() -> tuple[bytes, str]:
|
||||
if not _MSS:
|
||||
raise RuntimeError("mss is not installed. Run: pip install mss")
|
||||
with mss.mss() as sct:
|
||||
monitors = sct.monitors
|
||||
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
||||
shot = sct.grab(target)
|
||||
png = mss.tools.to_png(shot.rgb, shot.size)
|
||||
return _compress(png, "PNG")
|
||||
|
||||
|
||||
def _cv2_backend() -> int:
|
||||
if not _CV2:
|
||||
return 0
|
||||
os_name = _get_os()
|
||||
if os_name == "windows":
|
||||
return cv2.CAP_DSHOW
|
||||
if os_name == "mac":
|
||||
return cv2.CAP_AVFOUNDATION
|
||||
return cv2.CAP_ANY
|
||||
|
||||
|
||||
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
||||
if not _CV2:
|
||||
return False
|
||||
import numpy as np
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
if not cap.isOpened():
|
||||
cap.release(); return False
|
||||
for _ in range(warmup):
|
||||
cap.read()
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
if not ret or frame is None:
|
||||
return False
|
||||
return bool(np.mean(frame) > 8)
|
||||
|
||||
|
||||
def _detect_camera_index() -> int:
|
||||
backend = _cv2_backend()
|
||||
print("[Vision] 🔍 Auto-detecting camera…")
|
||||
for idx in range(6):
|
||||
if _probe_camera(idx, backend):
|
||||
print(f"[Vision] ✅ Camera found at index {idx}")
|
||||
_save_config_key("camera_index", idx)
|
||||
return idx
|
||||
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
||||
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
||||
_save_config_key("camera_index", 0)
|
||||
return 0
|
||||
|
||||
|
||||
def _get_camera_index() -> int:
|
||||
cfg = _load_config()
|
||||
if "camera_index" in cfg:
|
||||
return int(cfg["camera_index"])
|
||||
return _detect_camera_index()
|
||||
|
||||
|
||||
def _capture_camera() -> tuple[bytes, str]:
|
||||
if not _CV2:
|
||||
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
||||
import numpy as np
|
||||
index = _get_camera_index()
|
||||
backend = _cv2_backend()
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
if not cap.isOpened():
|
||||
raise RuntimeError(f"Camera index {index} could not be opened.")
|
||||
for _ in range(10):
|
||||
cap.read()
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
if not ret or frame is None:
|
||||
raise RuntimeError("Camera returned no frame.")
|
||||
if _PIL:
|
||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
img = PIL.Image.fromarray(rgb)
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
||||
return buf.tobytes(), "image/jpeg"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Vision analysis via Ollama
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_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."
|
||||
)
|
||||
|
||||
|
||||
def _call_vision(image_bytes: bytes, mime: str, user_text: str) -> str:
|
||||
cfg = _load_config()
|
||||
url = cfg.get("llm_url", "http://localhost:11434").rstrip("/")
|
||||
vision_model = cfg.get("vision_model") or cfg.get("llm_model", "llava")
|
||||
|
||||
b64 = base64.b64encode(image_bytes).decode("ascii")
|
||||
|
||||
payload = {
|
||||
"model": vision_model,
|
||||
"stream": False,
|
||||
"messages": [
|
||||
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||
{
|
||||
"role": "user",
|
||||
"content": user_text,
|
||||
"images": [b64],
|
||||
},
|
||||
],
|
||||
}
|
||||
try:
|
||||
resp = requests.post(f"{url}/api/chat", json=payload, timeout=60)
|
||||
resp.raise_for_status()
|
||||
return (resp.json().get("message", {}).get("content") or "").strip()
|
||||
except requests.exceptions.ConnectionError:
|
||||
return "Cannot connect to Ollama. Make sure Ollama is running."
|
||||
except Exception as e:
|
||||
return f"Vision analysis failed: {e}"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Public entry point
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def screen_process(
|
||||
parameters: dict,
|
||||
response=None,
|
||||
player=None,
|
||||
session_memory=None,
|
||||
speak: Optional[Callable[[str], None]] = None,
|
||||
) -> str:
|
||||
"""
|
||||
Capture screen or camera, analyse with Ollama vision model.
|
||||
|
||||
Returns the analysis text (str).
|
||||
Optionally speaks via `speak` callback and logs to `player`.
|
||||
"""
|
||||
params = parameters or {}
|
||||
user_text = (params.get("text") or params.get("user_text") or "").strip()
|
||||
angle = params.get("angle", "screen").lower().strip()
|
||||
|
||||
if not user_text:
|
||||
user_text = "What do you see? Describe briefly."
|
||||
|
||||
if player:
|
||||
player.write_log(f"SYS: Vision [{angle}] — {user_text[:60]}")
|
||||
|
||||
# Capture
|
||||
try:
|
||||
if angle == "camera":
|
||||
image_bytes, mime = _capture_camera()
|
||||
print(f"[Vision] 📷 Camera: {len(image_bytes):,} bytes")
|
||||
else:
|
||||
image_bytes, mime = _capture_screen()
|
||||
print(f"[Vision] 🖥️ Screen: {len(image_bytes):,} bytes")
|
||||
except Exception as e:
|
||||
msg = f"Capture error: {e}"
|
||||
print(f"[Vision] ❌ {msg}")
|
||||
if player: player.write_log(f"ERR: {msg}")
|
||||
return msg
|
||||
|
||||
# Analyse
|
||||
analysis = _call_vision(image_bytes, mime, user_text)
|
||||
print(f"[Vision] 💬 {analysis[:120]}")
|
||||
|
||||
if player:
|
||||
player.write_log(f"Jarvis: {analysis}")
|
||||
|
||||
if speak and analysis:
|
||||
speak(analysis)
|
||||
|
||||
return analysis
|
||||
+117
-141
@@ -1,141 +1,117 @@
|
||||
#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
|
||||
# Gemini grounded-search replaced with DuckDuckGo + Ollama LLM summarization.
|
||||
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()
|
||||
|
||||
|
||||
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 _llm_summarize(query: str, raw_results: str) -> str:
|
||||
try:
|
||||
from core.llm_client import call_llm_text
|
||||
system = (
|
||||
"You are JARVIS. Summarize web search results clearly and concisely. "
|
||||
"Answer the user's query directly. Be factual. Address user as 'sir'."
|
||||
)
|
||||
prompt = (
|
||||
f"User question: {query}\n\n"
|
||||
f"Web search results:\n{raw_results[:4000]}\n\n"
|
||||
"Answer the question based on these results:"
|
||||
)
|
||||
return call_llm_text(prompt, system=system)
|
||||
except Exception:
|
||||
return raw_results
|
||||
|
||||
|
||||
def _compare(items: list[str], aspect: str) -> str:
|
||||
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']}")
|
||||
raw = "\n".join(lines)
|
||||
return _llm_summarize(f"Compare {', '.join(items)} regarding {aspect}", raw)
|
||||
|
||||
|
||||
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}")
|
||||
return _compare(items, aspect)
|
||||
|
||||
results = _ddg_search(query)
|
||||
raw = _format_ddg(query, results)
|
||||
print(f"[WebSearch] ✅ DDG: {len(results)} result(s).")
|
||||
# Let Ollama summarise the results for a cleaner spoken response
|
||||
return _llm_summarize(query, raw)
|
||||
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ❌ Failed: {e}")
|
||||
return f"Search failed, sir: {e}"
|
||||
+11
-22
@@ -48,11 +48,6 @@ HEADERS = {
|
||||
_YT_VIDEO_FILTER = "EgIQAQ%3D%3D"
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _open_url(url: str) -> None:
|
||||
try:
|
||||
if is_mac():
|
||||
@@ -158,26 +153,20 @@ def _get_transcript(video_id: str) -> str | None:
|
||||
|
||||
|
||||
def _summarize_with_gemini(transcript: str, video_url: str) -> str:
|
||||
import google.generativeai as genai
|
||||
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(
|
||||
model_name="gemini-2.5-flash",
|
||||
system_instruction=(
|
||||
"You are JARVIS, an AI assistant. "
|
||||
"Summarize YouTube video transcripts clearly and concisely. "
|
||||
"Structure: 1-sentence overview, then 3-5 key points. "
|
||||
"Be direct. Address the user as 'sir'. "
|
||||
"Match the language of the transcript."
|
||||
)
|
||||
from core.llm_client import call_llm_text
|
||||
system = (
|
||||
"You are JARVIS, an AI assistant. "
|
||||
"Summarize YouTube video transcripts clearly and concisely. "
|
||||
"Structure: 1-sentence overview, then 3-5 key points. "
|
||||
"Be direct. Address the user as 'sir'. "
|
||||
"Match the language of the transcript."
|
||||
)
|
||||
|
||||
max_chars = 80000
|
||||
max_chars = 12000
|
||||
truncated = transcript[:max_chars] + ("..." if len(transcript) > max_chars else "")
|
||||
response = model.generate_content(
|
||||
f"Please summarize this YouTube video transcript:\n\n{truncated}"
|
||||
return call_llm_text(
|
||||
f"Please summarize this YouTube video transcript:\n\n{truncated}",
|
||||
system=system,
|
||||
)
|
||||
return response.text.strip()
|
||||
|
||||
|
||||
def _save_summary(content: str, video_url: str) -> str:
|
||||
|
||||
+149
-197
@@ -1,197 +1,149 @@
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from enum import Enum
|
||||
|
||||
|
||||
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"
|
||||
|
||||
|
||||
class ErrorDecision(Enum):
|
||||
RETRY = "retry"
|
||||
SKIP = "skip"
|
||||
REPLAN = "replan"
|
||||
ABORT = "abort"
|
||||
|
||||
|
||||
ERROR_ANALYST_PROMPT = """You are the error recovery module of MARK XXV AI assistant.
|
||||
|
||||
A task step has failed. Analyze the error and decide what to do.
|
||||
|
||||
DECISIONS:
|
||||
- retry : Transient error (network timeout, temporary file lock, race condition).
|
||||
The same step can succeed if tried again.
|
||||
- skip : This step is not critical and the task can succeed without it.
|
||||
- replan : The approach was wrong. A different tool or method should be tried.
|
||||
- abort : The task is fundamentally impossible or unsafe to continue.
|
||||
|
||||
Also provide:
|
||||
- A brief explanation of WHY it failed (1 sentence)
|
||||
- A fix suggestion if decision is replan (what to try instead)
|
||||
- Max retries: how many times to retry if decision is retry (1 or 2)
|
||||
|
||||
Return ONLY valid JSON:
|
||||
{
|
||||
"decision": "retry|skip|replan|abort",
|
||||
"reason": "why it failed",
|
||||
"fix_suggestion": "what to try instead (for replan)",
|
||||
"max_retries": 1,
|
||||
"user_message": "Short message to tell the user (max 15 words)"
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def analyze_error(
|
||||
step: dict,
|
||||
error: str,
|
||||
attempt: int = 1,
|
||||
max_attempts: int = 2
|
||||
) -> dict:
|
||||
"""
|
||||
Analyzes a failed step and returns a recovery decision.
|
||||
|
||||
Args:
|
||||
step : The step dict that failed
|
||||
error : Error message/traceback
|
||||
attempt : Current attempt number
|
||||
max_attempts : How many times we've already tried
|
||||
|
||||
Returns:
|
||||
{
|
||||
"decision": ErrorDecision,
|
||||
"reason": str,
|
||||
"fix_suggestion": str,
|
||||
"max_retries": int,
|
||||
"user_message": str
|
||||
}
|
||||
"""
|
||||
import google.generativeai as genai
|
||||
|
||||
if attempt >= max_attempts:
|
||||
print(f"[ErrorHandler] ⚠️ Max attempts reached for step {step.get('step')} — forcing replan")
|
||||
return {
|
||||
"decision": ErrorDecision.REPLAN,
|
||||
"reason": f"Failed {attempt} times: {error[:100]}",
|
||||
"fix_suggestion": "Try a completely different approach or tool",
|
||||
"max_retries": 0,
|
||||
"user_message": "Trying a different approach, sir."
|
||||
}
|
||||
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(
|
||||
model_name="gemini-2.5-flash-lite",
|
||||
system_instruction=ERROR_ANALYST_PROMPT
|
||||
)
|
||||
|
||||
prompt = f"""Failed step:
|
||||
Tool: {step.get('tool')}
|
||||
Description: {step.get('description')}
|
||||
Parameters: {json.dumps(step.get('parameters', {}), indent=2)}
|
||||
Critical: {step.get('critical', False)}
|
||||
|
||||
Error:
|
||||
{error[:500]}
|
||||
|
||||
Attempt number: {attempt}"""
|
||||
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
text = response.text.strip()
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
|
||||
result = json.loads(text)
|
||||
decision_str = result.get("decision", "replan").lower()
|
||||
decision_map = {
|
||||
"retry": ErrorDecision.RETRY,
|
||||
"skip": ErrorDecision.SKIP,
|
||||
"replan": ErrorDecision.REPLAN,
|
||||
"abort": ErrorDecision.ABORT,
|
||||
}
|
||||
result["decision"] = decision_map.get(decision_str, ErrorDecision.REPLAN)
|
||||
|
||||
|
||||
if step.get("critical") and result["decision"] == ErrorDecision.SKIP:
|
||||
result["decision"] = ErrorDecision.REPLAN
|
||||
result["user_message"] = "This step is critical — finding alternative approach, sir."
|
||||
|
||||
print(f"[ErrorHandler] Decision: {result['decision'].value} — {result.get('reason', '')}")
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ErrorHandler] ⚠️ Analysis failed: {e} — defaulting to replan")
|
||||
return {
|
||||
"decision": ErrorDecision.REPLAN,
|
||||
"reason": str(e),
|
||||
"fix_suggestion": "Try alternative approach",
|
||||
"max_retries": 1,
|
||||
"user_message": "Encountered an issue, adjusting approach, sir."
|
||||
}
|
||||
|
||||
|
||||
def generate_fix(step: dict, error: str, fix_suggestion: str) -> dict:
|
||||
"""
|
||||
When decision is REPLAN and a fix suggestion exists,
|
||||
generates a replacement step using generated_code as fallback.
|
||||
|
||||
Returns a modified step dict.
|
||||
"""
|
||||
import google.generativeai as genai
|
||||
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(model_name="gemini-2.0-flash")
|
||||
|
||||
prompt = f"""A task step failed. Generate a replacement step.
|
||||
|
||||
Original step:
|
||||
Tool: {step.get('tool')}
|
||||
Description: {step.get('description')}
|
||||
Parameters: {json.dumps(step.get('parameters', {}), indent=2)}
|
||||
|
||||
Error: {error[:300]}
|
||||
Fix suggestion: {fix_suggestion}
|
||||
|
||||
Write a Python script that accomplishes the same goal differently.
|
||||
Return ONLY the Python code, no explanation."""
|
||||
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
code = response.text.strip()
|
||||
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||
|
||||
return {
|
||||
"step": step.get("step"),
|
||||
"tool": "code_helper",
|
||||
"description": f"Auto-fix for: {step.get('description')}",
|
||||
"parameters": {
|
||||
"action": "run",
|
||||
"description": fix_suggestion,
|
||||
"code": code,
|
||||
"language": "python"
|
||||
},
|
||||
"depends_on": step.get("depends_on", []),
|
||||
"critical": step.get("critical", False)
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ErrorHandler] ⚠️ Fix generation failed: {e}")
|
||||
return {
|
||||
"step": step.get("step"),
|
||||
"tool": "generated_code",
|
||||
"description": f"Fallback for: {step.get('description')}",
|
||||
"parameters": {"description": step.get("description", "")},
|
||||
"depends_on": step.get("depends_on", []),
|
||||
"critical": step.get("critical", False)
|
||||
}
|
||||
"""
|
||||
MARK XL — Error Handler
|
||||
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from enum import Enum
|
||||
from pathlib import Path
|
||||
|
||||
from core.llm_client import call_llm_text
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
class ErrorDecision(Enum):
|
||||
RETRY = "retry"
|
||||
SKIP = "skip"
|
||||
REPLAN = "replan"
|
||||
ABORT = "abort"
|
||||
|
||||
|
||||
ERROR_ANALYST_PROMPT = """You are the error recovery module of MARK XL AI assistant.
|
||||
|
||||
A task step has failed. Analyze the error and decide what to do.
|
||||
|
||||
DECISIONS:
|
||||
- retry : Transient error (network timeout, temporary file lock, race condition).
|
||||
- skip : This step is not critical and the task can succeed without it.
|
||||
- replan : The approach was wrong. A different tool or method should be tried.
|
||||
- abort : The task is fundamentally impossible or unsafe to continue.
|
||||
|
||||
Return ONLY valid JSON:
|
||||
{
|
||||
"decision": "retry|skip|replan|abort",
|
||||
"reason": "why it failed",
|
||||
"fix_suggestion": "what to try instead (for replan)",
|
||||
"max_retries": 1,
|
||||
"user_message": "Short message to tell the user (max 15 words)"
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def analyze_error(
|
||||
step: dict,
|
||||
error: str,
|
||||
attempt: int = 1,
|
||||
max_attempts: int = 2,
|
||||
) -> dict:
|
||||
if attempt >= max_attempts:
|
||||
print(f"[ErrorHandler] ⚠️ Max attempts for step {step.get('step')} — forcing replan")
|
||||
return {
|
||||
"decision": ErrorDecision.REPLAN,
|
||||
"reason": f"Failed {attempt} times: {error[:100]}",
|
||||
"fix_suggestion": "Try a completely different approach or tool",
|
||||
"max_retries": 0,
|
||||
"user_message": "Trying a different approach, sir.",
|
||||
}
|
||||
|
||||
prompt = f"""Failed step:
|
||||
Tool: {step.get('tool')}
|
||||
Description: {step.get('description')}
|
||||
Parameters: {json.dumps(step.get('parameters', {}), indent=2)}
|
||||
Critical: {step.get('critical', False)}
|
||||
|
||||
Error:
|
||||
{error[:500]}
|
||||
|
||||
Attempt number: {attempt}"""
|
||||
|
||||
try:
|
||||
text = call_llm_text(prompt, system=ERROR_ANALYST_PROMPT)
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
result = json.loads(text)
|
||||
|
||||
decision_str = result.get("decision", "replan").lower()
|
||||
decision_map = {
|
||||
"retry": ErrorDecision.RETRY,
|
||||
"skip": ErrorDecision.SKIP,
|
||||
"replan": ErrorDecision.REPLAN,
|
||||
"abort": ErrorDecision.ABORT,
|
||||
}
|
||||
result["decision"] = decision_map.get(decision_str, ErrorDecision.REPLAN)
|
||||
|
||||
if step.get("critical") and result["decision"] == ErrorDecision.SKIP:
|
||||
result["decision"] = ErrorDecision.REPLAN
|
||||
result["user_message"] = "This step is critical — finding alternative approach, sir."
|
||||
|
||||
print(f"[ErrorHandler] Decision: {result['decision'].value} — {result.get('reason', '')}")
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ErrorHandler] ⚠️ Analysis failed: {e} — defaulting to replan")
|
||||
return {
|
||||
"decision": ErrorDecision.REPLAN,
|
||||
"reason": str(e),
|
||||
"fix_suggestion": "Try alternative approach",
|
||||
"max_retries": 1,
|
||||
"user_message": "Encountered an issue, adjusting approach, sir.",
|
||||
}
|
||||
|
||||
|
||||
def generate_fix(step: dict, error: str, fix_suggestion: str) -> dict:
|
||||
prompt = f"""A task step failed. Generate a replacement step.
|
||||
|
||||
Original step:
|
||||
Tool: {step.get('tool')}
|
||||
Description: {step.get('description')}
|
||||
Parameters: {json.dumps(step.get('parameters', {}), indent=2)}
|
||||
|
||||
Error: {error[:300]}
|
||||
Fix suggestion: {fix_suggestion}
|
||||
|
||||
Write a Python script that accomplishes the same goal differently.
|
||||
Return ONLY the Python code, no explanation."""
|
||||
|
||||
try:
|
||||
code = call_llm_text(prompt)
|
||||
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||
return {
|
||||
"step": step.get("step"),
|
||||
"tool": "code_helper",
|
||||
"description": f"Auto-fix for: {step.get('description')}",
|
||||
"parameters": {
|
||||
"action": "run",
|
||||
"description": fix_suggestion,
|
||||
"code": code,
|
||||
"language": "python",
|
||||
},
|
||||
"depends_on": step.get("depends_on", []),
|
||||
"critical": step.get("critical", False),
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"[ErrorHandler] ⚠️ Fix generation failed: {e}")
|
||||
return {
|
||||
"step": step.get("step"),
|
||||
"tool": "generated_code",
|
||||
"description": f"Fallback for: {step.get('description')}",
|
||||
"parameters": {"description": step.get("description", "")},
|
||||
"depends_on": step.get("depends_on", []),
|
||||
"critical": step.get("critical", False),
|
||||
}
|
||||
+394
-396
@@ -1,396 +1,394 @@
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import subprocess
|
||||
import tempfile
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from agent.planner import create_plan, replan
|
||||
from agent.error_handler import analyze_error, generate_fix, ErrorDecision
|
||||
|
||||
|
||||
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 _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
||||
import google.generativeai as genai
|
||||
|
||||
if speak:
|
||||
speak("Writing custom code for this task, sir.")
|
||||
|
||||
home = Path.home()
|
||||
desktop = home / "Desktop"
|
||||
downloads = home / "Downloads"
|
||||
documents = home / "Documents"
|
||||
|
||||
if not desktop.exists():
|
||||
try:
|
||||
import winreg
|
||||
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
|
||||
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
|
||||
desktop = Path(winreg.QueryValueEx(key, "Desktop")[0])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(
|
||||
model_name="gemini-2.5-flash",
|
||||
system_instruction=(
|
||||
"You are an expert Python developer. "
|
||||
"Write clean, complete, working Python code. "
|
||||
"Use standard library + common packages. "
|
||||
"Install missing packages with subprocess + pip if needed. "
|
||||
"Return ONLY the Python code. No explanation, no markdown, no backticks.\n\n"
|
||||
f"SYSTEM PATHS:\n"
|
||||
f" Desktop = r'{desktop}'\n"
|
||||
f" Downloads = r'{downloads}'\n"
|
||||
f" Documents = r'{documents}'\n"
|
||||
f" Home = r'{home}'\n"
|
||||
)
|
||||
)
|
||||
|
||||
try:
|
||||
response = model.generate_content(
|
||||
f"Write Python code to accomplish this task:\n\n{description}"
|
||||
)
|
||||
code = response.text.strip()
|
||||
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w", suffix=".py", delete=False, encoding="utf-8"
|
||||
) as f:
|
||||
f.write(code)
|
||||
tmp_path = f.name
|
||||
|
||||
print(f"[Executor] 🐍 Running generated code: {tmp_path}")
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, tmp_path],
|
||||
capture_output=True, text=True,
|
||||
timeout=120, cwd=str(Path.home())
|
||||
)
|
||||
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
output = result.stdout.strip()
|
||||
error = result.stderr.strip()
|
||||
|
||||
if result.returncode == 0 and output:
|
||||
return output
|
||||
elif result.returncode == 0:
|
||||
return "Task completed successfully."
|
||||
elif error:
|
||||
raise RuntimeError(f"Code error: {error[:400]}")
|
||||
return "Completed."
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
raise RuntimeError("Generated code timed out after 120 seconds.")
|
||||
except RuntimeError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Generated code failed: {e}")
|
||||
|
||||
def _inject_context(params: dict, tool: str, step_results: dict, goal: str = "") -> dict:
|
||||
if not step_results:
|
||||
return params
|
||||
|
||||
params = dict(params)
|
||||
|
||||
if tool == "file_controller" and params.get("action") in ("write", "create_file"):
|
||||
content = params.get("content", "")
|
||||
if not content or len(content) < 50:
|
||||
all_results = [
|
||||
v for v in step_results.values()
|
||||
if v and len(v) > 100 and v not in ("Done.", "Completed.")
|
||||
]
|
||||
if all_results:
|
||||
combined = "\n\n---\n\n".join(all_results)
|
||||
translated = _translate_to_goal_language(combined, goal)
|
||||
params["content"] = translated
|
||||
print(f"[Executor] 💉 Injected + translated content")
|
||||
|
||||
return params
|
||||
def _detect_language(text: str) -> str:
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel("gemini-2.5-flash-lite")
|
||||
try:
|
||||
response = model.generate_content(
|
||||
f"What language is this text written in? "
|
||||
f"Reply with ONLY the language name in English (e.g. Turkish, English, French).\n\n"
|
||||
f"Text: {text[:200]}"
|
||||
)
|
||||
return response.text.strip()
|
||||
except Exception:
|
||||
return "English"
|
||||
|
||||
|
||||
def _translate_to_goal_language(content: str, goal: str) -> str:
|
||||
if not goal:
|
||||
return content
|
||||
try:
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel("gemini-2.5-flash")
|
||||
|
||||
target_lang = _detect_language(goal)
|
||||
print(f"[Executor] 🌐 Translating to: {target_lang}")
|
||||
|
||||
prompt = (
|
||||
f"You are a professional translator. "
|
||||
f"Translate the following text into {target_lang}.\n"
|
||||
f"IMPORTANT:\n"
|
||||
f"- Translate EVERYTHING, leave nothing in English\n"
|
||||
f"- Keep all facts, numbers, and data intact\n"
|
||||
f"- Keep the structure and formatting\n"
|
||||
f"- Output ONLY the translated text, nothing else\n\n"
|
||||
f"Text to translate:\n{content[:4000]}"
|
||||
)
|
||||
response = model.generate_content(prompt)
|
||||
translated = response.text.strip()
|
||||
print(f"[Executor] ✅ Translation done ({target_lang})")
|
||||
return translated
|
||||
except Exception as e:
|
||||
print(f"[Executor] ⚠️ Translation failed: {e}")
|
||||
return content
|
||||
|
||||
def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
||||
|
||||
if tool == "open_app":
|
||||
from actions.open_app import open_app
|
||||
return open_app(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "web_search":
|
||||
from actions.web_search import web_search
|
||||
return web_search(parameters=parameters, player=None) or "Done."
|
||||
elif tool == "game_updater":
|
||||
from actions.game_updater import game_updater
|
||||
return game_updater(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
elif tool == "browser_control":
|
||||
from actions.browser_control import browser_control
|
||||
return browser_control(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "file_controller":
|
||||
from actions.file_controller import file_controller
|
||||
return file_controller(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "code_helper":
|
||||
from actions.code_helper import code_helper
|
||||
return code_helper(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
|
||||
elif tool == "dev_agent":
|
||||
from actions.dev_agent import dev_agent
|
||||
return dev_agent(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
|
||||
elif tool == "screen_process":
|
||||
from actions.screen_processor import screen_process
|
||||
screen_process(parameters=parameters, player=None)
|
||||
return "Screen captured and analyzed."
|
||||
|
||||
elif tool == "send_message":
|
||||
from actions.send_message import send_message
|
||||
return send_message(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "reminder":
|
||||
from actions.reminder import reminder
|
||||
return reminder(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "youtube_video":
|
||||
from actions.youtube_video import youtube_video
|
||||
return youtube_video(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "weather_report":
|
||||
from actions.weather_report import weather_action
|
||||
return weather_action(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "computer_settings":
|
||||
from actions.computer_settings import computer_settings
|
||||
return computer_settings(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "desktop_control":
|
||||
from actions.desktop import desktop_control
|
||||
return desktop_control(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "computer_control":
|
||||
from actions.computer_control import computer_control
|
||||
return computer_control(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "generated_code":
|
||||
description = parameters.get("description", "")
|
||||
if not description:
|
||||
raise ValueError("generated_code requires a 'description' parameter.")
|
||||
return _run_generated_code(description, speak=speak)
|
||||
|
||||
elif tool == "flight_finder":
|
||||
from actions.flight_finder import flight_finder
|
||||
return flight_finder(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
|
||||
else:
|
||||
print(f"[Executor] ⚠️ Unknown tool '{tool}' — falling back to generated_code")
|
||||
return _run_generated_code(f"Accomplish this task: {parameters}", speak=speak)
|
||||
|
||||
class AgentExecutor:
|
||||
|
||||
MAX_REPLAN_ATTEMPTS = 2
|
||||
|
||||
def execute(
|
||||
self,
|
||||
goal: str,
|
||||
speak: Callable | None = None,
|
||||
cancel_flag: threading.Event | None = None,
|
||||
) -> str:
|
||||
print(f"\n[Executor] 🎯 Goal: {goal}")
|
||||
|
||||
replan_attempts = 0
|
||||
completed_steps = []
|
||||
step_results = {}
|
||||
plan = create_plan(goal)
|
||||
|
||||
while True:
|
||||
steps = plan.get("steps", [])
|
||||
|
||||
if not steps:
|
||||
msg = "I couldn't create a valid plan for this task, sir."
|
||||
if speak: speak(msg)
|
||||
return msg
|
||||
|
||||
success = True
|
||||
failed_step = None
|
||||
failed_error = ""
|
||||
|
||||
for step in steps:
|
||||
if cancel_flag and cancel_flag.is_set():
|
||||
if speak: speak("Task cancelled, sir.")
|
||||
return "Task cancelled."
|
||||
|
||||
step_num = step.get("step", "?")
|
||||
tool = step.get("tool", "generated_code")
|
||||
desc = step.get("description", "")
|
||||
params = step.get("parameters", {})
|
||||
|
||||
params = _inject_context(params, tool, step_results, goal=goal)
|
||||
|
||||
print(f"\n[Executor] ▶️ Step {step_num}: [{tool}] {desc}")
|
||||
|
||||
attempt = 1
|
||||
step_ok = False
|
||||
|
||||
while attempt <= 3:
|
||||
if cancel_flag and cancel_flag.is_set():
|
||||
break
|
||||
try:
|
||||
result = _call_tool(tool, params, speak)
|
||||
step_results[step_num] = result
|
||||
completed_steps.append(step)
|
||||
print(f"[Executor] ✅ Step {step_num} done: {str(result)[:100]}")
|
||||
step_ok = True
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
print(f"[Executor] ❌ Step {step_num} attempt {attempt} failed: {error_msg}")
|
||||
|
||||
recovery = analyze_error(step, error_msg, attempt=attempt)
|
||||
decision = recovery["decision"]
|
||||
user_msg = recovery.get("user_message", "")
|
||||
|
||||
if speak and user_msg:
|
||||
speak(user_msg)
|
||||
|
||||
if decision == ErrorDecision.RETRY:
|
||||
attempt += 1
|
||||
import time; time.sleep(2)
|
||||
continue
|
||||
|
||||
elif decision == ErrorDecision.SKIP:
|
||||
print(f"[Executor] ⏭️ Skipping step {step_num}")
|
||||
completed_steps.append(step)
|
||||
step_ok = True
|
||||
break
|
||||
|
||||
elif decision == ErrorDecision.ABORT:
|
||||
msg = f"Task aborted, sir. {recovery.get('reason', '')}"
|
||||
if speak: speak(msg)
|
||||
return msg
|
||||
|
||||
else:
|
||||
fix_suggestion = recovery.get("fix_suggestion", "")
|
||||
if fix_suggestion and tool != "generated_code":
|
||||
try:
|
||||
fixed_step = generate_fix(step, error_msg, fix_suggestion)
|
||||
if speak: speak("Trying an alternative approach, sir.")
|
||||
res = _call_tool(
|
||||
fixed_step["tool"],
|
||||
fixed_step["parameters"],
|
||||
speak
|
||||
)
|
||||
step_results[step_num] = res
|
||||
completed_steps.append(step)
|
||||
step_ok = True
|
||||
break
|
||||
except Exception as fix_err:
|
||||
print(f"[Executor] ⚠️ Fix failed: {fix_err}")
|
||||
|
||||
failed_step = step
|
||||
failed_error = error_msg
|
||||
success = False
|
||||
break
|
||||
|
||||
if not step_ok and not failed_step:
|
||||
failed_step = step
|
||||
failed_error = "Max retries exceeded"
|
||||
success = False
|
||||
|
||||
if not success:
|
||||
break
|
||||
|
||||
if success:
|
||||
return self._summarize(goal, completed_steps, speak)
|
||||
|
||||
if replan_attempts >= self.MAX_REPLAN_ATTEMPTS:
|
||||
msg = f"Task failed after {replan_attempts} replan attempts, sir."
|
||||
if speak: speak(msg)
|
||||
return msg
|
||||
|
||||
if speak: speak("Adjusting my approach, sir.")
|
||||
|
||||
replan_attempts += 1
|
||||
plan = replan(goal, completed_steps, failed_step, failed_error)
|
||||
|
||||
def _summarize(self, goal: str, completed_steps: list, speak: Callable | None) -> str:
|
||||
fallback = f"All done, sir. Completed {len(completed_steps)} steps for: {goal[:60]}."
|
||||
try:
|
||||
import google.generativeai as genai
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(model_name="gemini-2.5-flash-lite")
|
||||
steps_str = "\n".join(f"- {s.get('description', '')}" for s in completed_steps)
|
||||
prompt = (
|
||||
f'User goal: "{goal}"\n'
|
||||
f"Completed steps:\n{steps_str}\n\n"
|
||||
"Write a single natural sentence summarizing what was accomplished. "
|
||||
"Address the user as 'sir'. Be direct and positive."
|
||||
)
|
||||
response = model.generate_content(prompt)
|
||||
summary = response.text.strip()
|
||||
if speak: speak(summary)
|
||||
return summary
|
||||
except Exception:
|
||||
if speak: speak(fallback)
|
||||
return fallback
|
||||
"""
|
||||
MARK XL — Agent Executor
|
||||
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import subprocess
|
||||
import tempfile
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
from agent.planner import create_plan, replan
|
||||
from agent.error_handler import analyze_error, generate_fix, ErrorDecision
|
||||
from core.llm_client import call_llm_text
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Code generation helper (replaces _run_generated_code with Gemini)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
||||
if speak:
|
||||
speak("Writing custom code for this task, sir.")
|
||||
|
||||
home = Path.home()
|
||||
desktop = home / "Desktop"
|
||||
downloads = home / "Downloads"
|
||||
documents = home / "Documents"
|
||||
|
||||
if not desktop.exists():
|
||||
try:
|
||||
import winreg
|
||||
key = winreg.OpenKey(
|
||||
winreg.HKEY_CURRENT_USER,
|
||||
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders",
|
||||
)
|
||||
desktop = Path(winreg.QueryValueEx(key, "Desktop")[0])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
system = (
|
||||
"You are an expert Python developer. "
|
||||
"Write clean, complete, working Python code. "
|
||||
"Use standard library + common packages. "
|
||||
"Install missing packages with subprocess + pip if needed. "
|
||||
"Return ONLY the Python code. No explanation, no markdown, no backticks.\n\n"
|
||||
f"SYSTEM PATHS:\n"
|
||||
f" Desktop = r'{desktop}'\n"
|
||||
f" Downloads = r'{downloads}'\n"
|
||||
f" Documents = r'{documents}'\n"
|
||||
f" Home = r'{home}'\n"
|
||||
)
|
||||
prompt = f"Write Python code to accomplish this task:\n\n{description}"
|
||||
|
||||
try:
|
||||
code = call_llm_text(prompt, system=system)
|
||||
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||
|
||||
with tempfile.NamedTemporaryFile(
|
||||
mode="w", suffix=".py", delete=False, encoding="utf-8"
|
||||
) as f:
|
||||
f.write(code)
|
||||
tmp_path = f.name
|
||||
|
||||
print(f"[Executor] 🐍 Running generated code: {tmp_path}")
|
||||
|
||||
result = subprocess.run(
|
||||
[sys.executable, tmp_path],
|
||||
capture_output=True, text=True,
|
||||
timeout=120, cwd=str(Path.home()),
|
||||
)
|
||||
|
||||
try:
|
||||
os.unlink(tmp_path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
output = result.stdout.strip()
|
||||
error = result.stderr.strip()
|
||||
|
||||
if result.returncode == 0 and output:
|
||||
return output
|
||||
elif result.returncode == 0:
|
||||
return "Task completed successfully."
|
||||
elif error:
|
||||
raise RuntimeError(f"Code error: {error[:400]}")
|
||||
return "Completed."
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
raise RuntimeError("Generated code timed out after 120 seconds.")
|
||||
except RuntimeError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Generated code failed: {e}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Context injection
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _detect_language(text: str) -> str:
|
||||
try:
|
||||
return call_llm_text(
|
||||
f"What language is this text written in? "
|
||||
f"Reply with ONLY the language name in English (e.g. Turkish, English, French).\n\n"
|
||||
f"Text: {text[:200]}"
|
||||
).strip()
|
||||
except Exception:
|
||||
return "English"
|
||||
|
||||
|
||||
def _translate_to_goal_language(content: str, goal: str) -> str:
|
||||
if not goal:
|
||||
return content
|
||||
try:
|
||||
target_lang = _detect_language(goal)
|
||||
print(f"[Executor] 🌐 Translating to: {target_lang}")
|
||||
prompt = (
|
||||
f"You are a professional translator. "
|
||||
f"Translate the following text into {target_lang}.\n"
|
||||
f"IMPORTANT:\n"
|
||||
f"- Translate EVERYTHING, leave nothing in English\n"
|
||||
f"- Keep all facts, numbers, and data intact\n"
|
||||
f"- Keep the structure and formatting\n"
|
||||
f"- Output ONLY the translated text, nothing else\n\n"
|
||||
f"Text to translate:\n{content[:4000]}"
|
||||
)
|
||||
translated = call_llm_text(prompt)
|
||||
print(f"[Executor] ✅ Translation done ({target_lang})")
|
||||
return translated
|
||||
except Exception as e:
|
||||
print(f"[Executor] ⚠️ Translation failed: {e}")
|
||||
return content
|
||||
|
||||
|
||||
def _inject_context(params: dict, tool: str, step_results: dict, goal: str = "") -> dict:
|
||||
if not step_results:
|
||||
return params
|
||||
params = dict(params)
|
||||
if tool == "file_controller" and params.get("action") in ("write", "create_file"):
|
||||
content = params.get("content", "")
|
||||
if not content or len(content) < 50:
|
||||
all_results = [
|
||||
v for v in step_results.values()
|
||||
if v and len(v) > 100 and v not in ("Done.", "Completed.")
|
||||
]
|
||||
if all_results:
|
||||
combined = "\n\n---\n\n".join(all_results)
|
||||
translated = _translate_to_goal_language(combined, goal)
|
||||
params["content"] = translated
|
||||
print("[Executor] 💉 Injected + translated content")
|
||||
return params
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tool routing
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
||||
if tool == "open_app":
|
||||
from actions.open_app import open_app
|
||||
return open_app(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "web_search":
|
||||
from actions.web_search import web_search
|
||||
return web_search(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "game_updater":
|
||||
from actions.game_updater import game_updater
|
||||
return game_updater(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
|
||||
elif tool == "browser_control":
|
||||
from actions.browser_control import browser_control
|
||||
return browser_control(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "file_controller":
|
||||
from actions.file_controller import file_controller
|
||||
return file_controller(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "code_helper":
|
||||
from actions.code_helper import code_helper
|
||||
return code_helper(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
|
||||
elif tool == "dev_agent":
|
||||
from actions.dev_agent import dev_agent
|
||||
return dev_agent(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
|
||||
elif tool == "screen_process":
|
||||
from actions.screen_processor import screen_process
|
||||
result = screen_process(parameters=parameters, player=None)
|
||||
return result if isinstance(result, str) else "Screen captured and analyzed."
|
||||
|
||||
elif tool == "send_message":
|
||||
from actions.send_message import send_message
|
||||
return send_message(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "reminder":
|
||||
from actions.reminder import reminder
|
||||
return reminder(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "youtube_video":
|
||||
from actions.youtube_video import youtube_video
|
||||
return youtube_video(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "weather_report":
|
||||
from actions.weather_report import weather_action
|
||||
return weather_action(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "computer_settings":
|
||||
from actions.computer_settings import computer_settings
|
||||
return computer_settings(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "desktop_control":
|
||||
from actions.desktop import desktop_control
|
||||
return desktop_control(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "computer_control":
|
||||
from actions.computer_control import computer_control
|
||||
return computer_control(parameters=parameters, player=None) or "Done."
|
||||
|
||||
elif tool == "generated_code":
|
||||
description = parameters.get("description", "")
|
||||
if not description:
|
||||
raise ValueError("generated_code requires a 'description' parameter.")
|
||||
return _run_generated_code(description, speak=speak)
|
||||
|
||||
elif tool == "flight_finder":
|
||||
from actions.flight_finder import flight_finder
|
||||
return flight_finder(parameters=parameters, player=None, speak=speak) or "Done."
|
||||
|
||||
else:
|
||||
print(f"[Executor] ⚠️ Unknown tool '{tool}' — falling back to generated_code")
|
||||
return _run_generated_code(f"Accomplish this task: {parameters}", speak=speak)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# AgentExecutor
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class AgentExecutor:
|
||||
|
||||
MAX_REPLAN_ATTEMPTS = 2
|
||||
|
||||
def execute(
|
||||
self,
|
||||
goal: str,
|
||||
speak: Callable | None = None,
|
||||
cancel_flag: threading.Event | None = None,
|
||||
) -> str:
|
||||
print(f"\n[Executor] 🎯 Goal: {goal}")
|
||||
|
||||
replan_attempts = 0
|
||||
completed_steps: list = []
|
||||
step_results: dict = {}
|
||||
plan = create_plan(goal)
|
||||
|
||||
while True:
|
||||
steps = plan.get("steps", [])
|
||||
if not steps:
|
||||
msg = "I couldn't create a valid plan for this task, sir."
|
||||
if speak: speak(msg)
|
||||
return msg
|
||||
|
||||
success = True
|
||||
failed_step = None
|
||||
failed_error = ""
|
||||
|
||||
for step in steps:
|
||||
if cancel_flag and cancel_flag.is_set():
|
||||
if speak: speak("Task cancelled, sir.")
|
||||
return "Task cancelled."
|
||||
|
||||
step_num = step.get("step", "?")
|
||||
tool = step.get("tool", "generated_code")
|
||||
desc = step.get("description", "")
|
||||
params = step.get("parameters", {})
|
||||
params = _inject_context(params, tool, step_results, goal=goal)
|
||||
|
||||
print(f"\n[Executor] ▶️ Step {step_num}: [{tool}] {desc}")
|
||||
|
||||
attempt = 1
|
||||
step_ok = False
|
||||
|
||||
while attempt <= 3:
|
||||
if cancel_flag and cancel_flag.is_set():
|
||||
break
|
||||
try:
|
||||
result = _call_tool(tool, params, speak)
|
||||
step_results[step_num] = result
|
||||
completed_steps.append(step)
|
||||
print(f"[Executor] ✅ Step {step_num} done: {str(result)[:100]}")
|
||||
step_ok = True
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
print(f"[Executor] ❌ Step {step_num} attempt {attempt} failed: {error_msg}")
|
||||
|
||||
recovery = analyze_error(step, error_msg, attempt=attempt)
|
||||
decision = recovery["decision"]
|
||||
user_msg = recovery.get("user_message", "")
|
||||
|
||||
if speak and user_msg:
|
||||
speak(user_msg)
|
||||
|
||||
if decision == ErrorDecision.RETRY:
|
||||
attempt += 1
|
||||
import time; time.sleep(2)
|
||||
continue
|
||||
|
||||
elif decision == ErrorDecision.SKIP:
|
||||
print(f"[Executor] ⏭️ Skipping step {step_num}")
|
||||
completed_steps.append(step)
|
||||
step_ok = True
|
||||
break
|
||||
|
||||
elif decision == ErrorDecision.ABORT:
|
||||
msg = f"Task aborted, sir. {recovery.get('reason', '')}"
|
||||
if speak: speak(msg)
|
||||
return msg
|
||||
|
||||
else: # REPLAN
|
||||
fix_suggestion = recovery.get("fix_suggestion", "")
|
||||
if fix_suggestion and tool != "generated_code":
|
||||
try:
|
||||
fixed_step = generate_fix(step, error_msg, fix_suggestion)
|
||||
if speak: speak("Trying an alternative approach, sir.")
|
||||
res = _call_tool(
|
||||
fixed_step["tool"],
|
||||
fixed_step["parameters"],
|
||||
speak,
|
||||
)
|
||||
step_results[step_num] = res
|
||||
completed_steps.append(step)
|
||||
step_ok = True
|
||||
break
|
||||
except Exception as fix_err:
|
||||
print(f"[Executor] ⚠️ Fix failed: {fix_err}")
|
||||
|
||||
failed_step = step
|
||||
failed_error = error_msg
|
||||
success = False
|
||||
break
|
||||
|
||||
if not step_ok and not failed_step:
|
||||
failed_step = step
|
||||
failed_error = "Max retries exceeded"
|
||||
success = False
|
||||
|
||||
if not success:
|
||||
break
|
||||
|
||||
if success:
|
||||
return self._summarize(goal, completed_steps, speak)
|
||||
|
||||
if replan_attempts >= self.MAX_REPLAN_ATTEMPTS:
|
||||
msg = f"Task failed after {replan_attempts} replan attempts, sir."
|
||||
if speak: speak(msg)
|
||||
return msg
|
||||
|
||||
if speak: speak("Adjusting my approach, sir.")
|
||||
replan_attempts += 1
|
||||
plan = replan(goal, completed_steps, failed_step, failed_error)
|
||||
|
||||
def _summarize(self, goal: str, completed_steps: list, speak: Callable | None) -> str:
|
||||
fallback = f"All done, sir. Completed {len(completed_steps)} steps for: {goal[:60]}."
|
||||
steps_str = "\n".join(f"- {s.get('description', '')}" for s in completed_steps)
|
||||
prompt = (
|
||||
f'User goal: "{goal}"\n'
|
||||
f"Completed steps:\n{steps_str}\n\n"
|
||||
"Write a single natural sentence summarising what was accomplished. "
|
||||
"Address the user as 'sir'. Be direct and positive."
|
||||
)
|
||||
try:
|
||||
summary = call_llm_text(prompt)
|
||||
if summary:
|
||||
if speak: speak(summary)
|
||||
return summary
|
||||
except Exception:
|
||||
pass
|
||||
if speak: speak(fallback)
|
||||
return fallback
|
||||
+211
-272
@@ -1,272 +1,211 @@
|
||||
import json
|
||||
import re
|
||||
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"
|
||||
|
||||
|
||||
PLANNER_PROMPT = """You are the planning module of MARK XXV, a personal AI assistant.
|
||||
Your job: break any user goal into a sequence of steps using ONLY the tools listed below.
|
||||
|
||||
ABSOLUTE RULES:
|
||||
- NEVER use generated_code or write Python scripts. It does not exist.
|
||||
- NEVER reference previous step results in parameters. Every step is independent.
|
||||
- Use web_search for ANY information retrieval, research, or current data.
|
||||
- Use file_controller to save content to disk.
|
||||
- Max 5 steps. Use the minimum steps needed.
|
||||
|
||||
AVAILABLE TOOLS AND THEIR PARAMETERS:
|
||||
|
||||
open_app
|
||||
app_name: string (required)
|
||||
|
||||
web_search
|
||||
query: string (required) — write a clear, focused search query
|
||||
mode: "search" or "compare" (optional, default: search)
|
||||
items: list of strings (optional, for compare mode)
|
||||
aspect: string (optional, for compare mode)
|
||||
|
||||
game_updater
|
||||
action: "update" | "install" | "list" | "download_status" | "schedule" (required)
|
||||
platform: "steam" | "epic" | "both" (optional, default: both)
|
||||
game_name: string (optional)
|
||||
app_id: string (optional)
|
||||
shutdown_when_done: boolean (optional)
|
||||
|
||||
browser_control
|
||||
action: "go_to" | "search" | "click" | "type" | "scroll" | "get_text" | "press" | "close" (required)
|
||||
url: string (for go_to)
|
||||
query: string (for search)
|
||||
text: string (for click/type)
|
||||
direction: "up" | "down" (for scroll)
|
||||
|
||||
file_controller
|
||||
action: "write" | "create_file" | "read" | "list" | "delete" | "move" | "copy" | "find" | "disk_usage" (required)
|
||||
path: string — use "desktop" for Desktop folder
|
||||
name: string — filename
|
||||
content: string — file content (for write/create_file)
|
||||
|
||||
computer_settings
|
||||
action: string (required)
|
||||
description: string — natural language description
|
||||
value: string (optional)
|
||||
|
||||
computer_control
|
||||
action: "type" | "click" | "hotkey" | "press" | "scroll" | "screenshot" | "screen_find" | "screen_click" (required)
|
||||
text: string (for type)
|
||||
x, y: int (for click)
|
||||
keys: string (for hotkey, e.g. "ctrl+c")
|
||||
key: string (for press)
|
||||
direction: "up" | "down" (for scroll)
|
||||
description: string (for screen_find/screen_click)
|
||||
|
||||
screen_process
|
||||
text: string (required) — what to analyze or ask about the screen
|
||||
angle: "screen" | "camera" (optional)
|
||||
|
||||
send_message
|
||||
receiver: string (required)
|
||||
message_text: string (required)
|
||||
platform: string (required)
|
||||
|
||||
reminder
|
||||
date: string YYYY-MM-DD (required)
|
||||
time: string HH:MM (required)
|
||||
message: string (required)
|
||||
|
||||
desktop_control
|
||||
action: "wallpaper" | "organize" | "clean" | "list" | "task" (required)
|
||||
path: string (optional)
|
||||
task: string (optional)
|
||||
|
||||
youtube_video
|
||||
action: "play" | "summarize" | "trending" (required)
|
||||
query: string (for play)
|
||||
|
||||
weather_report
|
||||
city: string (required)
|
||||
|
||||
flight_finder
|
||||
origin: string (required)
|
||||
destination: string (required)
|
||||
date: string (required)
|
||||
|
||||
code_helper
|
||||
action: "write" | "edit" | "run" | "explain" (required)
|
||||
description: string (required)
|
||||
language: string (optional)
|
||||
output_path: string (optional)
|
||||
file_path: string (optional)
|
||||
|
||||
dev_agent
|
||||
description: string (required)
|
||||
language: string (optional)
|
||||
EXAMPLES:
|
||||
|
||||
Goal: "research mechanical engineering and save it to a notepad file"
|
||||
Steps:
|
||||
|
||||
web_search | query: "mechanical engineering overview definition history"
|
||||
web_search | query: "mechanical engineering applications and future trends"
|
||||
file_controller | action: write, path: desktop, name: mechanical_engineering.txt, content: "MECHANICAL ENGINEERING RESEARCH\n\nThis file will be filled with web research results."
|
||||
|
||||
Goal: "What is the price of Bitcoin"
|
||||
Steps:
|
||||
|
||||
web_search | query: "Bitcoin price today USD"
|
||||
|
||||
Goal: "List the files on the desktop and find the largest 5 files"
|
||||
Steps:
|
||||
|
||||
file_controller | action: list, path: desktop
|
||||
file_controller | action: largest, path: desktop, count: 5
|
||||
|
||||
Goal: "Install PUBG from Steam"
|
||||
Steps:
|
||||
|
||||
game_updater | action: install, platform: steam, game_name: "PUBG"
|
||||
|
||||
Goal: "Update all my Steam games"
|
||||
Steps:
|
||||
|
||||
game_updater | action: update, platform: steam
|
||||
|
||||
Goal: "Send John a message on WhatsApp saying there is a meeting tomorrow"
|
||||
Steps:
|
||||
|
||||
send_message | receiver: John, message_text: "There is a meeting tomorrow", platform: WhatsApp
|
||||
|
||||
Goal: "Open the clock and set a reminder for 30 minutes later"
|
||||
Steps:
|
||||
|
||||
reminder | date: [today], time: [now+30min], message: "Reminder"
|
||||
|
||||
OUTPUT — return ONLY valid JSON, no markdown, no explanation, no code blocks:
|
||||
{
|
||||
"goal": "...",
|
||||
"steps": [
|
||||
{
|
||||
"step": 1,
|
||||
"tool": "tool_name",
|
||||
"description": "what this step does",
|
||||
"parameters": {},
|
||||
"critical": true
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def create_plan(goal: str, context: str = "") -> dict:
|
||||
import google.generativeai as genai
|
||||
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(
|
||||
model_name="gemini-2.5-flash-lite",
|
||||
system_instruction=PLANNER_PROMPT
|
||||
)
|
||||
|
||||
user_input = f"Goal: {goal}"
|
||||
if context:
|
||||
user_input += f"\n\nContext: {context}"
|
||||
|
||||
try:
|
||||
response = model.generate_content(user_input)
|
||||
text = response.text.strip()
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
|
||||
plan = json.loads(text)
|
||||
|
||||
if "steps" not in plan or not isinstance(plan["steps"], list):
|
||||
raise ValueError("Invalid plan structure")
|
||||
|
||||
for step in plan["steps"]:
|
||||
if step.get("tool") in ("generated_code",):
|
||||
print(f"[Planner] ⚠️ generated_code detected in step {step.get('step')} — replacing with web_search")
|
||||
desc = step.get("description", goal)
|
||||
step["tool"] = "web_search"
|
||||
step["parameters"] = {"query": desc[:200]}
|
||||
|
||||
print(f"[Planner] ✅ Plan: {len(plan['steps'])} steps")
|
||||
for s in plan["steps"]:
|
||||
print(f" Step {s['step']}: [{s['tool']}] {s['description']}")
|
||||
|
||||
return plan
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"[Planner] ⚠️ JSON parse failed: {e}")
|
||||
return _fallback_plan(goal)
|
||||
except Exception as e:
|
||||
print(f"[Planner] ⚠️ Planning failed: {e}")
|
||||
return _fallback_plan(goal)
|
||||
|
||||
|
||||
def _fallback_plan(goal: str) -> dict:
|
||||
print("[Planner] 🔄 Fallback plan")
|
||||
return {
|
||||
"goal": goal,
|
||||
"steps": [
|
||||
{
|
||||
"step": 1,
|
||||
"tool": "web_search",
|
||||
"description": f"Search for: {goal}",
|
||||
"parameters": {"query": goal},
|
||||
"critical": True
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def replan(goal: str, completed_steps: list, failed_step: dict, error: str) -> dict:
|
||||
import google.generativeai as genai
|
||||
|
||||
genai.configure(api_key=_get_api_key())
|
||||
model = genai.GenerativeModel(
|
||||
model_name="gemini-2.5-flash",
|
||||
system_instruction=PLANNER_PROMPT
|
||||
)
|
||||
|
||||
completed_summary = "\n".join(
|
||||
f" - Step {s['step']} ({s['tool']}): DONE" for s in completed_steps
|
||||
)
|
||||
|
||||
prompt = f"""Goal: {goal}
|
||||
|
||||
Already completed:
|
||||
{completed_summary if completed_summary else ' (none)'}
|
||||
|
||||
Failed step: [{failed_step.get('tool')}] {failed_step.get('description')}
|
||||
Error: {error}
|
||||
|
||||
Create a REVISED plan for the remaining work only. Do not repeat completed steps."""
|
||||
|
||||
try:
|
||||
response = model.generate_content(prompt)
|
||||
text = response.text.strip()
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
plan = json.loads(text)
|
||||
|
||||
for step in plan.get("steps", []):
|
||||
if step.get("tool") == "generated_code":
|
||||
step["tool"] = "web_search"
|
||||
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
||||
|
||||
print(f"[Planner] 🔄 Revised plan: {len(plan['steps'])} steps")
|
||||
return plan
|
||||
except Exception as e:
|
||||
print(f"[Planner] ⚠️ Replan failed: {e}")
|
||||
return _fallback_plan(goal)
|
||||
"""
|
||||
MARK XL — Task Planner
|
||||
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from core.llm_client import call_llm_text
|
||||
|
||||
|
||||
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()
|
||||
|
||||
|
||||
PLANNER_PROMPT = """You are the planning module of MARK XL, a personal AI assistant.
|
||||
Your job: break any user goal into a sequence of steps using ONLY the tools listed below.
|
||||
|
||||
ABSOLUTE RULES:
|
||||
- NEVER use generated_code or write Python scripts. It does not exist.
|
||||
- NEVER reference previous step results in parameters. Every step is independent.
|
||||
- Use web_search for ANY information retrieval, research, or current data.
|
||||
- Use file_controller to save content to disk.
|
||||
- Max 5 steps. Use the minimum steps needed.
|
||||
|
||||
AVAILABLE TOOLS AND THEIR PARAMETERS:
|
||||
|
||||
open_app
|
||||
app_name: string (required)
|
||||
|
||||
web_search
|
||||
query: string (required) — write a clear, focused search query
|
||||
mode: "search" or "compare" (optional, default: search)
|
||||
items: list of strings (optional, for compare mode)
|
||||
aspect: string (optional, for compare mode)
|
||||
|
||||
game_updater
|
||||
action: "update" | "install" | "list" | "download_status" | "schedule" (required)
|
||||
platform: "steam" | "epic" | "both" (optional, default: both)
|
||||
game_name: string (optional)
|
||||
app_id: string (optional)
|
||||
shutdown_when_done: boolean (optional)
|
||||
|
||||
browser_control
|
||||
action: "go_to" | "search" | "click" | "type" | "scroll" | "get_text" | "press" | "close" (required)
|
||||
url: string (for go_to)
|
||||
query: string (for search)
|
||||
text: string (for click/type)
|
||||
direction: "up" | "down" (for scroll)
|
||||
|
||||
file_controller
|
||||
action: "write" | "create_file" | "read" | "list" | "delete" | "move" | "copy" | "find" | "disk_usage" (required)
|
||||
path: string — use "desktop" for Desktop folder
|
||||
name: string — filename
|
||||
content: string — file content (for write/create_file)
|
||||
|
||||
computer_settings
|
||||
action: string (required)
|
||||
description: string — natural language description
|
||||
value: string (optional)
|
||||
|
||||
computer_control
|
||||
action: "type" | "click" | "hotkey" | "press" | "scroll" | "screenshot" | "screen_find" | "screen_click" (required)
|
||||
text: string (for type)
|
||||
x, y: int (for click)
|
||||
keys: string (for hotkey, e.g. "ctrl+c")
|
||||
key: string (for press)
|
||||
direction: "up" | "down" (for scroll)
|
||||
description: string (for screen_find/screen_click)
|
||||
|
||||
screen_process
|
||||
text: string (required) — what to analyze or ask about the screen
|
||||
angle: "screen" | "camera" (optional)
|
||||
|
||||
send_message
|
||||
receiver: string (required)
|
||||
message_text: string (required)
|
||||
platform: string (required)
|
||||
|
||||
reminder
|
||||
date: string YYYY-MM-DD (required)
|
||||
time: string HH:MM (required)
|
||||
message: string (required)
|
||||
|
||||
desktop_control
|
||||
action: "wallpaper" | "organize" | "clean" | "list" | "task" (required)
|
||||
path: string (optional)
|
||||
task: string (optional)
|
||||
|
||||
youtube_video
|
||||
action: "play" | "summarize" | "trending" (required)
|
||||
query: string (for play)
|
||||
|
||||
weather_report
|
||||
city: string (required)
|
||||
|
||||
flight_finder
|
||||
origin: string (required)
|
||||
destination: string (required)
|
||||
date: string (required)
|
||||
|
||||
code_helper
|
||||
action: "write" | "edit" | "run" | "explain" (required)
|
||||
description: string (required)
|
||||
language: string (optional)
|
||||
output_path: string (optional)
|
||||
file_path: string (optional)
|
||||
|
||||
dev_agent
|
||||
description: string (required)
|
||||
language: string (optional)
|
||||
|
||||
OUTPUT — return ONLY valid JSON, no markdown, no explanation, no code blocks:
|
||||
{
|
||||
"goal": "...",
|
||||
"steps": [
|
||||
{
|
||||
"step": 1,
|
||||
"tool": "tool_name",
|
||||
"description": "what this step does",
|
||||
"parameters": {},
|
||||
"critical": true
|
||||
}
|
||||
]
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def create_plan(goal: str, context: str = "") -> dict:
|
||||
user_input = f"Goal: {goal}"
|
||||
if context:
|
||||
user_input += f"\n\nContext: {context}"
|
||||
|
||||
try:
|
||||
text = call_llm_text(user_input, system=PLANNER_PROMPT)
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
|
||||
plan = json.loads(text)
|
||||
if "steps" not in plan or not isinstance(plan["steps"], list):
|
||||
raise ValueError("Invalid plan structure")
|
||||
|
||||
for step in plan["steps"]:
|
||||
if step.get("tool") == "generated_code":
|
||||
print(f"[Planner] ⚠️ generated_code in step {step.get('step')} — replacing with web_search")
|
||||
step["tool"] = "web_search"
|
||||
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
||||
|
||||
print(f"[Planner] ✅ Plan: {len(plan['steps'])} steps")
|
||||
for s in plan["steps"]:
|
||||
print(f" Step {s['step']}: [{s['tool']}] {s['description']}")
|
||||
return plan
|
||||
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"[Planner] ⚠️ JSON parse failed: {e}")
|
||||
return _fallback_plan(goal)
|
||||
except Exception as e:
|
||||
print(f"[Planner] ⚠️ Planning failed: {e}")
|
||||
return _fallback_plan(goal)
|
||||
|
||||
|
||||
def _fallback_plan(goal: str) -> dict:
|
||||
print("[Planner] 🔄 Fallback plan")
|
||||
return {
|
||||
"goal": goal,
|
||||
"steps": [
|
||||
{
|
||||
"step": 1,
|
||||
"tool": "web_search",
|
||||
"description": f"Search for: {goal}",
|
||||
"parameters": {"query": goal},
|
||||
"critical": True,
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def replan(goal: str, completed_steps: list, failed_step: dict, error: str) -> dict:
|
||||
completed_summary = "\n".join(
|
||||
f" - Step {s['step']} ({s['tool']}): DONE" for s in completed_steps
|
||||
)
|
||||
prompt = f"""Goal: {goal}
|
||||
|
||||
Already completed:
|
||||
{completed_summary if completed_summary else ' (none)'}
|
||||
|
||||
Failed step: [{failed_step.get('tool')}] {failed_step.get('description')}
|
||||
Error: {error}
|
||||
|
||||
Create a REVISED plan for the remaining work only. Do not repeat completed steps."""
|
||||
|
||||
try:
|
||||
text = call_llm_text(prompt, system=PLANNER_PROMPT)
|
||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||
plan = json.loads(text)
|
||||
|
||||
for step in plan.get("steps", []):
|
||||
if step.get("tool") == "generated_code":
|
||||
step["tool"] = "web_search"
|
||||
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
||||
|
||||
print(f"[Planner] 🔄 Revised plan: {len(plan['steps'])} steps")
|
||||
return plan
|
||||
except Exception as e:
|
||||
print(f"[Planner] ⚠️ Replan failed: {e}")
|
||||
return _fallback_plan(goal)
|
||||
+26
-17
@@ -1,17 +1,26 @@
|
||||
# config/__init__.py
|
||||
import json, os
|
||||
from pathlib import Path
|
||||
|
||||
_CONFIG_PATH = Path(__file__).parent / "api_keys.json"
|
||||
|
||||
def get_config() -> dict:
|
||||
with open(_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
|
||||
def get_os() -> str:
|
||||
"""Returns: 'windows' | 'mac' | 'linux'"""
|
||||
return get_config().get("os_system", "windows").lower()
|
||||
|
||||
def is_windows() -> bool: return get_os() == "windows"
|
||||
def is_mac() -> bool: return get_os() == "mac"
|
||||
def is_linux() -> bool: return get_os() == "linux"
|
||||
# config/__init__.py
|
||||
import json
|
||||
import platform
|
||||
from pathlib import Path
|
||||
|
||||
_CONFIG_PATH = Path(__file__).parent / "api_keys.json"
|
||||
|
||||
def get_config() -> dict:
|
||||
try:
|
||||
with open(_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
def get_os() -> str:
|
||||
"""Returns 'windows' | 'mac' | 'linux' — detected at runtime, not from config."""
|
||||
s = platform.system().lower()
|
||||
if s == "darwin":
|
||||
return "mac"
|
||||
if s == "windows":
|
||||
return "windows"
|
||||
return "linux"
|
||||
|
||||
def is_windows() -> bool: return get_os() == "windows"
|
||||
def is_mac() -> bool: return get_os() == "mac"
|
||||
def is_linux() -> bool: return get_os() == "linux"
|
||||
@@ -0,0 +1 @@
|
||||
# core package
|
||||
@@ -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 ✓")
|
||||
@@ -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
@@ -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
@@ -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
@@ -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)
|
||||
+54
-51
@@ -1,51 +1,54 @@
|
||||
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()
|
||||
CONFIG_DIR = BASE_DIR / "config"
|
||||
CONFIG_FILE = CONFIG_DIR / "api_keys.json"
|
||||
|
||||
def ensure_config_dir() -> None:
|
||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def config_exists() -> bool:
|
||||
return CONFIG_FILE.exists()
|
||||
|
||||
def save_api_keys(gemini_api_key: str) -> None:
|
||||
ensure_config_dir()
|
||||
|
||||
data: dict = {}
|
||||
if CONFIG_FILE.exists():
|
||||
try:
|
||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
data = {}
|
||||
|
||||
data["gemini_api_key"] = gemini_api_key.strip()
|
||||
|
||||
CONFIG_FILE.write_text(
|
||||
json.dumps(data, indent=2),
|
||||
encoding="utf-8"
|
||||
)
|
||||
|
||||
def load_api_keys() -> dict:
|
||||
if not CONFIG_FILE.exists():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
except Exception as e:
|
||||
print(f"❌ Failed to load api_keys.json: {e}")
|
||||
return {}
|
||||
|
||||
def get_gemini_key() -> str | None:
|
||||
return load_api_keys().get("gemini_api_key")
|
||||
|
||||
def is_configured() -> bool:
|
||||
key = get_gemini_key()
|
||||
return bool(key and len(key) > 15)
|
||||
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()
|
||||
CONFIG_DIR = BASE_DIR / "config"
|
||||
CONFIG_FILE = CONFIG_DIR / "api_keys.json"
|
||||
|
||||
|
||||
def ensure_config_dir() -> None:
|
||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
|
||||
def config_exists() -> bool:
|
||||
return CONFIG_FILE.exists()
|
||||
|
||||
|
||||
def save_config(cfg: dict) -> None:
|
||||
ensure_config_dir()
|
||||
existing: dict = {}
|
||||
if CONFIG_FILE.exists():
|
||||
try:
|
||||
existing = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
existing = {}
|
||||
existing.update(cfg)
|
||||
CONFIG_FILE.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def load_api_keys() -> dict:
|
||||
if not CONFIG_FILE.exists():
|
||||
return {}
|
||||
try:
|
||||
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||
except Exception as e:
|
||||
print(f"❌ Failed to load api_keys.json: {e}")
|
||||
return {}
|
||||
|
||||
|
||||
def is_configured() -> bool:
|
||||
cfg = load_api_keys()
|
||||
return (
|
||||
bool(cfg.get("os_system")) and
|
||||
bool(cfg.get("llm_model")) and
|
||||
bool(cfg.get("stt_engine")) and
|
||||
bool(cfg.get("tts_engine"))
|
||||
)
|
||||
@@ -1,81 +1,159 @@
|
||||
# 🤖 MARK XXXIX (39)
|
||||
### The Ultimate Cross-Platform Personal AI Assistant — By FatihMakes
|
||||
|
||||
> 📺 **[Watch the full setup video on YouTube](https://youtu.be/ej1f5OE3SNQ?si=lCxDhJix9ungq1Ry)**
|
||||
|
||||
A real-time voice AI that can hear, see, understand, and control your computer — on any OS. Supporting Windows, macOS, and Linux. Local execution. Zero subscriptions. Engineered for total autonomy.
|
||||
|
||||
---
|
||||
|
||||
## ✨ Overview
|
||||
|
||||
MARK XXXIX represents the pinnacle of the Jarvis series, evolving into a more flexible and robust system. It bridges the gap between the operating system and human intent. Through natural dialogue, Mark 39 analyzes your screen, processes uploaded documents, and executes complex workflows with a brand-new, adaptive interface.
|
||||
|
||||
It's not just an assistant — it's an extension of your digital life.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Capabilities
|
||||
|
||||
### Core Features
|
||||
| Feature | Description |
|
||||
|---|---|
|
||||
| 🎙️ Real-time Voice | Ultra-low latency conversation in any language |
|
||||
| 🖥️ System Control | Launch apps, manage files, execute terminal commands |
|
||||
| 🧩 Autonomous Tasks | High-level planning for complex, multi-step goals |
|
||||
| 👁️ Visual Awareness | Real-time screen processing and webcam vision |
|
||||
| 🧠 Persistent Memory | Deeply remembers your projects, preferences, and personal context |
|
||||
| ⌨️ Hybrid Input | Seamlessly switch between keyboard typing and voice commands |
|
||||
|
||||
---
|
||||
|
||||
## 🆕 What's New in XXXIX
|
||||
|
||||
- 📂 **Advanced File Handling** — New support for direct file uploads. Drop PDFs, source code, or images into the assistant to have them analyzed, summarized, or edited instantly.
|
||||
- 🎨 **Adaptive & Flexible UI** — A complete overhaul of the interface. The new UI is fully resizable and responsive, featuring transparency controls and customizable layouts to fit your workspace perfectly.
|
||||
- 🐧🍎 **Refined Cross-Platform Stability** — Major fixes for macOS and Linux compatibility. Core system actions are now more consistent across all three major operating systems.
|
||||
- ⚡ **Optimized Core Engine** — Significant performance boost in tool-calling logic and response generation, resulting in a 40% faster interaction speed.
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Quick Start
|
||||
|
||||
```bash
|
||||
git clone https://github.com/FatihMakes/Mark-XXXIX.git
|
||||
cd Mark-XXXIX
|
||||
pip install -r requirements.txt
|
||||
playwright install
|
||||
python main.py
|
||||
```
|
||||
|
||||
> ⚠️ **Installation Note:** To keep the repository lightweight, some OS-specific dependencies are not bundled in `requirements.txt`. If you run into a `ModuleNotFoundError`, simply install the missing package via `pip install <module_name>` for your specific system.
|
||||
|
||||
---
|
||||
|
||||
## 📋 Requirements
|
||||
|
||||
| Requirement | Details |
|
||||
|---|---|
|
||||
| **OS** | Windows 10/11, macOS, or Linux |
|
||||
| **Python** | 3.11 or 3.12 |
|
||||
| **Microphone** | Required for voice interaction |
|
||||
| **API Key** | Free Gemini API key |
|
||||
|
||||
---
|
||||
|
||||
## ⚠️ License
|
||||
|
||||
Personal and non-commercial use only.
|
||||
Licensed under **[Creative Commons BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/)**.
|
||||
|
||||
---
|
||||
|
||||
## 👤 Connect with the Creator
|
||||
|
||||
Engineered by a developer building a real-world JARVIS-style assistant.
|
||||
⭐ **Star the repository to support the journey to Mark 100.**
|
||||
|
||||
| Platform | Link |
|
||||
|---|---|
|
||||
| YouTube | [@FatihMakes](https://www.youtube.com/@FatihMakes) |
|
||||
| Instagram | [@fatihmakes](https://www.instagram.com/fatihmakes) |
|
||||
# 🤖 MARK XL — Local AI Assistant
|
||||
|
||||
> **J.A.R.V.I.S** — Just A Rather Very Intelligent System
|
||||
> Cross-platform voice AI assistant running entirely on local hardware. No cloud APIs required.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
MARK XL is a fully local, real-time voice and visual AI agent. It combines offline speech recognition, a locally hosted LLM (via Ollama), and text-to-speech to deliver a privacy-first personal assistant with OS-level control capabilities.
|
||||
|
||||
Successor to the previous mark, which used the Google Gemini Live API. MARK XL removes all cloud LLM dependencies while adding streaming responses, a dynamic configuration UI, and multi-language support.
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
Microphone → STT (Whisper / Vosk)
|
||||
↓
|
||||
Ollama LLM (tool calling + streaming)
|
||||
↓
|
||||
Tool Execution (OS, Browser, Files …)
|
||||
↓
|
||||
TTS (EdgeTTS / Kokoro / ElevenLabs)
|
||||
↓
|
||||
Speaker
|
||||
```
|
||||
|
||||
### Core Components
|
||||
|
||||
| Layer | Technology | Notes |
|
||||
|-------|-----------|-------|
|
||||
| **STT** | faster-whisper / Vosk | Fully offline. Auto language detection or forced locale. |
|
||||
| **LLM** | Ollama (any model) | qwen2.5, llama3.2, mistral, etc. Streaming + tool calling. |
|
||||
| **TTS** | EdgeTTS / Kokoro / ElevenLabs | EdgeTTS = free + internet. Kokoro = fully offline. |
|
||||
| **UI** | PyQt6 | HUD overlay with system monitor, log panel, file drop zone. |
|
||||
| **Agent** | Custom task queue | Multi-step planner + executor + error recovery. |
|
||||
|
||||
---
|
||||
|
||||
## Features
|
||||
|
||||
- **Streaming responses** — TTS starts speaking on the first sentence, not after the full response
|
||||
- **Tool calling** — 18 built-in tools: browser control, file management, weather, YouTube, messaging, screen analysis, code helper, game updater, flight finder, and more
|
||||
- **Long-term memory** — Silently saves personal facts; recalled in every conversation
|
||||
- **Live configuration** — Change LLM model, STT engine, TTS voice without restarting (⚙ Configure button)
|
||||
- **Ollama auto-start** — Automatically launches `ollama serve` if it's not running
|
||||
- **Model warmup** — Pre-loads the LLM into memory during startup so the first message is as fast as subsequent ones
|
||||
- **Multi-language STT** — Set `stt_language` to `auto` (Whisper detects) or a specific locale (`tr`, `de`, `fr`, …)
|
||||
- **Cross-platform** — Windows, macOS, Linux (OS detected automatically at runtime)
|
||||
- **File drop zone** — Drag and drop images, PDFs, Word docs, CSV, audio, video for AI processing
|
||||
|
||||
---
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.11 or 3.12
|
||||
- [Ollama](https://ollama.com) installed and a model pulled (e.g. `ollama pull qwen2.5:7b`)
|
||||
- A microphone
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
```bash
|
||||
# 1. Install Ollama → https://ollama.com
|
||||
# Then pull a model:
|
||||
ollama pull qwen2.5:7b
|
||||
|
||||
# 2. Clone / download the project and launch
|
||||
cd Mark-XL
|
||||
python main.py
|
||||
```
|
||||
|
||||
That's it. On first run MARK XL:
|
||||
1. Auto-installs base packages (PyQt6, numpy …) and restarts once
|
||||
2. Opens the **Initialisation** overlay — choose STT engine, LLM model, TTS engine
|
||||
3. Click **INITIALISE SYSTEMS** — engine packages install in the background (progress shown in log)
|
||||
4. JARVIS comes online
|
||||
|
||||
After setup, use the **⚙ CONFIGURE** button in the right panel to change any setting at any time without restarting.
|
||||
|
||||
---
|
||||
|
||||
## Configuration (`config/api_keys.json`)
|
||||
|
||||
```json
|
||||
{
|
||||
"stt_engine": "whisper",
|
||||
"stt_model": "base",
|
||||
"stt_language": "auto",
|
||||
"llm_url": "http://localhost:11434",
|
||||
"llm_model": "qwen2.5:7b",
|
||||
"tts_engine": "edgetts",
|
||||
"tts_voice": "en-US-GuyNeural",
|
||||
"elevenlabs_api_key": ""
|
||||
}
|
||||
```
|
||||
|
||||
| Key | Values | Default |
|
||||
|-----|--------|---------|
|
||||
| `stt_engine` | `whisper` / `vosk` | `whisper` |
|
||||
| `stt_model` | `tiny` / `base` / `small` / `medium` / `large-v3` | `base` |
|
||||
| `stt_language` | `auto` or ISO code (`tr`, `en`, `de` …) | `auto` |
|
||||
| `llm_url` | Ollama API base URL | `http://localhost:11434` |
|
||||
| `llm_model` | Any model pulled in Ollama | `qwen2.5:7b` |
|
||||
| `tts_engine` | `edgetts` / `kokoro` / `elevenlabs` | `edgetts` |
|
||||
| `tts_voice` | Voice name / ID depending on engine | `en-US-GuyNeural` |
|
||||
|
||||
---
|
||||
|
||||
## Built-in Tools
|
||||
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `open_app` | Opens any application or website |
|
||||
| `web_search` | Web search and compare mode |
|
||||
| `weather_report` | Current weather for any city |
|
||||
| `send_message` | WhatsApp / Telegram messaging |
|
||||
| `reminder` | Timed reminders via Task Scheduler |
|
||||
| `youtube_video` | Play, summarize, trending videos |
|
||||
| `screen_process` | Screen capture + vision model analysis |
|
||||
| `computer_settings` | Volume, brightness, window management, shortcuts |
|
||||
| `browser_control` | Full Playwright browser automation |
|
||||
| `file_controller` | File/folder CRUD, search, disk usage |
|
||||
| `desktop_control` | Wallpaper, organize, clean desktop |
|
||||
| `code_helper` | Write, edit, explain, run code |
|
||||
| `dev_agent` | Build complete multi-file projects |
|
||||
| `agent_task` | Multi-step autonomous task execution |
|
||||
| `computer_control` | Direct mouse/keyboard control |
|
||||
| `game_updater` | Steam / Epic Games install & update |
|
||||
| `flight_finder` | Google Flights search |
|
||||
| `file_processor` | Process images, PDFs, CSV, audio, video |
|
||||
|
||||
---
|
||||
|
||||
## Keyboard Shortcuts
|
||||
|
||||
| Key | Action |
|
||||
|-----|--------|
|
||||
| `F4` | Mute / unmute microphone |
|
||||
| `F11` | Toggle fullscreen |
|
||||
|
||||
---
|
||||
|
||||
## TTS Engine Comparison
|
||||
|
||||
| Engine | Internet | Quality | Cost |
|
||||
|--------|----------|---------|------|
|
||||
| EdgeTTS | Required | Good | Free |
|
||||
| Kokoro | No | Excellent | Free (local model ~100 MB) |
|
||||
| ElevenLabs | Required | Best | Paid API |
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT — FatihMakes Industries
|
||||
+54
-24
@@ -1,24 +1,54 @@
|
||||
sounddevice
|
||||
google-genai
|
||||
google-generativeai
|
||||
pillow
|
||||
requests
|
||||
beautifulsoup4
|
||||
duckduckgo-search
|
||||
playwright
|
||||
pyautogui
|
||||
pyperclip
|
||||
pygetwindow
|
||||
opencv-python
|
||||
numpy
|
||||
mss
|
||||
Pillow
|
||||
psutil
|
||||
comtypes
|
||||
pycaw
|
||||
win10toast
|
||||
send2trash
|
||||
youtube-transcript-api
|
||||
pywinauto
|
||||
python-pptx
|
||||
pyqt6
|
||||
# MARK XL — Python dependencies
|
||||
#
|
||||
# Normal users: just run python main.py
|
||||
# All packages are installed automatically on first launch.
|
||||
#
|
||||
# Developers / manual setup:
|
||||
# pip install -r requirements.txt
|
||||
# Platform-specific packages install only on the matching OS.
|
||||
|
||||
# ── Core UI & system ──────────────────────────────────────────────────────
|
||||
PyQt6
|
||||
psutil
|
||||
pillow
|
||||
sounddevice
|
||||
numpy
|
||||
soundfile
|
||||
requests
|
||||
|
||||
# ── Web automation & search ───────────────────────────────────────────────
|
||||
playwright
|
||||
beautifulsoup4
|
||||
duckduckgo-search
|
||||
|
||||
# ── OS control (cross-platform) ───────────────────────────────────────────
|
||||
pyautogui
|
||||
pyperclip
|
||||
pygetwindow
|
||||
send2trash
|
||||
mss
|
||||
opencv-python
|
||||
|
||||
# ── OS control (Windows only) ─────────────────────────────────────────────
|
||||
pywinauto ; sys_platform == "win32"
|
||||
comtypes ; sys_platform == "win32"
|
||||
pycaw ; sys_platform == "win32"
|
||||
win10toast; sys_platform == "win32"
|
||||
|
||||
# ── Media & file processing ───────────────────────────────────────────────
|
||||
youtube-transcript-api
|
||||
python-pptx
|
||||
miniaudio
|
||||
|
||||
# ── STT — choose one (auto-installed by main.py based on your config) ─────
|
||||
faster-whisper # Whisper (default, recommended)
|
||||
# vosk # Vosk (alternative — uncomment if preferred)
|
||||
|
||||
# ── TTS — choose one (auto-installed by main.py based on your config) ─────
|
||||
edge-tts # EdgeTTS (default, free, requires internet)
|
||||
# kokoro # Kokoro (fully offline — uncomment if preferred)
|
||||
# elevenlabs # ElevenLabs (cloud API — uncomment if preferred)
|
||||
|
||||
# ── Local LLM ─────────────────────────────────────────────────────────────
|
||||
# Ollama must be installed separately: https://ollama.com
|
||||
# Then pull a model: ollama pull qwen2.5:7b
|
||||
@@ -23,7 +23,7 @@ from PyQt6.QtGui import (
|
||||
QRadialGradient, QShortcut,
|
||||
)
|
||||
from PyQt6.QtWidgets import (
|
||||
QApplication, QFileDialog, QFrame, QHBoxLayout, QLabel, QLineEdit,
|
||||
QApplication, QComboBox, QFileDialog, QFrame, QHBoxLayout, QLabel, QLineEdit,
|
||||
QMainWindow, QPushButton, QScrollArea, QSizePolicy, QTextEdit,
|
||||
QVBoxLayout, QWidget, QProgressBar,
|
||||
)
|
||||
@@ -856,111 +856,85 @@ class _DropCanvas(QWidget):
|
||||
|
||||
|
||||
class SetupOverlay(QWidget):
|
||||
done = pyqtSignal(str, str)
|
||||
# Emits a JSON string containing the full config dict
|
||||
done = pyqtSignal(str)
|
||||
|
||||
def __init__(self, parent=None):
|
||||
# ------------------------------------------------------------------ #
|
||||
_INPUT_STYLE = "" # filled in __init__ after C is available
|
||||
|
||||
def __init__(self, parent=None, initial: dict | None = None, mode: str = "init"):
|
||||
super().__init__(parent)
|
||||
self._mode = mode
|
||||
_init = initial or {}
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||
self.setStyleSheet(f"""
|
||||
SetupOverlay {{
|
||||
background: rgba(0, 6, 10, 245);
|
||||
background: rgba(0, 6, 10, 248);
|
||||
border: 1px solid {C.BORDER_B};
|
||||
border-radius: 6px;
|
||||
}}
|
||||
""")
|
||||
|
||||
detected = {"darwin": "mac", "windows": "windows"}.get(
|
||||
_OS.lower(), "linux"
|
||||
)
|
||||
self._sel_os = detected
|
||||
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(30, 22, 30, 22)
|
||||
layout.setSpacing(8)
|
||||
|
||||
def _lbl(txt, font_size=9, bold=False, color=C.PRI,
|
||||
align=Qt.AlignmentFlag.AlignCenter):
|
||||
w = QLabel(txt)
|
||||
w.setAlignment(align)
|
||||
w.setFont(QFont("Courier New", font_size,
|
||||
QFont.Weight.Bold if bold else QFont.Weight.Normal))
|
||||
w.setStyleSheet(f"color: {color}; background: transparent;")
|
||||
return w
|
||||
|
||||
layout.addWidget(_lbl("◈ INITIALISATION REQUIRED", 13, True))
|
||||
layout.addWidget(_lbl("Configure J.A.R.V.I.S. before first boot.", 9, color=C.PRI_DIM))
|
||||
layout.addSpacing(6)
|
||||
|
||||
sep = QFrame(); sep.setFrameShape(QFrame.Shape.HLine)
|
||||
sep.setStyleSheet(f"color: {C.BORDER};"); layout.addWidget(sep)
|
||||
layout.addSpacing(4)
|
||||
|
||||
layout.addWidget(_lbl("GEMINI API KEY", 8, color=C.TEXT_DIM,
|
||||
align=Qt.AlignmentFlag.AlignLeft))
|
||||
self._key_input = QLineEdit()
|
||||
self._key_input.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self._key_input.setPlaceholderText("AIza…")
|
||||
self._key_input.setFont(QFont("Courier New", 10))
|
||||
self._key_input.setFixedHeight(32)
|
||||
self._key_input.setStyleSheet(f"""
|
||||
_INPUT = f"""
|
||||
QLineEdit {{
|
||||
background: #000d12; color: {C.TEXT};
|
||||
border: 1px solid {C.BORDER}; border-radius: 3px; padding: 4px 8px;
|
||||
border: 1px solid {C.BORDER}; border-radius: 3px; padding: 3px 7px;
|
||||
font-family: 'Courier New'; font-size: 9pt;
|
||||
}}
|
||||
QLineEdit:focus {{ border: 1px solid {C.PRI}; }}
|
||||
""")
|
||||
layout.addWidget(self._key_input)
|
||||
layout.addSpacing(12)
|
||||
"""
|
||||
|
||||
sep2 = QFrame(); sep2.setFrameShape(QFrame.Shape.HLine)
|
||||
sep2.setStyleSheet(f"color: {C.BORDER};"); layout.addWidget(sep2)
|
||||
layout.addSpacing(4)
|
||||
self._sel_stt = _init.get("stt_engine", "whisper")
|
||||
self._sel_tts = _init.get("tts_engine", "edgetts")
|
||||
|
||||
layout.addWidget(_lbl("OPERATING SYSTEM", 8, color=C.TEXT_DIM,
|
||||
align=Qt.AlignmentFlag.AlignLeft))
|
||||
det_name = {"windows": "Windows", "mac": "macOS", "linux": "Linux"}[detected]
|
||||
layout.addWidget(_lbl(f"Auto-detected: {det_name}", 8, color=C.ACC2,
|
||||
align=Qt.AlignmentFlag.AlignLeft))
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(22, 16, 22, 16)
|
||||
layout.setSpacing(6)
|
||||
|
||||
os_row = QHBoxLayout(); os_row.setSpacing(6)
|
||||
self._os_btns: dict[str, QPushButton] = {}
|
||||
for key, label in [("windows","⊞ Windows"),("mac"," macOS"),("linux","🐧 Linux")]:
|
||||
btn = QPushButton(label)
|
||||
btn.setFont(QFont("Courier New", 9, QFont.Weight.Bold))
|
||||
btn.setFixedHeight(32)
|
||||
btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
btn.clicked.connect(lambda _, k=key: self._sel(k))
|
||||
os_row.addWidget(btn)
|
||||
self._os_btns[key] = btn
|
||||
layout.addLayout(os_row)
|
||||
self._sel(detected)
|
||||
layout.addSpacing(12)
|
||||
def _lbl(txt, sz=9, bold=False, col=C.PRI, align=Qt.AlignmentFlag.AlignCenter):
|
||||
w = QLabel(txt); w.setAlignment(align)
|
||||
w.setFont(QFont("Courier New", sz,
|
||||
QFont.Weight.Bold if bold else QFont.Weight.Normal))
|
||||
w.setStyleSheet(f"color: {col}; background: transparent;")
|
||||
return w
|
||||
|
||||
init_btn = QPushButton("▸ INITIALISE SYSTEMS")
|
||||
init_btn.setFont(QFont("Courier New", 10, QFont.Weight.Bold))
|
||||
init_btn.setFixedHeight(36)
|
||||
init_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
init_btn.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background: transparent; color: {C.PRI};
|
||||
border: 1px solid {C.PRI_DIM}; border-radius: 3px;
|
||||
}}
|
||||
QPushButton:hover {{
|
||||
background: {C.PRI_GHO}; border: 1px solid {C.PRI};
|
||||
}}
|
||||
""")
|
||||
init_btn.clicked.connect(self._submit)
|
||||
layout.addWidget(init_btn)
|
||||
def _sep():
|
||||
s = QFrame(); s.setFrameShape(QFrame.Shape.HLine)
|
||||
s.setStyleSheet(f"color: {C.BORDER}; margin: 2px 0;")
|
||||
return s
|
||||
|
||||
def _sel(self, key: str):
|
||||
self._sel_os = key
|
||||
pal = {"windows":(C.PRI,"#001a22"),"mac":(C.ACC2,"#1a1400"),"linux":(C.GREEN,"#001a0d")}
|
||||
for k, btn in self._os_btns.items():
|
||||
if k == key:
|
||||
fg, bg = pal[k]
|
||||
def _input(placeholder="", pw=False, fixed_h=28):
|
||||
w = QLineEdit()
|
||||
w.setPlaceholderText(placeholder)
|
||||
w.setFixedHeight(fixed_h)
|
||||
if pw:
|
||||
w.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
w.setStyleSheet(_INPUT)
|
||||
return w
|
||||
|
||||
def _toggle_row(keys_labels: list, getter, setter):
|
||||
row = QHBoxLayout(); row.setSpacing(5)
|
||||
btns: dict[str, QPushButton] = {}
|
||||
def _click(k):
|
||||
setter(k)
|
||||
for bk, b in btns.items():
|
||||
_style_btn(b, bk == k)
|
||||
for k, lbl in keys_labels:
|
||||
b = QPushButton(lbl)
|
||||
b.setFixedHeight(26)
|
||||
b.setFont(QFont("Courier New", 8, QFont.Weight.Bold))
|
||||
b.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
b.clicked.connect(lambda _, kk=k: _click(kk))
|
||||
row.addWidget(b)
|
||||
btns[k] = b
|
||||
_click(getter())
|
||||
return row, btns
|
||||
|
||||
def _style_btn(btn: QPushButton, active: bool):
|
||||
if active:
|
||||
btn.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background: {fg}; color: {bg};
|
||||
background: {C.PRI}; color: #001a22;
|
||||
border: none; border-radius: 3px; font-weight: bold;
|
||||
}}
|
||||
""")
|
||||
@@ -973,15 +947,335 @@ class SetupOverlay(QWidget):
|
||||
QPushButton:hover {{ color: {C.TEXT}; border: 1px solid {C.BORDER_B}; }}
|
||||
""")
|
||||
|
||||
# ── Header ──────────────────────────────────────────────────── #
|
||||
if mode == "config":
|
||||
layout.addWidget(_lbl("◈ CONFIGURATION", 12, True))
|
||||
layout.addWidget(_lbl("Update J.A.R.V.I.S. settings and click Apply.", 8, col=C.PRI_DIM))
|
||||
else:
|
||||
layout.addWidget(_lbl("◈ INITIALISATION REQUIRED", 12, True))
|
||||
layout.addWidget(_lbl("Configure J.A.R.V.I.S. before first boot.", 8, col=C.PRI_DIM))
|
||||
layout.addWidget(_sep())
|
||||
|
||||
# ── STT ──────────────────────────────────────────────────────── #
|
||||
layout.addWidget(_lbl("SPEECH-TO-TEXT ENGINE", 7, col=C.TEXT_DIM,
|
||||
align=Qt.AlignmentFlag.AlignLeft))
|
||||
stt_row, self._stt_btns = _toggle_row(
|
||||
[("whisper","🎙 Whisper"), ("vosk","🔊 Vosk")],
|
||||
lambda: self._sel_stt,
|
||||
self._set_stt,
|
||||
)
|
||||
layout.addLayout(stt_row)
|
||||
|
||||
_COMBO_STYLE = f"""
|
||||
QComboBox {{
|
||||
background: #000d12; color: {C.TEXT};
|
||||
border: 1px solid {C.BORDER}; border-radius: 3px; padding: 3px 7px;
|
||||
font-family: 'Courier New'; font-size: 9pt;
|
||||
}}
|
||||
QComboBox:focus {{ border: 1px solid {C.PRI}; }}
|
||||
QComboBox::drop-down {{ border: none; width: 18px; }}
|
||||
QComboBox QAbstractItemView {{
|
||||
background: #000d12; color: {C.TEXT};
|
||||
border: 1px solid {C.BORDER};
|
||||
selection-background-color: {C.PRI_GHO};
|
||||
font-family: 'Courier New'; font-size: 9pt;
|
||||
}}
|
||||
"""
|
||||
|
||||
stt_detail = QHBoxLayout(); stt_detail.setSpacing(5)
|
||||
stt_detail.addWidget(_lbl("Model:", 7, col=C.TEXT_MED,
|
||||
align=Qt.AlignmentFlag.AlignRight))
|
||||
|
||||
# Whisper: dropdown with predefined sizes
|
||||
self._whisper_combo = QComboBox()
|
||||
self._whisper_combo.setFixedHeight(28)
|
||||
self._whisper_combo.setStyleSheet(_COMBO_STYLE)
|
||||
for m in ["tiny", "base", "small", "medium", "large-v3"]:
|
||||
self._whisper_combo.addItem(m)
|
||||
_cur_model = _init.get("stt_model", "base")
|
||||
_idx = self._whisper_combo.findText(_cur_model)
|
||||
self._whisper_combo.setCurrentIndex(_idx if _idx >= 0 else 1)
|
||||
stt_detail.addWidget(self._whisper_combo)
|
||||
|
||||
# Vosk: free-text path input
|
||||
self._vosk_model_input = _input("model dir path (leave empty for auto-download)")
|
||||
self._vosk_model_input.setText(_init.get("vosk_model_path", ""))
|
||||
stt_detail.addWidget(self._vosk_model_input)
|
||||
|
||||
layout.addLayout(stt_detail)
|
||||
|
||||
# Initial visibility
|
||||
self._whisper_combo.setVisible(self._sel_stt == "whisper")
|
||||
self._vosk_model_input.setVisible(self._sel_stt == "vosk")
|
||||
|
||||
stt_lang_row = QHBoxLayout(); stt_lang_row.setSpacing(5)
|
||||
stt_lang_row.addWidget(_lbl("Language:", 7, col=C.TEXT_MED,
|
||||
align=Qt.AlignmentFlag.AlignRight))
|
||||
self._stt_lang_input = _input("auto (or: tr / en / de / fr / es / zh …)")
|
||||
self._stt_lang_input.setText(_init.get("stt_language", "auto"))
|
||||
stt_lang_row.addWidget(self._stt_lang_input)
|
||||
layout.addLayout(stt_lang_row)
|
||||
layout.addWidget(_sep())
|
||||
|
||||
# ── LLM ──────────────────────────────────────────────────────── #
|
||||
layout.addWidget(_lbl("LOCAL LLM (Ollama)", 7, col=C.TEXT_DIM,
|
||||
align=Qt.AlignmentFlag.AlignLeft))
|
||||
llm_row = QHBoxLayout(); llm_row.setSpacing(5)
|
||||
llm_row.addWidget(_lbl("URL:", 7, col=C.TEXT_MED,
|
||||
align=Qt.AlignmentFlag.AlignRight))
|
||||
self._llm_url_input = _input("http://localhost:11434")
|
||||
self._llm_url_input.setText(_init.get("llm_url", "http://localhost:11434"))
|
||||
llm_row.addWidget(self._llm_url_input, stretch=2)
|
||||
llm_row.addWidget(_lbl("Model:", 7, col=C.TEXT_MED,
|
||||
align=Qt.AlignmentFlag.AlignRight))
|
||||
self._llm_model_input = _input("e.g. llama3.2 / qwen2.5 / mistral")
|
||||
self._llm_model_input.setText(_init.get("llm_model", ""))
|
||||
llm_row.addWidget(self._llm_model_input, stretch=2)
|
||||
layout.addLayout(llm_row)
|
||||
layout.addWidget(_sep())
|
||||
|
||||
# ── TTS ──────────────────────────────────────────────────────── #
|
||||
layout.addWidget(_lbl("TEXT-TO-SPEECH ENGINE", 7, col=C.TEXT_DIM,
|
||||
align=Qt.AlignmentFlag.AlignLeft))
|
||||
tts_row, self._tts_btns = _toggle_row(
|
||||
[("edgetts","🔈 EdgeTTS"), ("kokoro","🤖 Kokoro"), ("elevenlabs","⚡ ElevenLabs")],
|
||||
lambda: self._sel_tts,
|
||||
self._set_tts,
|
||||
)
|
||||
layout.addLayout(tts_row)
|
||||
|
||||
voice_row = QHBoxLayout(); voice_row.setSpacing(5)
|
||||
self._voice_lbl = QLabel("Voice:")
|
||||
self._voice_lbl.setFont(QFont("Courier New", 7))
|
||||
self._voice_lbl.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
|
||||
self._voice_lbl.setStyleSheet(f"color: {C.TEXT_MED}; background: transparent;")
|
||||
voice_row.addWidget(self._voice_lbl)
|
||||
|
||||
self._tts_voice_input = _input("en-US-GuyNeural")
|
||||
self._tts_voice_input.setText(_init.get("tts_voice", "en-US-GuyNeural"))
|
||||
voice_row.addWidget(self._tts_voice_input)
|
||||
|
||||
# Kokoro: dropdown with predefined voices (hidden unless Kokoro selected)
|
||||
self._kokoro_combo = QComboBox()
|
||||
self._kokoro_combo.setFixedHeight(28)
|
||||
self._kokoro_combo.setStyleSheet(_COMBO_STYLE)
|
||||
_KOKORO_VOICES = [
|
||||
("af_heart", "af_heart — EN-F warm (recommended)"),
|
||||
("af_sky", "af_sky — EN-F clear"),
|
||||
("af_bella", "af_bella — EN-F bella"),
|
||||
("af_sarah", "af_sarah — EN-F sarah"),
|
||||
("am_adam", "am_adam — EN-M adam"),
|
||||
("am_michael", "am_michael — EN-M michael"),
|
||||
("bf_emma", "bf_emma — UK-F emma"),
|
||||
("bf_isabella", "bf_isabella — UK-F isabella"),
|
||||
("bm_george", "bm_george — UK-M george"),
|
||||
("bm_lewis", "bm_lewis — UK-M lewis"),
|
||||
("jf_alpha", "jf_alpha — Japanese Female"),
|
||||
("jm_kumo", "jm_kumo — Japanese Male"),
|
||||
]
|
||||
for val, display in _KOKORO_VOICES:
|
||||
self._kokoro_combo.addItem(display, userData=val)
|
||||
_cur_voice = _init.get("tts_voice", "af_heart")
|
||||
for i in range(self._kokoro_combo.count()):
|
||||
if self._kokoro_combo.itemData(i) == _cur_voice:
|
||||
self._kokoro_combo.setCurrentIndex(i)
|
||||
break
|
||||
self._kokoro_combo.setVisible(False) # shown only when Kokoro active
|
||||
voice_row.addWidget(self._kokoro_combo)
|
||||
|
||||
layout.addLayout(voice_row)
|
||||
|
||||
# Kokoro speed — only visible when Kokoro is selected
|
||||
self._kokoro_speed_widget = QWidget()
|
||||
self._kokoro_speed_widget.setStyleSheet("background: transparent;")
|
||||
ks_row = QHBoxLayout(self._kokoro_speed_widget)
|
||||
ks_row.setContentsMargins(0, 0, 0, 0)
|
||||
ks_row.setSpacing(5)
|
||||
ks_row.addWidget(_lbl("Speed:", 7, col=C.TEXT_MED,
|
||||
align=Qt.AlignmentFlag.AlignRight))
|
||||
self._kokoro_speed_combo = QComboBox()
|
||||
self._kokoro_speed_combo.setFixedHeight(28)
|
||||
self._kokoro_speed_combo.setStyleSheet(_COMBO_STYLE)
|
||||
for val, label in [
|
||||
("0.8", "0.8× — Slow"),
|
||||
("1.0", "1.0× — Normal"),
|
||||
("1.1", "1.1× — Slightly fast"),
|
||||
("1.2", "1.2× — Fast (recommended)"),
|
||||
("1.3", "1.3× — Faster"),
|
||||
("1.5", "1.5× — Very fast"),
|
||||
]:
|
||||
self._kokoro_speed_combo.addItem(label, userData=val)
|
||||
_cur_speed = str(_init.get("tts_speed", "1.2"))
|
||||
for i in range(self._kokoro_speed_combo.count()):
|
||||
if self._kokoro_speed_combo.itemData(i) == _cur_speed:
|
||||
self._kokoro_speed_combo.setCurrentIndex(i)
|
||||
break
|
||||
ks_row.addWidget(self._kokoro_speed_combo)
|
||||
layout.addWidget(self._kokoro_speed_widget)
|
||||
|
||||
# ElevenLabs key — only visible when ElevenLabs is selected
|
||||
self._el_key_widget = QWidget()
|
||||
self._el_key_widget.setStyleSheet("background: transparent;")
|
||||
el_row = QHBoxLayout(self._el_key_widget)
|
||||
el_row.setContentsMargins(0, 0, 0, 0)
|
||||
el_row.setSpacing(5)
|
||||
el_row.addWidget(_lbl("API Key:", 7, col=C.TEXT_MED,
|
||||
align=Qt.AlignmentFlag.AlignRight))
|
||||
self._el_key_input = _input("ElevenLabs API key", pw=True)
|
||||
self._el_key_input.setText(_init.get("elevenlabs_api_key", ""))
|
||||
el_row.addWidget(self._el_key_input)
|
||||
layout.addWidget(self._el_key_widget)
|
||||
|
||||
layout.addWidget(_sep())
|
||||
|
||||
# Set correct initial state for TTS UI
|
||||
self._update_tts_ui(self._sel_tts)
|
||||
|
||||
# ── Action buttons ─────────────────────────────────────────────── #
|
||||
btn_row = QHBoxLayout(); btn_row.setSpacing(8)
|
||||
|
||||
if mode == "config":
|
||||
cancel_btn = QPushButton("✕ CANCEL")
|
||||
cancel_btn.setFont(QFont("Courier New", 9, QFont.Weight.Bold))
|
||||
cancel_btn.setFixedHeight(34)
|
||||
cancel_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
cancel_btn.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background: transparent; color: {C.TEXT_DIM};
|
||||
border: 1px solid {C.BORDER}; border-radius: 3px;
|
||||
}}
|
||||
QPushButton:hover {{
|
||||
color: {C.RED}; border: 1px solid {C.RED};
|
||||
}}
|
||||
""")
|
||||
cancel_btn.clicked.connect(self.hide)
|
||||
btn_row.addWidget(cancel_btn)
|
||||
|
||||
btn_label = "▸ APPLY CHANGES" if mode == "config" else "▸ INITIALISE SYSTEMS"
|
||||
init_btn = QPushButton(btn_label)
|
||||
init_btn.setFont(QFont("Courier New", 10, QFont.Weight.Bold))
|
||||
init_btn.setFixedHeight(34)
|
||||
init_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
init_btn.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background: transparent; color: {C.PRI};
|
||||
border: 1px solid {C.PRI_DIM}; border-radius: 3px;
|
||||
}}
|
||||
QPushButton:hover {{
|
||||
background: {C.PRI_GHO}; border: 1px solid {C.PRI};
|
||||
}}
|
||||
""")
|
||||
init_btn.clicked.connect(self._submit)
|
||||
btn_row.addWidget(init_btn)
|
||||
layout.addLayout(btn_row)
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
def _update_tts_ui(self, key: str) -> None:
|
||||
"""Show/hide and relabel TTS fields based on selected engine."""
|
||||
if not hasattr(self, "_voice_lbl"):
|
||||
return
|
||||
|
||||
is_kokoro = (key == "kokoro")
|
||||
|
||||
# Kokoro uses a dropdown; other engines use a text input
|
||||
if hasattr(self, "_tts_voice_input"):
|
||||
self._tts_voice_input.setVisible(not is_kokoro)
|
||||
if hasattr(self, "_kokoro_combo"):
|
||||
self._kokoro_combo.setVisible(is_kokoro)
|
||||
|
||||
if key == "elevenlabs":
|
||||
self._voice_lbl.setText("Voice ID:")
|
||||
if hasattr(self, "_tts_voice_input"):
|
||||
self._tts_voice_input.setPlaceholderText("ElevenLabs voice ID")
|
||||
elif key == "kokoro":
|
||||
self._voice_lbl.setText("Voice:")
|
||||
else: # edgetts
|
||||
self._voice_lbl.setText("Voice:")
|
||||
if hasattr(self, "_tts_voice_input"):
|
||||
self._tts_voice_input.setPlaceholderText(
|
||||
"en-US-GuyNeural / en-GB-RyanNeural / tr-TR-AhmetNeural …"
|
||||
)
|
||||
|
||||
if hasattr(self, "_kokoro_speed_widget"):
|
||||
self._kokoro_speed_widget.setVisible(is_kokoro)
|
||||
if hasattr(self, "_el_key_widget"):
|
||||
self._el_key_widget.setVisible(key == "elevenlabs")
|
||||
|
||||
def _set_stt(self, key: str):
|
||||
self._sel_stt = key
|
||||
if not hasattr(self, "_stt_btns"):
|
||||
return
|
||||
for k, btn in self._stt_btns.items():
|
||||
active = (k == key)
|
||||
btn.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background: {'#00d4ff' if active else '#000d12'};
|
||||
color: {'#001a22' if active else C.TEXT_DIM};
|
||||
border: {'none' if active else f'1px solid {C.BORDER}'};
|
||||
border-radius: 3px; font-weight: {'bold' if active else 'normal'};
|
||||
}}
|
||||
QPushButton:hover {{ color: {C.TEXT}; border: 1px solid {C.BORDER_B}; }}
|
||||
""")
|
||||
# Toggle model selector widgets
|
||||
if hasattr(self, "_whisper_combo"):
|
||||
self._whisper_combo.setVisible(key == "whisper")
|
||||
if hasattr(self, "_vosk_model_input"):
|
||||
self._vosk_model_input.setVisible(key == "vosk")
|
||||
|
||||
def _set_tts(self, key: str):
|
||||
self._sel_tts = key
|
||||
if not hasattr(self, "_tts_btns"):
|
||||
return
|
||||
for k, btn in self._tts_btns.items():
|
||||
active = (k == key)
|
||||
btn.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background: {'#00d4ff' if active else '#000d12'};
|
||||
color: {'#001a22' if active else C.TEXT_DIM};
|
||||
border: {'none' if active else f'1px solid {C.BORDER}'};
|
||||
border-radius: 3px; font-weight: {'bold' if active else 'normal'};
|
||||
}}
|
||||
QPushButton:hover {{ color: {C.TEXT}; border: 1px solid {C.BORDER_B}; }}
|
||||
""")
|
||||
self._update_tts_ui(key)
|
||||
|
||||
def _submit(self):
|
||||
key = self._key_input.text().strip()
|
||||
if not key:
|
||||
self._key_input.setStyleSheet(
|
||||
self._key_input.styleSheet() +
|
||||
llm_model = self._llm_model_input.text().strip()
|
||||
if not llm_model:
|
||||
self._llm_model_input.setStyleSheet(
|
||||
self._llm_model_input.styleSheet() +
|
||||
f" QLineEdit {{ border: 1px solid {C.RED}; }}"
|
||||
)
|
||||
return
|
||||
self.done.emit(key, self._sel_os)
|
||||
|
||||
# STT model: combo for Whisper, text input for Vosk
|
||||
if self._sel_stt == "whisper":
|
||||
stt_model = self._whisper_combo.currentText()
|
||||
else:
|
||||
stt_model = self._vosk_model_input.text().strip()
|
||||
|
||||
# Voice: Kokoro uses dropdown, others use text input
|
||||
if self._sel_tts == "kokoro":
|
||||
tts_voice = self._kokoro_combo.currentData() or "af_heart"
|
||||
tts_speed = self._kokoro_speed_combo.currentData() or "1.2"
|
||||
else:
|
||||
tts_voice = self._tts_voice_input.text().strip() or "en-US-GuyNeural"
|
||||
tts_speed = "1.0"
|
||||
|
||||
cfg = {
|
||||
"stt_engine": self._sel_stt,
|
||||
"stt_model": stt_model,
|
||||
"stt_language": self._stt_lang_input.text().strip() or "auto",
|
||||
"llm_url": self._llm_url_input.text().strip() or "http://localhost:11434",
|
||||
"llm_model": llm_model,
|
||||
"tts_engine": self._sel_tts,
|
||||
"tts_voice": tts_voice,
|
||||
"tts_speed": tts_speed,
|
||||
"elevenlabs_api_key": self._el_key_input.text().strip(),
|
||||
}
|
||||
if self._sel_stt == "vosk" and stt_model:
|
||||
cfg["vosk_model_path"] = stt_model
|
||||
self.done.emit(json.dumps(cfg))
|
||||
|
||||
|
||||
class MainWindow(QMainWindow):
|
||||
@@ -990,7 +1284,7 @@ class MainWindow(QMainWindow):
|
||||
|
||||
def __init__(self, face_path: str):
|
||||
super().__init__()
|
||||
self.setWindowTitle("J.A.R.V.I.S — MARK XXXIX")
|
||||
self.setWindowTitle("J.A.R.V.I.S — MARK XL")
|
||||
self.setMinimumSize(_MIN_W, _MIN_H)
|
||||
self.resize(_DEFAULT_W, _DEFAULT_H)
|
||||
|
||||
@@ -1045,6 +1339,7 @@ class MainWindow(QMainWindow):
|
||||
self._state_sig.connect(self._apply_state)
|
||||
|
||||
self._overlay: SetupOverlay | None = None
|
||||
self._on_reconfigure_cb = None
|
||||
self._ready = self._check_config()
|
||||
if not self._ready:
|
||||
self._show_setup()
|
||||
@@ -1063,7 +1358,7 @@ class MainWindow(QMainWindow):
|
||||
def resizeEvent(self, event):
|
||||
super().resizeEvent(event)
|
||||
if self._overlay and self._overlay.isVisible():
|
||||
ow, oh = 460, 390
|
||||
ow, oh = 520, 580
|
||||
cw = self.centralWidget()
|
||||
self._overlay.setGeometry(
|
||||
(cw.width() - ow) // 2,
|
||||
@@ -1135,7 +1430,7 @@ class MainWindow(QMainWindow):
|
||||
l.setStyleSheet(f"color: {color}; background: transparent;")
|
||||
return l
|
||||
|
||||
lay.addWidget(_badge("MARK XXXIX", C.PRI_DIM))
|
||||
lay.addWidget(_badge("MARK XL", C.PRI_DIM))
|
||||
lay.addStretch()
|
||||
|
||||
mid = QVBoxLayout(); mid.setSpacing(1)
|
||||
@@ -1227,7 +1522,7 @@ class MainWindow(QMainWindow):
|
||||
for txt, col in [
|
||||
("AI CORE\nACTIVE", C.GREEN),
|
||||
("SEC\nCLEARED", C.PRI),
|
||||
("PROTOCOL\nXXXVIII", C.TEXT_DIM),
|
||||
("PROTOCOL\nXL", C.TEXT_DIM),
|
||||
]:
|
||||
lbl = QLabel(txt)
|
||||
lbl.setFont(QFont("Courier New", 7, QFont.Weight.Bold))
|
||||
@@ -1303,6 +1598,22 @@ class MainWindow(QMainWindow):
|
||||
fs_btn.clicked.connect(self._toggle_fullscreen)
|
||||
lay.addWidget(fs_btn)
|
||||
|
||||
cfg_btn = QPushButton("⚙ CONFIGURE")
|
||||
cfg_btn.setFixedHeight(26)
|
||||
cfg_btn.setFont(QFont("Courier New", 7))
|
||||
cfg_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
||||
cfg_btn.setStyleSheet(f"""
|
||||
QPushButton {{
|
||||
background: transparent; color: {C.TEXT_MED};
|
||||
border: 1px solid {C.BORDER}; border-radius: 3px;
|
||||
}}
|
||||
QPushButton:hover {{
|
||||
color: {C.ACC2}; border: 1px solid {C.ACC2};
|
||||
}}
|
||||
""")
|
||||
cfg_btn.clicked.connect(self._show_config)
|
||||
lay.addWidget(cfg_btn)
|
||||
|
||||
return w
|
||||
|
||||
def _build_input_row(self) -> QHBoxLayout:
|
||||
@@ -1349,7 +1660,7 @@ class MainWindow(QMainWindow):
|
||||
|
||||
lay.addWidget(_fl("[F4] Mute · [F11] Fullscreen"))
|
||||
lay.addStretch()
|
||||
lay.addWidget(_fl("FatihMakes Industries · MARK XXXIX · CLASSIFIED"))
|
||||
lay.addWidget(_fl("FatihMakes Industries · MARK XL · CLASSIFIED"))
|
||||
lay.addStretch()
|
||||
lay.addWidget(_fl("© FATIHMAKES", C.PRI_DIM))
|
||||
return w
|
||||
@@ -1417,14 +1728,18 @@ class MainWindow(QMainWindow):
|
||||
if not API_FILE.exists(): return False
|
||||
try:
|
||||
d = json.loads(API_FILE.read_text(encoding="utf-8"))
|
||||
return bool(d.get("gemini_api_key")) and bool(d.get("os_system"))
|
||||
return (
|
||||
bool(d.get("llm_model")) and
|
||||
bool(d.get("stt_engine")) and
|
||||
bool(d.get("tts_engine"))
|
||||
)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _show_setup(self):
|
||||
ov = SetupOverlay(self.centralWidget())
|
||||
cw = self.centralWidget()
|
||||
ow, oh = 460, 390
|
||||
ow, oh = 520, 580
|
||||
ov.setGeometry(
|
||||
(cw.width() - ow) // 2,
|
||||
(cw.height() - oh) // 2,
|
||||
@@ -1434,10 +1749,14 @@ class MainWindow(QMainWindow):
|
||||
ov.show()
|
||||
self._overlay = ov
|
||||
|
||||
def _on_setup_done(self, key: str, os_name: str):
|
||||
def _on_setup_done(self, config_json: str):
|
||||
try:
|
||||
cfg = json.loads(config_json)
|
||||
except Exception:
|
||||
cfg = {}
|
||||
os.makedirs(CONFIG_DIR, exist_ok=True)
|
||||
API_FILE.write_text(
|
||||
json.dumps({"gemini_api_key": key, "os_system": os_name}, indent=4),
|
||||
json.dumps(cfg, indent=4),
|
||||
encoding="utf-8",
|
||||
)
|
||||
self._ready = True
|
||||
@@ -1445,7 +1764,50 @@ class MainWindow(QMainWindow):
|
||||
self._overlay.hide()
|
||||
self._overlay = None
|
||||
self._apply_state("LISTENING")
|
||||
self._log.append_log(f"SYS: Initialised. OS={os_name.upper()}. JARVIS online.")
|
||||
llm = cfg.get("llm_model", "")
|
||||
stt = cfg.get("stt_engine", "")
|
||||
tts = cfg.get("tts_engine", "")
|
||||
self._log.append_log(
|
||||
f"SYS: Initialised. LLM={llm} | STT={stt} | TTS={tts}"
|
||||
)
|
||||
|
||||
def _show_config(self):
|
||||
if self._overlay and self._overlay.isVisible():
|
||||
return
|
||||
current: dict = {}
|
||||
try:
|
||||
current = json.loads(API_FILE.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
pass
|
||||
ov = SetupOverlay(self.centralWidget(), initial=current, mode="config")
|
||||
cw = self.centralWidget()
|
||||
ow, oh = 520, 600
|
||||
ov.setGeometry(
|
||||
(cw.width() - ow) // 2,
|
||||
(cw.height() - oh) // 2,
|
||||
ow, oh,
|
||||
)
|
||||
ov.done.connect(self._on_config_done)
|
||||
ov.show()
|
||||
self._overlay = ov
|
||||
|
||||
def _on_config_done(self, config_json: str):
|
||||
try:
|
||||
cfg = json.loads(config_json)
|
||||
except Exception:
|
||||
cfg = {}
|
||||
os.makedirs(CONFIG_DIR, exist_ok=True)
|
||||
API_FILE.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
||||
if self._overlay:
|
||||
self._overlay.hide()
|
||||
self._overlay = None
|
||||
llm = cfg.get("llm_model", "")
|
||||
stt = cfg.get("stt_engine", "")
|
||||
tts = cfg.get("tts_engine", "")
|
||||
self._log.append_log(f"SYS: Config updated. LLM={llm} | STT={stt} | TTS={tts}")
|
||||
if self._on_reconfigure_cb:
|
||||
self._on_reconfigure_cb(cfg)
|
||||
|
||||
|
||||
class _RootShim:
|
||||
def __init__(self, app: QApplication):
|
||||
@@ -1485,6 +1847,14 @@ class JarvisUI:
|
||||
def on_text_command(self, cb):
|
||||
self._win.on_text_command = cb
|
||||
|
||||
@property
|
||||
def on_reconfigure(self):
|
||||
return self._win._on_reconfigure_cb
|
||||
|
||||
@on_reconfigure.setter
|
||||
def on_reconfigure(self, cb):
|
||||
self._win._on_reconfigure_cb = cb
|
||||
|
||||
def set_state(self, state: str):
|
||||
self._win._state_sig.emit(state)
|
||||
|
||||
|
||||
Reference in new issue
Block a user