From 502309ad249b148a7c4be2657a3c7d8e8b932810 Mon Sep 17 00:00:00 2001 From: FatihMakes Date: Sat, 6 Jun 2026 17:41:38 +0300 Subject: [PATCH] Add files via upload --- actions/code_helper.py | 201 ++-- actions/computer_control.py | 48 +- actions/computer_settings.py | 42 +- actions/desktop.py | 55 +- actions/dev_agent.py | 181 +-- actions/file_processor.py | 19 +- actions/flight_finder.py | 41 +- actions/screen_processor.py | 714 +++++------- actions/web_search.py | 258 ++--- actions/youtube_video.py | 33 +- agent/error_handler.py | 346 +++--- agent/executor.py | 790 +++++++------ agent/planner.py | 483 ++++---- config/__init__.py | 43 +- core/__init__.py | 1 + core/installer.py | 137 +++ core/llm_client.py | 308 +++++ core/prompt.txt | 3 +- core/stt.py | 59 + core/tts.py | 276 +++++ main.py | 2072 +++++++++++++++++++--------------- memory/config_manager.py | 105 +- readme.md | 240 ++-- requirements.txt | 78 +- ui.py | 570 ++++++++-- 25 files changed, 4097 insertions(+), 3006 deletions(-) create mode 100644 core/__init__.py create mode 100644 core/installer.py create mode 100644 core/llm_client.py create mode 100644 core/stt.py create mode 100644 core/tts.py diff --git a/actions/code_helper.py b/actions/code_helper.py index c163537..6cfe81f 100644 --- a/actions/code_helper.py +++ b/actions/code_helper.py @@ -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: diff --git a/actions/computer_control.py b/actions/computer_control.py index 3d9cd0a..92aa2d1 100644 --- a/actions/computer_control.py +++ b/actions/computer_control.py @@ -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 diff --git a/actions/computer_settings.py b/actions/computer_settings.py index 2653b78..12649d9 100644 --- a/actions/computer_settings.py +++ b/actions/computer_settings.py @@ -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}") diff --git a/actions/desktop.py b/actions/desktop.py index bb63774..495eeca 100644 --- a/actions/desktop.py +++ b/actions/desktop.py @@ -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() diff --git a/actions/dev_agent.py b/actions/dev_agent.py index 67a10fe..871f1b6 100644 --- a/actions/dev_agent.py +++ b/actions/dev_agent.py @@ -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 diff --git a/actions/file_processor.py b/actions/file_processor.py index 84e51cb..c0654c0 100644 --- a/actions/file_processor.py +++ b/actions/file_processor.py @@ -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: diff --git a/actions/flight_finder.py b/actions/flight_finder.py index ea6ba30..c6e4b8a 100644 --- a/actions/flight_finder.py +++ b/actions/flight_finder.py @@ -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( diff --git a/actions/screen_processor.py b/actions/screen_processor.py index 84db42e..23c388f 100644 --- a/actions/screen_processor.py +++ b/actions/screen_processor.py @@ -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.") \ No newline at end of file +""" +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 diff --git a/actions/web_search.py b/actions/web_search.py index 22a9109..192d698 100644 --- a/actions/web_search.py +++ b/actions/web_search.py @@ -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}" \ No newline at end of file +# 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}" diff --git a/actions/youtube_video.py b/actions/youtube_video.py index bb47461..4f56bfa 100644 --- a/actions/youtube_video.py +++ b/actions/youtube_video.py @@ -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: diff --git a/agent/error_handler.py b/agent/error_handler.py index 462b4e4..c122068 100644 --- a/agent/error_handler.py +++ b/agent/error_handler.py @@ -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) - } \ No newline at end of file +""" +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), + } diff --git a/agent/executor.py b/agent/executor.py index 6a33a67..b2dcfd9 100644 --- a/agent/executor.py +++ b/agent/executor.py @@ -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 \ No newline at end of file +""" +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 diff --git a/agent/planner.py b/agent/planner.py index 62c2949..5613c13 100644 --- a/agent/planner.py +++ b/agent/planner.py @@ -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) \ No newline at end of file +""" +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) diff --git a/config/__init__.py b/config/__init__.py index c917739..13f1a5f 100644 --- a/config/__init__.py +++ b/config/__init__.py @@ -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" \ No newline at end of file +# 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" diff --git a/core/__init__.py b/core/__init__.py new file mode 100644 index 0000000..97daee7 --- /dev/null +++ b/core/__init__.py @@ -0,0 +1 @@ +# core package diff --git a/core/installer.py b/core/installer.py new file mode 100644 index 0000000..ad5c1a2 --- /dev/null +++ b/core/installer.py @@ -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 ✓") diff --git a/core/llm_client.py b/core/llm_client.py new file mode 100644 index 0000000..e227d1f --- /dev/null +++ b/core/llm_client.py @@ -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}") diff --git a/core/prompt.txt b/core/prompt.txt index b66d176..5bdb91b 100644 --- a/core/prompt.txt +++ b/core/prompt.txt @@ -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. \ No newline at end of file diff --git a/core/stt.py b/core/stt.py new file mode 100644 index 0000000..710f1e6 --- /dev/null +++ b/core/stt.py @@ -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 diff --git a/core/tts.py b/core/tts.py new file mode 100644 index 0000000..3c00c89 --- /dev/null +++ b/core/tts.py @@ -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) diff --git a/main.py b/main.py index 813b9fd..fd94cb5 100644 --- a/main.py +++ b/main.py @@ -1,881 +1,1191 @@ -import asyncio -import re -import threading -import json -import sys -import traceback -from pathlib import Path - -import sounddevice as sd -from google import genai -from google.genai import types -from ui import JarvisUI -from memory.memory_manager import ( - load_memory, update_memory, format_memory_for_prompt, -) - -from actions.file_processor import file_processor -from actions.flight_finder import flight_finder -from actions.open_app import open_app -from actions.weather_report import weather_action -from actions.send_message import send_message -from actions.reminder import reminder -from actions.computer_settings import computer_settings -from actions.screen_processor import screen_process -from actions.youtube_video import youtube_video -from actions.desktop import desktop_control -from actions.browser_control import browser_control -from actions.file_controller import file_controller -from actions.code_helper import code_helper -from actions.dev_agent import dev_agent -from actions.web_search import web_search as web_search_action -from actions.computer_control import computer_control -from actions.game_updater import game_updater - - -def get_base_dir(): - if getattr(sys, "frozen", False): - return Path(sys.executable).parent - return Path(__file__).resolve().parent - - -BASE_DIR = get_base_dir() -API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json" -PROMPT_PATH = BASE_DIR / "core" / "prompt.txt" -LIVE_MODEL = "models/gemini-2.5-flash-native-audio-preview-12-2025" -CHANNELS = 1 -SEND_SAMPLE_RATE = 16000 -RECEIVE_SAMPLE_RATE = 24000 -CHUNK_SIZE = 1024 - -def _get_api_key() -> str: - with open(API_CONFIG_PATH, "r", encoding="utf-8") as f: - return json.load(f)["gemini_api_key"] - - -def _load_system_prompt() -> str: - try: - return PROMPT_PATH.read_text(encoding="utf-8") - except Exception: - return ( - "You are JARVIS, Tony Stark's AI assistant. " - "Be concise, direct, and always use the provided tools to complete tasks. " - "Never simulate or guess results — always call the appropriate tool." - ) - -_CTRL_RE = re.compile(r"", re.IGNORECASE) - -def _clean_transcript(text: str) -> str: - text = _CTRL_RE.sub("", text) - text = re.sub(r"[\x00-\x08\x0b-\x1f]", "", text) - return text.strip() - -TOOL_DECLARATIONS = [ - { - "name": "open_app", - "description": ( - "Opens any application on the computer. " - "Use this whenever the user asks to open, launch, or start any app, " - "website, or program. Always call this tool — never just say you opened it." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "app_name": { - "type": "STRING", - "description": "Exact name of the application (e.g. 'WhatsApp', 'Chrome', 'Spotify')" - } - }, - "required": ["app_name"] - } - }, - { - "name": "web_search", - "description": "Searches the web for any information.", - "parameters": { - "type": "OBJECT", - "properties": { - "query": {"type": "STRING", "description": "Search query"}, - "mode": {"type": "STRING", "description": "search (default) or compare"}, - "items": {"type": "ARRAY", "items": {"type": "STRING"}, "description": "Items to compare"}, - "aspect": {"type": "STRING", "description": "price | specs | reviews"} - }, - "required": ["query"] - } - }, - { - "name": "weather_report", - "description": "Gives the weather report to user", - "parameters": { - "type": "OBJECT", - "properties": { - "city": {"type": "STRING", "description": "City name"} - }, - "required": ["city"] - } - }, - { - "name": "send_message", - "description": "Sends a text message via WhatsApp, Telegram, or other messaging platform.", - "parameters": { - "type": "OBJECT", - "properties": { - "receiver": {"type": "STRING", "description": "Recipient contact name"}, - "message_text": {"type": "STRING", "description": "The message to send"}, - "platform": {"type": "STRING", "description": "Platform: WhatsApp, Telegram, etc."} - }, - "required": ["receiver", "message_text", "platform"] - } - }, - { - "name": "reminder", - "description": "Sets a timed reminder using Task Scheduler.", - "parameters": { - "type": "OBJECT", - "properties": { - "date": {"type": "STRING", "description": "Date in YYYY-MM-DD format"}, - "time": {"type": "STRING", "description": "Time in HH:MM format (24h)"}, - "message": {"type": "STRING", "description": "Reminder message text"} - }, - "required": ["date", "time", "message"] - } - }, - { - "name": "youtube_video", - "description": ( - "Controls YouTube. Use for: playing videos, summarizing a video's content, " - "getting video info, or showing trending videos." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "play | summarize | get_info | trending (default: play)"}, - "query": {"type": "STRING", "description": "Search query for play action"}, - "save": {"type": "BOOLEAN", "description": "Save summary to Notepad (summarize only)"}, - "region": {"type": "STRING", "description": "Country code for trending e.g. TR, US"}, - "url": {"type": "STRING", "description": "Video URL for get_info action"}, - }, - "required": [] - } - }, - { - "name": "screen_process", - "description": ( - "Captures and analyzes the screen or webcam image. " - "MUST be called when user asks what is on screen, what you see, " - "analyze my screen, look at camera, etc. " - "You have NO visual ability without this tool. " - "After calling this tool, stay SILENT — the vision module speaks directly." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "angle": {"type": "STRING", "description": "'screen' to capture display, 'camera' for webcam. Default: 'screen'"}, - "text": {"type": "STRING", "description": "The question or instruction about the captured image"} - }, - "required": ["text"] - } - }, - { - "name": "computer_settings", - "description": ( - "Controls the computer: volume, brightness, window management, keyboard shortcuts, " - "typing text on screen, closing apps, fullscreen, dark mode, WiFi, restart, shutdown, " - "scrolling, tab management, zoom, screenshots, lock screen, refresh/reload page. " - "Use for ANY single computer control command. NEVER route to agent_task." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "The action to perform"}, - "description": {"type": "STRING", "description": "Natural language description of what to do"}, - "value": {"type": "STRING", "description": "Optional value: volume level, text to type, etc."} - }, - "required": [] - } - }, - { - "name": "browser_control", - "description": ( - "Controls any web browser. Use for: opening websites, searching the web, " - "clicking elements, filling forms, scrolling, screenshots, navigation, any web-based task. " - "Always pass the 'browser' parameter when the user specifies a browser (e.g. 'open in Edge', " - "'use Firefox', 'open Chrome'). Multiple browsers can run simultaneously." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "go_to | search | click | type | scroll | fill_form | smart_click | smart_type | get_text | get_url | press | new_tab | close_tab | screenshot | back | forward | reload | switch | list_browsers | close | close_all"}, - "browser": {"type": "STRING", "description": "Target browser: chrome | edge | firefox | opera | operagx | brave | vivaldi | safari. Omit to use the currently active browser."}, - "url": {"type": "STRING", "description": "URL for go_to / new_tab action"}, - "query": {"type": "STRING", "description": "Search query for search action"}, - "engine": {"type": "STRING", "description": "Search engine: google | bing | duckduckgo | yandex (default: google)"}, - "selector": {"type": "STRING", "description": "CSS selector for click/type"}, - "text": {"type": "STRING", "description": "Text to click or type"}, - "description": {"type": "STRING", "description": "Element description for smart_click/smart_type"}, - "direction": {"type": "STRING", "description": "up | down for scroll"}, - "amount": {"type": "INTEGER", "description": "Scroll amount in pixels (default: 500)"}, - "key": {"type": "STRING", "description": "Key name for press action (e.g. Enter, Escape, F5)"}, - "path": {"type": "STRING", "description": "Save path for screenshot"}, - "incognito": {"type": "BOOLEAN", "description": "Open in private/incognito mode"}, - "clear_first": {"type": "BOOLEAN", "description": "Clear field before typing (default: true)"}, - }, - "required": ["action"] - } - }, - { - "name": "file_controller", - "description": "Manages files and folders: list, create, delete, move, copy, rename, read, write, find, disk usage.", - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "list | create_file | create_folder | delete | move | copy | rename | read | write | find | largest | disk_usage | organize_desktop | info"}, - "path": {"type": "STRING", "description": "File/folder path or shortcut: desktop, downloads, documents, home"}, - "destination": {"type": "STRING", "description": "Destination path for move/copy"}, - "new_name": {"type": "STRING", "description": "New name for rename"}, - "content": {"type": "STRING", "description": "Content for create_file/write"}, - "name": {"type": "STRING", "description": "File name to search for"}, - "extension": {"type": "STRING", "description": "File extension to search (e.g. .pdf)"}, - "count": {"type": "INTEGER", "description": "Number of results for largest"}, - }, - "required": ["action"] - } - }, - { - "name": "desktop_control", - "description": "Controls the desktop: wallpaper, organize, clean, list, stats.", - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "wallpaper | wallpaper_url | organize | clean | list | stats | task"}, - "path": {"type": "STRING", "description": "Image path for wallpaper"}, - "url": {"type": "STRING", "description": "Image URL for wallpaper_url"}, - "mode": {"type": "STRING", "description": "by_type or by_date for organize"}, - "task": {"type": "STRING", "description": "Natural language desktop task"}, - }, - "required": ["action"] - } - }, - { - "name": "code_helper", - "description": "Writes, edits, explains, runs, or builds code files.", - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "write | edit | explain | run | build | auto (default: auto)"}, - "description": {"type": "STRING", "description": "What the code should do or what change to make"}, - "language": {"type": "STRING", "description": "Programming language (default: python)"}, - "output_path": {"type": "STRING", "description": "Where to save the file"}, - "file_path": {"type": "STRING", "description": "Path to existing file for edit/explain/run/build"}, - "code": {"type": "STRING", "description": "Raw code string for explain"}, - "args": {"type": "STRING", "description": "CLI arguments for run/build"}, - "timeout": {"type": "INTEGER", "description": "Execution timeout in seconds (default: 30)"}, - }, - "required": ["action"] - } - }, - { - "name": "dev_agent", - "description": "Builds complete multi-file projects from scratch: plans, writes files, installs deps, opens VSCode, runs and fixes errors.", - "parameters": { - "type": "OBJECT", - "properties": { - "description": {"type": "STRING", "description": "What the project should do"}, - "language": {"type": "STRING", "description": "Programming language (default: python)"}, - "project_name": {"type": "STRING", "description": "Optional project folder name"}, - "timeout": {"type": "INTEGER", "description": "Run timeout in seconds (default: 30)"}, - }, - "required": ["description"] - } - }, - { - "name": "agent_task", - "description": ( - "Executes complex multi-step tasks requiring multiple different tools. " - "Examples: 'research X and save to file', 'find and organize files'. " - "DO NOT use for single commands. NEVER use for Steam/Epic — use game_updater." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "goal": {"type": "STRING", "description": "Complete description of what to accomplish"}, - "priority": {"type": "STRING", "description": "low | normal | high (default: normal)"} - }, - "required": ["goal"] - } - }, - { - "name": "computer_control", - "description": "Direct computer control: type, click, hotkeys, scroll, move mouse, screenshots, find elements on screen.", - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "type | smart_type | click | double_click | right_click | hotkey | press | scroll | move | copy | paste | screenshot | wait | clear_field | focus_window | screen_find | screen_click | random_data | user_data"}, - "text": {"type": "STRING", "description": "Text to type or paste"}, - "x": {"type": "INTEGER", "description": "X coordinate"}, - "y": {"type": "INTEGER", "description": "Y coordinate"}, - "keys": {"type": "STRING", "description": "Key combination e.g. 'ctrl+c'"}, - "key": {"type": "STRING", "description": "Single key e.g. 'enter'"}, - "direction": {"type": "STRING", "description": "up | down | left | right"}, - "amount": {"type": "INTEGER", "description": "Scroll amount (default: 3)"}, - "seconds": {"type": "NUMBER", "description": "Seconds to wait"}, - "title": {"type": "STRING", "description": "Window title for focus_window"}, - "description": {"type": "STRING", "description": "Element description for screen_find/screen_click"}, - "type": {"type": "STRING", "description": "Data type for random_data"}, - "field": {"type": "STRING", "description": "Field for user_data: name|email|city"}, - "clear_first": {"type": "BOOLEAN", "description": "Clear field before typing (default: true)"}, - "path": {"type": "STRING", "description": "Save path for screenshot"}, - }, - "required": ["action"] - } - }, - { - "name": "game_updater", - "description": ( - "THE ONLY tool for ANY Steam or Epic Games request. " - "Use for: installing, downloading, updating games, listing installed games, " - "checking download status, scheduling updates. " - "ALWAYS call directly for any Steam/Epic/game request. " - "NEVER use agent_task, browser_control, or web_search for Steam/Epic." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "action": {"type": "STRING", "description": "update | install | list | download_status | schedule | cancel_schedule | schedule_status (default: update)"}, - "platform": {"type": "STRING", "description": "steam | epic | both (default: both)"}, - "game_name": {"type": "STRING", "description": "Game name (partial match supported)"}, - "app_id": {"type": "STRING", "description": "Steam AppID for install (optional)"}, - "hour": {"type": "INTEGER", "description": "Hour for scheduled update 0-23 (default: 3)"}, - "minute": {"type": "INTEGER", "description": "Minute for scheduled update 0-59 (default: 0)"}, - "shutdown_when_done": {"type": "BOOLEAN", "description": "Shut down PC when download finishes"}, - }, - "required": [] - } - }, - { - "name": "flight_finder", - "description": "Searches Google Flights and speaks the best options.", - "parameters": { - "type": "OBJECT", - "properties": { - "origin": {"type": "STRING", "description": "Departure city or airport code"}, - "destination": {"type": "STRING", "description": "Arrival city or airport code"}, - "date": {"type": "STRING", "description": "Departure date (any format)"}, - "return_date": {"type": "STRING", "description": "Return date for round trips"}, - "passengers": {"type": "INTEGER", "description": "Number of passengers (default: 1)"}, - "cabin": {"type": "STRING", "description": "economy | premium | business | first"}, - "save": {"type": "BOOLEAN", "description": "Save results to Notepad"}, - }, - "required": ["origin", "destination", "date"] - } - }, - { - "name": "shutdown_jarvis", - "description": ( - "Shuts down the assistant completely. " - "Call this when the user expresses intent to end the conversation, " - "close the assistant, say goodbye, or stop Jarvis. " - "The user can say this in ANY language." - ), - "parameters": { - "type": "OBJECT", - "properties": {}, - } - }, - { - "name": "file_processor", - "description": ( - "Processes any file that the user has uploaded or dropped onto the interface. " - "Use this when the user refers to an uploaded file and wants an action on it. " - "Supports: images (describe/ocr/resize/compress/convert), " - "PDFs (summarize/extract_text/to_word), " - "Word docs & text files (summarize/fix/reformat/translate), " - "CSV/Excel (analyze/stats/filter/sort/convert), " - "JSON/XML (validate/format/analyze), " - "code files (explain/review/fix/optimize/run/document/test), " - "audio (transcribe/trim/convert/info), " - "video (trim/extract_audio/extract_frame/compress/transcribe/info), " - "archives (list/extract), " - "presentations (summarize/extract_text). " - "ALWAYS call this tool when a file has been uploaded and the user gives a command about it. " - "If the user's command is ambiguous, pick the most logical action for that file type." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "file_path": { - "type": "STRING", - "description": "Full path to the uploaded file. Leave empty to use the currently uploaded file." - }, - "action": { - "type": "STRING", - "description": ( - "What to do with the file. Examples by type:\n" - "image: describe | ocr | resize | compress | convert | info\n" - "pdf: summarize | extract_text | to_word | info\n" - "docx/txt: summarize | fix | reformat | translate_hint | word_count | to_bullet\n" - "csv/excel: analyze | stats | filter | sort | convert | info\n" - "json: validate | format | analyze | to_csv\n" - "code: explain | review | fix | optimize | run | document | test\n" - "audio: transcribe | trim | convert | info\n" - "video: trim | extract_audio | extract_frame | compress | transcribe | info | convert\n" - "archive: list | extract\n" - "pptx: summarize | extract_text | analyze" - ) - }, - "instruction": { - "type": "STRING", - "description": "Free-form instruction if action doesn't cover it. E.g. 'translate this to Turkish', 'find all email addresses'" - }, - "format": { - "type": "STRING", - "description": "Target format for conversion. E.g. 'mp3', 'pdf', 'csv', 'png'" - }, - "width": {"type": "INTEGER", "description": "Target width for image resize"}, - "height": {"type": "INTEGER", "description": "Target height for image resize"}, - "scale": {"type": "NUMBER", "description": "Scale factor for image resize (e.g. 0.5)"}, - "quality": {"type": "INTEGER", "description": "Quality 1-100 for image/video compress"}, - "start": {"type": "STRING", "description": "Start time for trim: seconds or HH:MM:SS"}, - "end": {"type": "STRING", "description": "End time for trim: seconds or HH:MM:SS"}, - "timestamp": {"type": "STRING", "description": "Timestamp for video frame extraction HH:MM:SS"}, - "column": {"type": "STRING", "description": "Column name for CSV filter/sort"}, - "value": {"type": "STRING", "description": "Filter value for CSV filter"}, - "condition": {"type": "STRING", "description": "Filter condition: equals|contains|gt|lt"}, - "ascending": {"type": "BOOLEAN", "description": "Sort order for CSV sort (default: true)"}, - "save": {"type": "BOOLEAN", "description": "Save result to file (default: true)"}, - "destination": {"type": "STRING", "description": "Output folder for archive extract"}, - }, - "required": [] - } -}, - { - "name": "save_memory", - "description": ( - "Save an important personal fact about the user to long-term memory. " - "Call this silently whenever the user reveals something worth remembering: " - "name, age, city, job, preferences, hobbies, relationships, projects, or future plans. " - "Do NOT call for: weather, reminders, searches, or one-time commands. " - "Do NOT announce that you are saving — just call it silently. " - "Values must be in English regardless of the conversation language." - ), - "parameters": { - "type": "OBJECT", - "properties": { - "category": { - "type": "STRING", - "description": ( - "identity — name, age, birthday, city, job, language, nationality | " - "preferences — favorite food/color/music/film/game/sport, hobbies | " - "projects — active projects, goals, things being built | " - "relationships — friends, family, partner, colleagues | " - "wishes — future plans, things to buy, travel dreams | " - "notes — habits, schedule, anything else worth remembering" - ) - }, - "key": {"type": "STRING", "description": "Short snake_case key (e.g. name, favorite_food, sister_name)"}, - "value": {"type": "STRING", "description": "Concise value in English (e.g. Fatih, pizza, older sister)"}, - }, - "required": ["category", "key", "value"] - } - }, -] - -class JarvisLive: - - def __init__(self, ui: JarvisUI): - self.ui = ui - self.session = None - self.audio_in_queue = None - self.out_queue = None - self._loop = None - self._is_speaking = False - self._speaking_lock = threading.Lock() - self.ui.on_text_command = self._on_text_command - self._turn_done_event: asyncio.Event | None = None - - def _on_text_command(self, text: str): - if not self._loop or not self.session: - return - asyncio.run_coroutine_threadsafe( - self.session.send_client_content( - turns={"parts": [{"text": text}]}, - turn_complete=True - ), - self._loop - ) - - def set_speaking(self, value: bool): - with self._speaking_lock: - self._is_speaking = value - if value: - self.ui.set_state("SPEAKING") - elif not self.ui.muted: - self.ui.set_state("LISTENING") - - def speak(self, text: str): - if not self._loop or not self.session: - return - asyncio.run_coroutine_threadsafe( - self.session.send_client_content( - turns={"parts": [{"text": text}]}, - turn_complete=True - ), - self._loop - ) - - def speak_error(self, tool_name: str, error: str): - short = str(error)[:120] - self.ui.write_log(f"ERR: {tool_name} — {short}") - self.speak(f"Sir, {tool_name} encountered an error. {short}") - - def _build_config(self) -> types.LiveConnectConfig: - from datetime import datetime - - memory = load_memory() - mem_str = format_memory_for_prompt(memory) - sys_prompt = _load_system_prompt() - - now = datetime.now() - time_str = now.strftime("%A, %B %d, %Y — %I:%M %p") - time_ctx = ( - f"[CURRENT DATE & TIME]\n" - f"Right now it is: {time_str}\n" - f"Use this to calculate exact times for reminders.\n\n" - ) - - parts = [time_ctx] - if mem_str: - parts.append(mem_str) - parts.append(sys_prompt) - - return types.LiveConnectConfig( - response_modalities=["AUDIO"], - output_audio_transcription={}, - input_audio_transcription={}, - system_instruction="\n".join(parts), - tools=[{"function_declarations": TOOL_DECLARATIONS}], - session_resumption=types.SessionResumptionConfig(), - speech_config=types.SpeechConfig( - voice_config=types.VoiceConfig( - prebuilt_voice_config=types.PrebuiltVoiceConfig( - voice_name="Charon" - ) - ) - ), - ) - - async def _execute_tool(self, fc) -> types.FunctionResponse: - name = fc.name - args = dict(fc.args or {}) - - print(f"[JARVIS] 🔧 {name} {args}") - self.ui.set_state("THINKING") - - if name == "save_memory": - category = args.get("category", "notes") - key = args.get("key", "") - value = args.get("value", "") - if key and value: - update_memory({category: {key: {"value": value}}}) - print(f"[Memory] 💾 save_memory: {category}/{key} = {value}") - if not self.ui.muted: - self.ui.set_state("LISTENING") - return types.FunctionResponse( - id=fc.id, name=name, - response={"result": "ok", "silent": True} - ) - - loop = asyncio.get_event_loop() - result = "Done." - - try: - if name == "open_app": - r = await loop.run_in_executor(None, lambda: open_app(parameters=args, response=None, player=self.ui)) - result = r or f"Opened {args.get('app_name')}." - - elif name == "weather_report": - r = await loop.run_in_executor(None, lambda: weather_action(parameters=args, player=self.ui)) - result = r or "Weather delivered." - - elif name == "browser_control": - r = await loop.run_in_executor(None, lambda: browser_control(parameters=args, player=self.ui)) - result = r or "Done." - - elif name == "file_controller": - r = await loop.run_in_executor(None, lambda: file_controller(parameters=args, player=self.ui)) - result = r or "Done." - - elif name == "send_message": - r = await loop.run_in_executor(None, lambda: send_message(parameters=args, response=None, player=self.ui, session_memory=None)) - result = r or f"Message sent to {args.get('receiver')}." - - elif name == "reminder": - r = await loop.run_in_executor(None, lambda: reminder(parameters=args, response=None, player=self.ui)) - result = r or "Reminder set." - - elif name == "youtube_video": - r = await loop.run_in_executor(None, lambda: youtube_video(parameters=args, response=None, player=self.ui)) - result = r or "Done." - - elif name == "screen_process": - threading.Thread( - target=screen_process, - kwargs={"parameters": args, "response": None, - "player": self.ui, "session_memory": None}, - daemon=True - ).start() - result = "Vision module activated. Stay completely silent — vision module will speak directly." - - elif name == "computer_settings": - r = await loop.run_in_executor(None, lambda: computer_settings(parameters=args, response=None, player=self.ui)) - result = r or "Done." - - elif name == "desktop_control": - r = await loop.run_in_executor(None, lambda: desktop_control(parameters=args, player=self.ui)) - result = r or "Done." - - elif name == "code_helper": - r = await loop.run_in_executor(None, lambda: code_helper(parameters=args, player=self.ui, speak=self.speak)) - result = r or "Done." - - elif name == "dev_agent": - r = await loop.run_in_executor(None, lambda: dev_agent(parameters=args, player=self.ui, speak=self.speak)) - result = r or "Done." - - elif name == "agent_task": - from agent.task_queue import get_queue, TaskPriority - priority_map = {"low": TaskPriority.LOW, "normal": TaskPriority.NORMAL, "high": TaskPriority.HIGH} - priority = priority_map.get(args.get("priority", "normal").lower(), TaskPriority.NORMAL) - task_id = get_queue().submit(goal=args.get("goal", ""), priority=priority, speak=self.speak) - result = f"Task started (ID: {task_id})." - - elif name == "web_search": - r = await loop.run_in_executor(None, lambda: web_search_action(parameters=args, player=self.ui)) - result = r or "Done." - elif name == "file_processor": - if not args.get("file_path") and self.ui.current_file: - args["file_path"] = self.ui.current_file - r = await loop.run_in_executor( - None, - lambda: file_processor(parameters=args, player=self.ui, speak=self.speak) - ) - result = r or "Done." - - elif name == "computer_control": - r = await loop.run_in_executor(None, lambda: computer_control(parameters=args, player=self.ui)) - result = r or "Done." - - elif name == "game_updater": - r = await loop.run_in_executor(None, lambda: game_updater(parameters=args, player=self.ui, speak=self.speak)) - result = r or "Done." - - elif name == "flight_finder": - r = await loop.run_in_executor(None, lambda: flight_finder(parameters=args, player=self.ui)) - result = r or "Done." - - elif name == "shutdown_jarvis": - self.ui.write_log("SYS: Shutdown requested.") - self.speak("Goodbye, sir.") - def _shutdown(): - import time, os - time.sleep(1) - os._exit(0) - threading.Thread(target=_shutdown, daemon=True).start() - - else: - result = f"Unknown tool: {name}" - - except Exception as e: - result = f"Tool '{name}' failed: {e}" - traceback.print_exc() - self.speak_error(name, e) - - if not self.ui.muted: - self.ui.set_state("LISTENING") - - print(f"[JARVIS] 📤 {name} → {str(result)[:80]}") - return types.FunctionResponse( - id=fc.id, name=name, - response={"result": result} - ) - - async def _send_realtime(self): - while True: - msg = await self.out_queue.get() - await self.session.send_realtime_input(media=msg) - - async def _listen_audio(self): - print("[JARVIS] 🎤 Mic started") - loop = asyncio.get_event_loop() - - def callback(indata, frames, time_info, status): - with self._speaking_lock: - jarvis_speaking = self._is_speaking - if not jarvis_speaking and not self.ui.muted: - data = indata.tobytes() - loop.call_soon_threadsafe( - self.out_queue.put_nowait, - {"data": data, "mime_type": "audio/pcm"} - ) - - try: - with sd.InputStream( - samplerate=SEND_SAMPLE_RATE, - channels=CHANNELS, - dtype="int16", - blocksize=CHUNK_SIZE, - callback=callback, - ): - print("[JARVIS] 🎤 Mic stream open") - while True: - await asyncio.sleep(0.1) - except Exception as e: - print(f"[JARVIS] ❌ Mic: {e}") - raise - - async def _receive_audio(self): - print("[JARVIS] 👂 Recv started") - out_buf, in_buf = [], [] - - try: - while True: - async for response in self.session.receive(): - - if response.data: - if self._turn_done_event and self._turn_done_event.is_set(): - self._turn_done_event.clear() - self.audio_in_queue.put_nowait(response.data) - - if response.server_content: - sc = response.server_content - - if sc.output_transcription and sc.output_transcription.text: - txt = _clean_transcript(sc.output_transcription.text) - if txt: - out_buf.append(txt) - - if sc.input_transcription and sc.input_transcription.text: - txt = _clean_transcript(sc.input_transcription.text) - if txt: - in_buf.append(txt) - - if sc.turn_complete: - if self._turn_done_event: - self._turn_done_event.set() - - full_in = " ".join(in_buf).strip() - if full_in: - self.ui.write_log(f"You: {full_in}") - in_buf = [] - - full_out = " ".join(out_buf).strip() - if full_out: - self.ui.write_log(f"Jarvis: {full_out}") - out_buf = [] - - if response.tool_call: - fn_responses = [] - for fc in response.tool_call.function_calls: - print(f"[JARVIS] 📞 {fc.name}") - fr = await self._execute_tool(fc) - fn_responses.append(fr) - await self.session.send_tool_response( - function_responses=fn_responses - ) - except Exception as e: - print(f"[JARVIS] ❌ Recv: {e}") - traceback.print_exc() - raise - - async def _play_audio(self): - print("[JARVIS] 🔊 Play started") - - stream = sd.RawOutputStream( - samplerate=RECEIVE_SAMPLE_RATE, - channels=CHANNELS, - dtype="int16", - blocksize=CHUNK_SIZE, - ) - stream.start() - - try: - while True: - try: - chunk = await asyncio.wait_for( - self.audio_in_queue.get(), - timeout=0.1 - ) - except asyncio.TimeoutError: - if ( - self._turn_done_event - and self._turn_done_event.is_set() - and self.audio_in_queue.empty() - ): - self.set_speaking(False) - self._turn_done_event.clear() - continue - self.set_speaking(True) - await asyncio.to_thread(stream.write, chunk) - except Exception as e: - print(f"[JARVIS] ❌ Play: {e}") - raise - finally: - self.set_speaking(False) - stream.stop() - stream.close() - - async def run(self): - client = genai.Client( - api_key=_get_api_key(), - http_options={"api_version": "v1beta"} - ) - - while True: - try: - print("[JARVIS] 🔌 Connecting...") - self.ui.set_state("THINKING") - config = self._build_config() - - async with ( - client.aio.live.connect(model=LIVE_MODEL, config=config) as session, - asyncio.TaskGroup() as tg, - ): - self.session = session - self._loop = asyncio.get_event_loop() - self.audio_in_queue = asyncio.Queue() - self.out_queue = asyncio.Queue(maxsize=10) - self._turn_done_event = asyncio.Event() - - print("[JARVIS] ✅ Connected.") - self.ui.set_state("LISTENING") - self.ui.write_log("SYS: JARVIS online.") - - tg.create_task(self._send_realtime()) - tg.create_task(self._listen_audio()) - tg.create_task(self._receive_audio()) - tg.create_task(self._play_audio()) - - except Exception as e: - print(f"[JARVIS] ⚠️ {e}") - traceback.print_exc() - self.set_speaking(False) - self.ui.set_state("THINKING") - print("[JARVIS] 🔄 Reconnecting in 3s...") - await asyncio.sleep(3) - -def main(): - ui = JarvisUI("face.png") - - def runner(): - ui.wait_for_api_key() - jarvis = JarvisLive(ui) - try: - asyncio.run(jarvis.run()) - except KeyboardInterrupt: - print("\n🔴 Shutting down...") - - threading.Thread(target=runner, daemon=True).start() - ui.root.mainloop() - -if __name__ == "__main__": - main() \ No newline at end of file +""" +MARK XL — Local LLM Edition +STT (Whisper / Vosk) + Ollama LLM + TTS (EdgeTTS / Kokoro / ElevenLabs) +All Gemini / Google-AI dependencies removed. +""" +# ── Bootstrap: auto-install base UI packages before anything else ────────── +# Uses only stdlib so it works even on a completely fresh Python install. +import importlib.util as _ilu +import os as _os +import subprocess as _sp +import sys as _sys + +_BASE_PKGS = [ + ("PyQt6", "PyQt6"), + ("psutil", "psutil"), + ("numpy", "numpy"), + ("sounddevice", "sounddevice"), + ("PIL", "pillow"), + ("requests", "requests"), +] + +def _bootstrap() -> None: + need = [pkg for mod, pkg in _BASE_PKGS if _ilu.find_spec(mod) is None] + if not need: + return + print(f"\n[MARK XL] First-run setup — installing: {', '.join(need)}") + print("[MARK XL] This happens only once.\n") + _sp.run([_sys.executable, "-m", "pip", "install", *need], check=True) + print("\n[MARK XL] Base packages ready — restarting…\n") + # Replace current process with a fresh one (picks up newly installed packages) + _os.execv(_sys.executable, [_sys.executable] + _sys.argv) + +_bootstrap() +# ─────────────────────────────────────────────────────────────────────────── + +import json +import queue +import re +import sys +import threading +import traceback +from datetime import datetime +from pathlib import Path + +import numpy as np +import sounddevice as sd + +from ui import JarvisUI +from memory.memory_manager import load_memory, update_memory, format_memory_for_prompt +from core.llm_client import call_llm, call_llm_stream, get_llm_settings + +from actions.file_processor import file_processor +from actions.flight_finder import flight_finder +from actions.open_app import open_app +from actions.weather_report import weather_action +from actions.send_message import send_message +from actions.reminder import reminder +from actions.computer_settings import computer_settings +from actions.screen_processor import screen_process +from actions.youtube_video import youtube_video +from actions.desktop import desktop_control +from actions.browser_control import browser_control +from actions.file_controller import file_controller +from actions.code_helper import code_helper +from actions.dev_agent import dev_agent +from actions.web_search import web_search as web_search_action +from actions.computer_control import computer_control +from actions.game_updater import game_updater + + +# --------------------------------------------------------------------------- +# Paths +# --------------------------------------------------------------------------- + +def _get_base_dir() -> Path: + if getattr(sys, "frozen", False): + return Path(sys.executable).parent + return Path(__file__).resolve().parent + + +BASE_DIR = _get_base_dir() +API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json" +PROMPT_PATH = BASE_DIR / "core" / "prompt.txt" + +SAMPLE_RATE_IN = 16_000 +BLOCK_SIZE = 1_024 +CHANNELS = 1 + +# --------------------------------------------------------------------------- +# Tool declarations (Gemini format kept for readability; +# converted to OpenAI/Ollama format by _to_ollama_tools()) +# --------------------------------------------------------------------------- + +TOOL_DECLARATIONS = [ + { + "name": "open_app", + "description": ( + "Opens any application on the computer. " + "Use this whenever the user asks to open, launch, or start any app, " + "website, or program. Always call this tool — never just say you opened it." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "app_name": {"type": "STRING", "description": "Exact name of the application"} + }, + "required": ["app_name"] + } + }, + { + "name": "web_search", + "description": "Searches the web for any information.", + "parameters": { + "type": "OBJECT", + "properties": { + "query": {"type": "STRING", "description": "Search query"}, + "mode": {"type": "STRING", "description": "search (default) or compare"}, + "items": {"type": "ARRAY", "items": {"type": "STRING"}, "description": "Items to compare"}, + "aspect": {"type": "STRING", "description": "price | specs | reviews"} + }, + "required": ["query"] + } + }, + { + "name": "weather_report", + "description": "Gives the weather report to user", + "parameters": { + "type": "OBJECT", + "properties": {"city": {"type": "STRING", "description": "City name"}}, + "required": ["city"] + } + }, + { + "name": "send_message", + "description": "Sends a text message via WhatsApp, Telegram, or other messaging platform.", + "parameters": { + "type": "OBJECT", + "properties": { + "receiver": {"type": "STRING", "description": "Recipient contact name"}, + "message_text": {"type": "STRING", "description": "The message to send"}, + "platform": {"type": "STRING", "description": "Platform: WhatsApp, Telegram, etc."} + }, + "required": ["receiver", "message_text", "platform"] + } + }, + { + "name": "reminder", + "description": "Sets a timed reminder using Task Scheduler.", + "parameters": { + "type": "OBJECT", + "properties": { + "date": {"type": "STRING", "description": "Date in YYYY-MM-DD format"}, + "time": {"type": "STRING", "description": "Time in HH:MM format (24h)"}, + "message": {"type": "STRING", "description": "Reminder message text"} + }, + "required": ["date", "time", "message"] + } + }, + { + "name": "youtube_video", + "description": ( + "Controls YouTube. Use for: playing videos, summarizing a video's content, " + "getting video info, or showing trending videos." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "play | summarize | get_info | trending"}, + "query": {"type": "STRING", "description": "Search query for play action"}, + "save": {"type": "BOOLEAN", "description": "Save summary to Notepad"}, + "region": {"type": "STRING", "description": "Country code for trending e.g. TR, US"}, + "url": {"type": "STRING", "description": "Video URL for get_info action"}, + }, + "required": [] + } + }, + { + "name": "screen_process", + "description": ( + "Captures and analyzes the screen or webcam image. " + "MUST be called when user asks what is on screen, what you see, " + "analyze my screen, look at camera, etc. " + "You have NO visual ability without this tool." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "angle": {"type": "STRING", "description": "'screen' or 'camera'. Default: 'screen'"}, + "text": {"type": "STRING", "description": "The question about the captured image"} + }, + "required": ["text"] + } + }, + { + "name": "computer_settings", + "description": ( + "Controls the computer: volume, brightness, window management, keyboard shortcuts, " + "typing text on screen, closing apps, fullscreen, dark mode, WiFi, restart, shutdown, " + "scrolling, tab management, zoom, screenshots, lock screen, refresh/reload page." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "The action to perform"}, + "description": {"type": "STRING", "description": "Natural language description"}, + "value": {"type": "STRING", "description": "Optional value"} + }, + "required": [] + } + }, + { + "name": "browser_control", + "description": ( + "Controls any web browser. Use for: opening websites, searching the web, " + "clicking elements, filling forms, scrolling, screenshots, navigation." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "go_to | search | click | type | scroll | fill_form | smart_click | smart_type | get_text | get_url | press | new_tab | close_tab | screenshot | back | forward | reload | switch | list_browsers | close | close_all"}, + "browser": {"type": "STRING", "description": "chrome | edge | firefox | opera | operagx | brave | vivaldi | safari"}, + "url": {"type": "STRING", "description": "URL for go_to / new_tab action"}, + "query": {"type": "STRING", "description": "Search query"}, + "engine": {"type": "STRING", "description": "google | bing | duckduckgo | yandex"}, + "selector": {"type": "STRING", "description": "CSS selector for click/type"}, + "text": {"type": "STRING", "description": "Text to click or type"}, + "description": {"type": "STRING", "description": "Element description for smart_click/smart_type"}, + "direction": {"type": "STRING", "description": "up | down for scroll"}, + "amount": {"type": "INTEGER", "description": "Scroll amount in pixels"}, + "key": {"type": "STRING", "description": "Key name for press"}, + "path": {"type": "STRING", "description": "Save path for screenshot"}, + "incognito": {"type": "BOOLEAN", "description": "Open in private/incognito mode"}, + "clear_first": {"type": "BOOLEAN", "description": "Clear field before typing"}, + }, + "required": ["action"] + } + }, + { + "name": "file_controller", + "description": "Manages files and folders: list, create, delete, move, copy, rename, read, write, find, disk usage.", + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "list | create_file | create_folder | delete | move | copy | rename | read | write | find | largest | disk_usage | organize_desktop | info"}, + "path": {"type": "STRING", "description": "File/folder path or shortcut: desktop, downloads, documents, home"}, + "destination": {"type": "STRING", "description": "Destination path for move/copy"}, + "new_name": {"type": "STRING", "description": "New name for rename"}, + "content": {"type": "STRING", "description": "Content for create_file/write"}, + "name": {"type": "STRING", "description": "File name to search for"}, + "extension": {"type": "STRING", "description": "File extension to search"}, + "count": {"type": "INTEGER", "description": "Number of results for largest"}, + }, + "required": ["action"] + } + }, + { + "name": "desktop_control", + "description": "Controls the desktop: wallpaper, organize, clean, list, stats.", + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "wallpaper | wallpaper_url | organize | clean | list | stats | task"}, + "path": {"type": "STRING", "description": "Image path for wallpaper"}, + "url": {"type": "STRING", "description": "Image URL for wallpaper_url"}, + "mode": {"type": "STRING", "description": "by_type or by_date for organize"}, + "task": {"type": "STRING", "description": "Natural language desktop task"}, + }, + "required": ["action"] + } + }, + { + "name": "code_helper", + "description": "Writes, edits, explains, runs, or builds code files.", + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "write | edit | explain | run | build | auto"}, + "description": {"type": "STRING", "description": "What the code should do"}, + "language": {"type": "STRING", "description": "Programming language"}, + "output_path": {"type": "STRING", "description": "Where to save the file"}, + "file_path": {"type": "STRING", "description": "Path to existing file"}, + "code": {"type": "STRING", "description": "Raw code string for explain"}, + "args": {"type": "STRING", "description": "CLI arguments"}, + "timeout": {"type": "INTEGER", "description": "Execution timeout in seconds"}, + }, + "required": ["action"] + } + }, + { + "name": "dev_agent", + "description": "Builds complete multi-file projects from scratch.", + "parameters": { + "type": "OBJECT", + "properties": { + "description": {"type": "STRING", "description": "What the project should do"}, + "language": {"type": "STRING", "description": "Programming language"}, + "project_name": {"type": "STRING", "description": "Optional project folder name"}, + "timeout": {"type": "INTEGER", "description": "Run timeout in seconds"}, + }, + "required": ["description"] + } + }, + { + "name": "agent_task", + "description": ( + "Executes complex multi-step tasks requiring multiple different tools. " + "Examples: 'research X and save to file', 'find and organize files'. " + "DO NOT use for single commands." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "goal": {"type": "STRING", "description": "Complete description of what to accomplish"}, + "priority": {"type": "STRING", "description": "low | normal | high"} + }, + "required": ["goal"] + } + }, + { + "name": "computer_control", + "description": "Direct computer control: type, click, hotkeys, scroll, move mouse, screenshots, find elements on screen.", + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "type | smart_type | click | double_click | right_click | hotkey | press | scroll | move | copy | paste | screenshot | wait | clear_field | focus_window | screen_find | screen_click | random_data | user_data"}, + "text": {"type": "STRING", "description": "Text to type or paste"}, + "x": {"type": "INTEGER", "description": "X coordinate"}, + "y": {"type": "INTEGER", "description": "Y coordinate"}, + "keys": {"type": "STRING", "description": "Key combination e.g. 'ctrl+c'"}, + "key": {"type": "STRING", "description": "Single key e.g. 'enter'"}, + "direction": {"type": "STRING", "description": "up | down | left | right"}, + "amount": {"type": "INTEGER", "description": "Scroll amount"}, + "seconds": {"type": "NUMBER", "description": "Seconds to wait"}, + "title": {"type": "STRING", "description": "Window title for focus_window"}, + "description": {"type": "STRING", "description": "Element description"}, + "type": {"type": "STRING", "description": "Data type for random_data"}, + "field": {"type": "STRING", "description": "Field for user_data"}, + "clear_first": {"type": "BOOLEAN", "description": "Clear field before typing"}, + "path": {"type": "STRING", "description": "Save path for screenshot"}, + }, + "required": ["action"] + } + }, + { + "name": "game_updater", + "description": ( + "THE ONLY tool for ANY Steam or Epic Games request. " + "Use for: installing, downloading, updating games, listing installed games." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "action": {"type": "STRING", "description": "update | install | list | download_status | schedule | cancel_schedule | schedule_status"}, + "platform": {"type": "STRING", "description": "steam | epic | both"}, + "game_name": {"type": "STRING", "description": "Game name"}, + "app_id": {"type": "STRING", "description": "Steam AppID"}, + "hour": {"type": "INTEGER", "description": "Hour for scheduled update 0-23"}, + "minute": {"type": "INTEGER", "description": "Minute for scheduled update 0-59"}, + "shutdown_when_done": {"type": "BOOLEAN", "description": "Shut down PC when done"}, + }, + "required": [] + } + }, + { + "name": "flight_finder", + "description": "Searches Google Flights and speaks the best options.", + "parameters": { + "type": "OBJECT", + "properties": { + "origin": {"type": "STRING", "description": "Departure city or airport code"}, + "destination": {"type": "STRING", "description": "Arrival city or airport code"}, + "date": {"type": "STRING", "description": "Departure date"}, + "return_date": {"type": "STRING", "description": "Return date for round trips"}, + "passengers": {"type": "INTEGER", "description": "Number of passengers"}, + "cabin": {"type": "STRING", "description": "economy | premium | business | first"}, + "save": {"type": "BOOLEAN", "description": "Save results to Notepad"}, + }, + "required": ["origin", "destination", "date"] + } + }, + { + "name": "shutdown_jarvis", + "description": ( + "Shuts down the assistant completely. " + "Call this when the user expresses intent to end the conversation, " + "close the assistant, say goodbye, or stop Jarvis." + ), + "parameters": {"type": "OBJECT", "properties": {}} + }, + { + "name": "file_processor", + "description": ( + "Processes any file that the user has uploaded or dropped onto the interface. " + "Supports: images, PDFs, Word docs, CSV/Excel, JSON, code files, audio, video, archives." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "file_path": {"type": "STRING", "description": "Full path to the uploaded file"}, + "action": {"type": "STRING", "description": "What to do with the file"}, + "instruction": {"type": "STRING", "description": "Free-form instruction"}, + "format": {"type": "STRING", "description": "Target format for conversion"}, + "width": {"type": "INTEGER", "description": "Target width for image resize"}, + "height": {"type": "INTEGER", "description": "Target height for image resize"}, + "scale": {"type": "NUMBER", "description": "Scale factor"}, + "quality": {"type": "INTEGER", "description": "Quality 1-100"}, + "start": {"type": "STRING", "description": "Start time for trim"}, + "end": {"type": "STRING", "description": "End time for trim"}, + "timestamp": {"type": "STRING", "description": "Timestamp for video frame extraction"}, + "column": {"type": "STRING", "description": "Column name for CSV filter/sort"}, + "value": {"type": "STRING", "description": "Filter value"}, + "condition": {"type": "STRING", "description": "Filter condition"}, + "ascending": {"type": "BOOLEAN", "description": "Sort order"}, + "save": {"type": "BOOLEAN", "description": "Save result to file"}, + "destination": {"type": "STRING", "description": "Output folder for archive extract"}, + }, + "required": [] + } + }, + { + "name": "save_memory", + "description": ( + "Save an important personal fact about the user to long-term memory. " + "Call this silently whenever the user reveals something worth remembering. " + "Do NOT announce that you are saving — just call it silently." + ), + "parameters": { + "type": "OBJECT", + "properties": { + "category": { + "type": "STRING", + "description": ( + "identity | preferences | projects | relationships | wishes | notes" + ) + }, + "key": {"type": "STRING", "description": "Short snake_case key"}, + "value": {"type": "STRING", "description": "Concise value in English"}, + }, + "required": ["category", "key", "value"] + } + }, +] + + +# --------------------------------------------------------------------------- +# Convert Gemini-style declarations to OpenAI/Ollama format +# --------------------------------------------------------------------------- + +_TYPE_MAP = { + "OBJECT": "object", "STRING": "string", "ARRAY": "array", + "INTEGER": "integer", "BOOLEAN": "boolean", "NUMBER": "number", +} + + +def _convert_type(t: str) -> str: + return _TYPE_MAP.get(t, t.lower()) if isinstance(t, str) else t + + +def _convert_props(props: dict) -> dict: + out = {} + for k, v in props.items(): + nv = dict(v) + if "type" in nv: + nv["type"] = _convert_type(nv["type"]) + if "items" in nv and isinstance(nv["items"], dict): + nv["items"] = {"type": _convert_type(nv["items"].get("type", "string"))} + out[k] = nv + return out + + +def _to_ollama_tools(decls: list) -> list: + tools = [] + for d in decls: + params = d.get("parameters", {}) + new_params: dict = { + "type": "object", + "properties": _convert_props(params.get("properties", {})), + } + req = params.get("required") + if req: + new_params["required"] = req + tools.append({ + "type": "function", + "function": { + "name": d["name"], + "description": d["description"], + "parameters": new_params, + }, + }) + return tools + + +OLLAMA_TOOLS = _to_ollama_tools(TOOL_DECLARATIONS) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _load_config() -> dict: + try: + with open(API_CONFIG_PATH, encoding="utf-8") as f: + return json.load(f) + except Exception: + return {} + + +def _load_system_prompt() -> str: + try: + return PROMPT_PATH.read_text(encoding="utf-8") + except Exception: + return ( + "You are JARVIS, Tony Stark's AI assistant. " + "Be concise, direct, and always use the provided tools to complete tasks. " + "Never simulate or guess results — always call the appropriate tool." + ) + + +# --------------------------------------------------------------------------- +# Voice Activity Detection (used for Whisper listen loop) +# --------------------------------------------------------------------------- + +class _VADBuffer: + """Energy-based VAD: buffers audio until end of utterance.""" + + def __init__( + self, + sample_rate: int = 16_000, + silence_sec: float = 1.2, + threshold: float = 0.015, + min_speech_sec: float = 0.4, + max_speech_sec: float = 30.0, + ): + self._sr = sample_rate + self._sil_n = int(silence_sec * sample_rate) + self._thresh = threshold + self._min_n = int(min_speech_sec * sample_rate) + self._max_n = int(max_speech_sec * sample_rate) + self._buf: list[np.ndarray] = [] + self._in_spch = False + self._sil_cnt = 0 + + def process(self, chunk: np.ndarray) -> np.ndarray | None: + """ + Feed one audio chunk (float32 mono). + Returns complete utterance when speech ends, otherwise None. + """ + rms = float(np.sqrt(np.mean(chunk ** 2))) + total_n = sum(len(c) for c in self._buf) + + if rms > self._thresh: + self._in_spch = True + self._sil_cnt = 0 + self._buf.append(chunk.copy()) + elif self._in_spch: + self._buf.append(chunk.copy()) + self._sil_cnt += len(chunk) + + if self._sil_cnt >= self._sil_n or total_n >= self._max_n: + audio = np.concatenate(self._buf) + self._buf = [] + self._in_spch = False + self._sil_cnt = 0 + if len(audio) >= self._min_n: + return audio + return None + + +# --------------------------------------------------------------------------- +# JarvisLocal +# --------------------------------------------------------------------------- + +class JarvisLocal: + """ + Main assistant class. + Replaces JarvisLive (Gemini Live API) with: + STT (Whisper/Vosk) → Ollama LLM (tool calling) → TTS (Edge/Kokoro/ElevenLabs) + """ + + def __init__(self, ui: JarvisUI): + self.ui = ui + self._config = _load_config() + self._stt = None + self._tts = None + self._speaking = False + self._speaking_lock = threading.Lock() + self._text_queue: queue.Queue = queue.Queue() + self._tts_queue: queue.Queue = queue.Queue() + self._conversation: list[dict] = [] + + self.ui.on_text_command = self._on_text_command + + # ------------------------------------------------------------------ + # System prompt + # ------------------------------------------------------------------ + + def _build_system_prompt(self) -> str: + memory = load_memory() + mem_str = format_memory_for_prompt(memory) + sys_p = _load_system_prompt() + now = datetime.now() + time_ctx = ( + f"[CURRENT DATE & TIME]\n" + f"Right now it is: {now.strftime('%A, %B %d, %Y — %I:%M %p')}\n" + f"Use this to calculate exact times for reminders.\n\n" + ) + parts = [time_ctx] + if mem_str: + parts.append(mem_str) + parts.append(sys_p) + return "\n".join(parts) + + # ------------------------------------------------------------------ + # Speaking state & TTS + # ------------------------------------------------------------------ + + # ------------------------------------------------------------------ + # TTS queue worker — plays sentences sequentially, no overlaps + # ------------------------------------------------------------------ + + def _tts_worker(self) -> None: + while True: + text = self._tts_queue.get() + n_got = 1 # how many queue items we consumed this round + + try: + if text and self._tts: + # ── Kokoro: merge buffered sentences into one inference call ── + # Each separate Kokoro call costs ~0.5–1 s startup. + # Draining the queue here combines "Hello. How are you?" into + # one call instead of two, eliminating the gap between them. + from core.tts import KokoroTTSEngine + engine = getattr(self._tts, "_engine", None) + if isinstance(engine, KokoroTTSEngine): + while True: + try: + nxt = self._tts_queue.get_nowait() + if nxt: + text = text.rstrip() + " " + nxt.lstrip() + n_got += 1 + except queue.Empty: + break + + with self._speaking_lock: + self._speaking = True + self.ui.set_state("SPEAKING") + self._tts.speak(text) + + except Exception as e: + print(f"[TTS] speak error: {e}") + finally: + for _ in range(n_got): + self._tts_queue.task_done() + if self._tts_queue.empty(): + with self._speaking_lock: + self._speaking = False + if not self.ui.muted: + self.ui.set_state("LISTENING") + + def set_speaking(self, value: bool) -> None: + with self._speaking_lock: + self._speaking = value + if value: + self.ui.set_state("SPEAKING") + elif not self.ui.muted: + self.ui.set_state("LISTENING") + + def speak(self, text: str) -> None: + if not text or not self._tts: + return + with self._speaking_lock: + self._speaking = True + self._tts_queue.put(text) + + def speak_error(self, tool_name: str, error) -> None: + short = str(error)[:120] + self.ui.write_log(f"ERR: {tool_name} — {short}") + self.speak(f"{tool_name} encountered an error.") + + # ------------------------------------------------------------------ + # Live reconfigure (called when user clicks Apply in Configure panel) + # ------------------------------------------------------------------ + + def reconfigure(self, new_config: dict) -> None: + """Non-blocking: spawns a background thread to install + reload.""" + threading.Thread( + target=self._do_reconfigure, args=(new_config,), daemon=True + ).start() + + def _do_reconfigure(self, new_config: dict) -> None: + old_stt_engine = self._config.get("stt_engine", "whisper").lower() + old_llm_model = self._config.get("llm_model", "") + new_stt_engine = new_config.get("stt_engine", "whisper").lower() + self._config = new_config + + # Install any packages required by the new config + try: + from core.installer import install_for_config + install_for_config(new_config, log=self.ui.write_log) + except Exception as e: + self.ui.write_log(f"ERR: Dependency install — {e}") + + # TTS: always hot-reload (runs in queue worker, safe to swap) + try: + from core.tts import create_tts_player + self._tts = create_tts_player(new_config) + self.ui.write_log("SYS: TTS reconfigured.") + except Exception as e: + self.ui.write_log(f"ERR: TTS reconfigure — {e}") + + # STT: hot-reload if same engine type; full restart needed if engine changed + if old_stt_engine == new_stt_engine: + try: + stt_language = new_config.get("stt_language", "auto") + if new_stt_engine == "vosk": + from core.stt import VoskSTT + self._stt = VoskSTT(new_config.get("vosk_model_path"), language=stt_language) + else: + from core.stt import WhisperSTT + self._stt = WhisperSTT(new_config.get("stt_model", "base"), language=stt_language) + self.ui.write_log("SYS: STT reconfigured.") + except Exception as e: + self.ui.write_log(f"ERR: STT reconfigure — {e}") + else: + self.ui.write_log("SYS: STT engine changed — restart required.") + + # LLM warmup if model changed + if new_config.get("llm_model", "") != old_llm_model: + self.ui.write_log("SYS: Warming up new LLM model…") + from core.llm_client import warmup_model + warmup_model() + self.ui.write_log("SYS: New LLM model ready.") + + if old_stt_engine == new_stt_engine: + self.speak("Configuration applied.") + else: + self.speak("LLM and TTS updated. Restart for speech engine change.") + + # ------------------------------------------------------------------ + # Text command (from UI input box) + # ------------------------------------------------------------------ + + def _on_text_command(self, text: str) -> None: + self._text_queue.put(text) + + # ------------------------------------------------------------------ + # Tool execution (routing unchanged from original) + # ------------------------------------------------------------------ + + def _execute_tool(self, name: str, args: dict) -> str: + print(f"[JARVIS] 🔧 {name} {args}") + self.ui.set_state("THINKING") + + # save_memory is handled silently + if name == "save_memory": + category = args.get("category", "notes") + key = args.get("key", "") + value = args.get("value", "") + if key and value: + update_memory({category: {key: {"value": value}}}) + print(f"[Memory] 💾 {category}/{key} = {value}") + if not self.ui.muted: + self.ui.set_state("LISTENING") + return "__SILENT__" + + result = "Done." + try: + if name == "open_app": + r = open_app(parameters=args, response=None, player=self.ui) + result = r or f"Opened {args.get('app_name')}." + + elif name == "weather_report": + r = weather_action(parameters=args, player=self.ui) + result = r or "Weather delivered." + + elif name == "browser_control": + r = browser_control(parameters=args, player=self.ui) + result = r or "Done." + + elif name == "file_controller": + r = file_controller(parameters=args, player=self.ui) + result = r or "Done." + + elif name == "send_message": + r = send_message(parameters=args, response=None, player=self.ui, session_memory=None) + result = r or f"Message sent to {args.get('receiver')}." + + elif name == "reminder": + r = reminder(parameters=args, response=None, player=self.ui) + result = r or "Reminder set." + + elif name == "youtube_video": + r = youtube_video(parameters=args, response=None, player=self.ui) + result = r or "Done." + + elif name == "screen_process": + # Synchronous call — returns analysis text which the LLM can speak + r = screen_process(parameters=args, response=None, player=self.ui, session_memory=None) + result = r if isinstance(r, str) and r else "Screen analyzed." + + elif name == "computer_settings": + r = computer_settings(parameters=args, response=None, player=self.ui) + result = r or "Done." + + elif name == "desktop_control": + r = desktop_control(parameters=args, player=self.ui) + result = r or "Done." + + elif name == "code_helper": + r = code_helper(parameters=args, player=self.ui, speak=self.speak) + result = r or "Done." + + elif name == "dev_agent": + r = dev_agent(parameters=args, player=self.ui, speak=self.speak) + result = r or "Done." + + elif name == "agent_task": + from agent.task_queue import get_queue, TaskPriority + priority_map = { + "low": TaskPriority.LOW, + "normal": TaskPriority.NORMAL, + "high": TaskPriority.HIGH, + } + priority = priority_map.get( + args.get("priority", "normal").lower(), TaskPriority.NORMAL + ) + task_id = get_queue().submit( + goal=args.get("goal", ""), priority=priority, speak=self.speak + ) + result = f"Task started (ID: {task_id})." + + elif name == "web_search": + r = web_search_action(parameters=args, player=self.ui) + result = r or "Done." + + elif name == "file_processor": + if not args.get("file_path") and self.ui.current_file: + args["file_path"] = self.ui.current_file + r = file_processor(parameters=args, player=self.ui, speak=self.speak) + result = r or "Done." + + elif name == "computer_control": + r = computer_control(parameters=args, player=self.ui) + result = r or "Done." + + elif name == "game_updater": + r = game_updater(parameters=args, player=self.ui, speak=self.speak) + result = r or "Done." + + elif name == "flight_finder": + r = flight_finder(parameters=args, player=self.ui) + result = r or "Done." + + elif name == "shutdown_jarvis": + self.ui.write_log("SYS: Shutdown requested.") + + def _shutdown(): + import time, os + self.speak("Goodbye.") + time.sleep(2.5) + os._exit(0) + + threading.Thread(target=_shutdown, daemon=True).start() + return "Shutting down." + + else: + result = f"Unknown tool: {name}" + + except Exception as e: + result = f"Tool '{name}' failed: {e}" + traceback.print_exc() + self.speak_error(name, e) + + if not self.ui.muted: + self.ui.set_state("LISTENING") + + print(f"[JARVIS] 📤 {name} → {str(result)[:80]}") + return result + + # ------------------------------------------------------------------ + # LLM processing loop + # ------------------------------------------------------------------ + + def _process_message(self, user_text: str) -> None: + """ + Full turn: + user_text → Ollama stream (with tools) → execute tools → final spoken response + + Streaming means TTS starts on the first complete sentence (~1-2 s), + not after the full response is ready. + """ + self.ui.set_state("THINKING") + self.ui.write_log(f"You: {user_text}") + + self._conversation.append({"role": "user", "content": user_text}) + + MAX_HISTORY = 30 + if len(self._conversation) > MAX_HISTORY: + self._conversation = self._conversation[-MAX_HISTORY:] + + messages = [ + {"role": "system", "content": self._build_system_prompt()} + ] + list(self._conversation) + + MAX_TOOL_ROUNDS = 6 + for _round in range(MAX_TOOL_ROUNDS): + final_content = "" + final_tool_calls: list = [] + + try: + for event in call_llm_stream(messages, OLLAMA_TOOLS): + if event["type"] == "sentence": + self.speak(event["text"]) + elif event["type"] == "done": + final_content = event["content"] + final_tool_calls = event["tool_calls"] + except RuntimeError as e: + self.speak_error("LLM", e) + return + + if not final_tool_calls: + # Final text response — TTS already started sentence-by-sentence + if final_content: + assistant_msg = {"role": "assistant", "content": final_content} + messages.append(assistant_msg) + self._conversation.append(assistant_msg) + self.ui.write_log(f"Jarvis: {final_content}") + break + + # ------- tool calls ------- + assistant_msg = { + "role": "assistant", + "content": final_content or "", + "tool_calls": final_tool_calls, + } + messages.append(assistant_msg) + self._conversation.append(assistant_msg) + + all_silent = True + for tc in final_tool_calls: + fn = tc.get("function", {}) + tname = fn.get("name", "") + targs = fn.get("arguments", {}) + if isinstance(targs, str): + try: + targs = json.loads(targs) + except Exception: + targs = {} + + tc_id = tc.get("id", "") + self.ui.write_log(f"SYS: ▶ {tname}") + result = self._execute_tool(tname, targs) + + if result != "__SILENT__": + all_silent = False + + tool_msg: dict = { + "role": "tool", + "content": "Done." if result == "__SILENT__" else str(result), + } + if tc_id: + tool_msg["tool_call_id"] = tc_id + + messages.append(tool_msg) + self._conversation.append(tool_msg) + + # Even if all tools were silent (e.g. save_memory only), + # always do one more LLM round so the assistant can verbally respond. + + if not self.ui.muted: + self.ui.set_state("LISTENING") + + # ------------------------------------------------------------------ + # STT listening loops + # ------------------------------------------------------------------ + + def _listen_whisper(self) -> None: + """Mic → VAD → Whisper → LLM loop.""" + vad = _VADBuffer() + q: queue.Queue = queue.Queue(maxsize=200) + + def callback(indata, frames, time_info, status): + with self._speaking_lock: + is_speaking = self._speaking + if not is_speaking and not self.ui.muted: + try: + q.put_nowait(indata.copy()) + except queue.Full: + pass + + try: + with sd.InputStream( + samplerate=SAMPLE_RATE_IN, + channels=CHANNELS, + dtype="float32", + blocksize=BLOCK_SIZE, + callback=callback, + ): + self.ui.write_log("SYS: Mic active (Whisper STT).") + while True: + try: + chunk = q.get(timeout=0.1) + audio = vad.process(chunk.flatten()) + if audio is not None: + self.ui.set_state("THINKING") + text = self._stt.transcribe(audio) + if text.strip(): + self._process_message(text) + except queue.Empty: + pass + except Exception as e: + print(f"[STT-Whisper] Mic error: {e}") + traceback.print_exc() + + def _listen_vosk(self) -> None: + """Mic → Vosk streaming → LLM loop.""" + q: queue.Queue = queue.Queue(maxsize=200) + + def callback(indata, frames, time_info, status): + with self._speaking_lock: + is_speaking = self._speaking + if not is_speaking and not self.ui.muted: + try: + q.put_nowait(indata.copy()) + except queue.Full: + pass + + try: + with sd.InputStream( + samplerate=SAMPLE_RATE_IN, + channels=CHANNELS, + dtype="int16", + blocksize=4096, + callback=callback, + ): + self.ui.write_log("SYS: Mic active (Vosk STT).") + while True: + try: + chunk = q.get(timeout=0.1) + text, is_final = self._stt.process_chunk(chunk.tobytes()) + if is_final and text.strip(): + self._process_message(text) + except queue.Empty: + pass + except Exception as e: + print(f"[STT-Vosk] Mic error: {e}") + traceback.print_exc() + + # ------------------------------------------------------------------ + # Text command loop (UI input box) + # ------------------------------------------------------------------ + + def _text_command_loop(self) -> None: + while True: + try: + text = self._text_queue.get(timeout=0.5) + if text.strip(): + self._process_message(text) + except queue.Empty: + pass + + # ------------------------------------------------------------------ + # Entry point + # ------------------------------------------------------------------ + + def run(self) -> None: + """Initialise STT + TTS, then start the main listen loop.""" + try: + # -- Wire reconfigure callback -- + self.ui.on_reconfigure = self.reconfigure + + # -- Ollama auto-start -- + from core.llm_client import ensure_ollama_running, warmup_model + self.ui.write_log("SYS: Checking Ollama…") + if ensure_ollama_running(): + self.ui.write_log("SYS: Ollama OK.") + else: + self.ui.write_log("ERR: Ollama unavailable. Start it manually: ollama serve") + self.speak("Ollama is not running. Please start it manually.") + + # -- LLM warmup (parallel with STT/TTS loading) -- + _warmup_done = threading.Event() + def _do_warmup(): + try: + warmup_model() + finally: + _warmup_done.set() + threading.Thread(target=_do_warmup, daemon=True).start() + + # -- STT -- + stt_engine = self._config.get("stt_engine", "whisper").lower() + stt_language = self._config.get("stt_language", "auto") + stt_model = self._config.get("stt_model", "base") + self.ui.write_log(f"SYS: Loading {stt_engine.upper()} STT…") + if stt_engine == "whisper": + self.ui.write_log(f"SYS: Whisper '{stt_model}' — downloading if not cached…") + elif stt_engine == "vosk": + self.ui.write_log("SYS: Vosk — downloading model if not cached…") + + if stt_engine == "vosk": + from core.stt import VoskSTT + self._stt = VoskSTT( + self._config.get("vosk_model_path"), + language=stt_language, + ) + else: + from core.stt import WhisperSTT + self._stt = WhisperSTT(stt_model, language=stt_language) + + self.ui.write_log("SYS: STT ready.") + + # -- TTS -- + tts_engine = self._config.get("tts_engine", "edgetts").lower() + self.ui.write_log(f"SYS: Loading {tts_engine.upper()} TTS…") + if tts_engine == "kokoro": + self.ui.write_log("SYS: Kokoro — downloading model (~330 MB) if not cached…") + from core.tts import create_tts_player + self._tts = create_tts_player(self._config) + self.ui.write_log("SYS: TTS ready.") + + # -- Wait for LLM warmup to finish -- + self.ui.write_log("SYS: Loading LLM into memory…") + _warmup_done.wait(timeout=120) + self.ui.write_log("SYS: LLM ready.") + + # Welcome + self.ui.write_log("SYS: JARVIS online.") + self.ui.set_state("LISTENING") + + # TTS queue worker (sequential, no overlap) + threading.Thread(target=self._tts_worker, daemon=True).start() + + self.speak("JARVIS online. All systems ready.") + + # Text-command handler (runs in background) + threading.Thread(target=self._text_command_loop, daemon=True).start() + + # STT loop (blocking — keeps this thread alive) + if stt_engine == "vosk": + self._listen_vosk() + else: + self._listen_whisper() + + except Exception as e: + self.ui.write_log(f"ERR: Init failed — {e}") + traceback.print_exc() + + +# --------------------------------------------------------------------------- +# Entry +# --------------------------------------------------------------------------- + +def main() -> None: + ui = JarvisUI("face.png") + + def runner(): + # 1. Wait until the user completes the setup overlay (first run) + # or config already exists (subsequent runs). + ui.wait_for_api_key() + + # 2. Install any missing engine packages before loading engines. + # Progress is streamed to the log panel in real time. + ui.write_log("SYS: Checking dependencies…") + cfg = _load_config() + _install_done = threading.Event() + + def _do_install(): + try: + from core.installer import install_for_config + install_for_config(cfg, log=ui.write_log) + except Exception as e: + ui.write_log(f"ERR: Dependency install — {e}") + finally: + _install_done.set() + + threading.Thread(target=_do_install, daemon=True).start() + _install_done.wait() # blocks runner thread; UI remains responsive + + # 3. Start the assistant (loads STT / TTS / LLM). + jarvis = JarvisLocal(ui) + try: + jarvis.run() + except KeyboardInterrupt: + print("\n[MARK XL] Shutting down…") + + threading.Thread(target=runner, daemon=True).start() + ui.root.mainloop() + + +if __name__ == "__main__": + main() diff --git a/memory/config_manager.py b/memory/config_manager.py index 1a324c4..1ca67c5 100644 --- a/memory/config_manager.py +++ b/memory/config_manager.py @@ -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) \ No newline at end of file +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")) + ) diff --git a/readme.md b/readme.md index 61e91c2..2e8dea0 100644 --- a/readme.md +++ b/readme.md @@ -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 ` 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 diff --git a/requirements.txt b/requirements.txt index 8453d5d..f60c114 100644 --- a/requirements.txt +++ b/requirements.txt @@ -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 diff --git a/ui.py b/ui.py index 1f2286e..3b00c81 100644 --- a/ui.py +++ b/ui.py @@ -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)