Add files via upload
This commit is contained in:
1 parent
d3e8504706
commit
502309ad24
25 files changed
+4097
-3006
No files matched your search
+76
-125
@@ -12,21 +12,10 @@ def get_base_dir():
|
|||||||
return Path(__file__).resolve().parent.parent
|
return Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
BASE_DIR = get_base_dir()
|
BASE_DIR = get_base_dir()
|
||||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
|
||||||
DESKTOP = Path.home() / "Desktop"
|
DESKTOP = Path.home() / "Desktop"
|
||||||
MAX_BUILD_ATTEMPTS = 3
|
MAX_BUILD_ATTEMPTS = 3
|
||||||
GEMINI_MODEL = "gemini-2.5-flash"
|
|
||||||
|
|
||||||
|
from core.llm_client import call_llm_text as _llm
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
def _clean_code(text: str) -> str:
|
def _clean_code(text: str) -> str:
|
||||||
@@ -145,47 +134,28 @@ def _detect_intent(description: str, file_path: str, code: str) -> str:
|
|||||||
return "write"
|
return "write"
|
||||||
|
|
||||||
def _write(description: str, language: str, output_path: str, player=None) -> tuple[str, Path]:
|
def _write(description: str, language: str, output_path: str, player=None) -> tuple[str, Path]:
|
||||||
lang = language or "python"
|
lang = language or "python"
|
||||||
model = _get_gemini()
|
system = f"You are an expert {lang} developer. Output ONLY raw code, no markdown, no backticks, no explanations."
|
||||||
|
prompt = (
|
||||||
prompt = f"""You are an expert {lang} developer.
|
f"Write clean, working, well-commented {lang} code.\n"
|
||||||
Write clean, working, well-commented {lang} code for the description below.
|
f"Handle errors and edge cases. Use modern best practices.\n\n"
|
||||||
|
f"Description: {description}\n\nCode:"
|
||||||
Rules:
|
)
|
||||||
- Output ONLY the code. No explanation, no markdown, no backticks.
|
code = _clean_code(_llm(prompt, system=system))
|
||||||
- Add helpful inline comments.
|
path = _resolve_save_path(output_path, lang)
|
||||||
- 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)
|
|
||||||
_save_file(path, code)
|
_save_file(path, code)
|
||||||
return code, path
|
return code, path
|
||||||
|
|
||||||
|
|
||||||
def _fix_code(code: str, error_output: str, description: str) -> str:
|
def _fix_code(code: str, error_output: str, description: str) -> str:
|
||||||
model = _get_gemini()
|
system = "You are an expert debugger. Return ONLY the corrected code — no explanation, no markdown, no backticks."
|
||||||
prompt = f"""You are an expert debugger.
|
prompt = (
|
||||||
The code below failed with the following error. Fix it.
|
f"Fix the code below. It failed with this error.\n\n"
|
||||||
Return ONLY the corrected code — no explanation, no markdown, no backticks.
|
f"Original goal: {description}\n\n"
|
||||||
|
f"Error:\n{error_output[:2000]}\n\n"
|
||||||
Original goal: {description}
|
f"Broken code:\n{code}\n\nFixed code:"
|
||||||
|
)
|
||||||
Error:
|
return _clean_code(_llm(prompt, system=system))
|
||||||
{error_output[:2000]}
|
|
||||||
|
|
||||||
Broken code:
|
|
||||||
{code}
|
|
||||||
|
|
||||||
Fixed code:"""
|
|
||||||
|
|
||||||
response = model.generate_content(prompt)
|
|
||||||
return _clean_code(response.text)
|
|
||||||
|
|
||||||
|
|
||||||
def _run_file(path: Path, args: list, timeout: int) -> str:
|
def _run_file(path: Path, args: list, timeout: int) -> str:
|
||||||
@@ -303,21 +273,14 @@ def _edit_action(file_path, instruction, player) -> str:
|
|||||||
if player:
|
if player:
|
||||||
player.write_log("[Code] Editing file...")
|
player.write_log("[Code] Editing file...")
|
||||||
|
|
||||||
model = _get_gemini()
|
system = "You are an expert code editor. Return ONLY the complete updated code — no explanation, no markdown, no backticks."
|
||||||
prompt = f"""You are an expert code editor.
|
prompt = (
|
||||||
Apply the following change to the code below.
|
f"Apply the following change to the code below.\n\n"
|
||||||
Return ONLY the complete updated code — no explanation, no markdown, no backticks.
|
f"Change: {instruction}\n\n"
|
||||||
|
f"Original code:\n{content}\n\nUpdated code:"
|
||||||
Change: {instruction}
|
)
|
||||||
|
|
||||||
Original code:
|
|
||||||
{content}
|
|
||||||
|
|
||||||
Updated code:"""
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
edited = _clean_code(_llm(prompt, system=system))
|
||||||
edited = _clean_code(response.text)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"Could not edit code: {e}"
|
return f"Could not edit code: {e}"
|
||||||
|
|
||||||
@@ -337,19 +300,13 @@ def _explain_action(file_path, code, player) -> str:
|
|||||||
if player:
|
if player:
|
||||||
player.write_log("[Code] Analyzing code...")
|
player.write_log("[Code] Analyzing code...")
|
||||||
|
|
||||||
model = _get_gemini()
|
system = "You are an expert programmer. Explain code concisely in 3-6 sentences."
|
||||||
prompt = f"""Explain what this code does in simple, clear language.
|
prompt = (
|
||||||
Focus on: what it does, how it works, and any important details.
|
f"Explain what this code does — what it does, how it works, important details.\n\n"
|
||||||
Be concise — 3 to 6 sentences maximum.
|
f"Code:\n{code[:4000]}\n\nExplanation:"
|
||||||
|
)
|
||||||
Code:
|
|
||||||
{code[:4000]}
|
|
||||||
|
|
||||||
Explanation:"""
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
return _llm(prompt, system=system)
|
||||||
return response.text.strip()
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"Could not explain code: {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:
|
if player:
|
||||||
player.write_log("[Code] Optimizing code...")
|
player.write_log("[Code] Optimizing code...")
|
||||||
|
|
||||||
lang = language or "python"
|
lang = language or "python"
|
||||||
model = _get_gemini()
|
system = f"You are an expert {lang} developer. Return ONLY the optimized code — no explanation, no markdown, no backticks."
|
||||||
|
prompt = (
|
||||||
prompt = f"""You are an expert {lang} developer and code reviewer.
|
f"Optimize this {lang} code for performance, readability, and best practices. "
|
||||||
Optimize the following code for:
|
f"Remove dead code and unnecessary complexity.\n\n"
|
||||||
1. Performance — eliminate unnecessary operations, use efficient data structures
|
f"Original code:\n{code[:6000]}\n\nOptimized code:"
|
||||||
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:"""
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
optimized = _clean_code(_llm(prompt, system=system))
|
||||||
optimized = _clean_code(response.text)
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return f"Could not optimize code: {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}")
|
print(f"[Code] ⚠️ Could not read file: {err}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from google import genai
|
import base64, json as _json, requests as _req
|
||||||
from google.genai import types
|
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()
|
ollama_url = cfg.get("llm_url", "http://localhost:11434").rstrip("/")
|
||||||
image_base64 = _image_to_base64(screenshot_path)
|
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?"
|
user_question = description or "What error or problem do you see on the screen? How can it be fixed?"
|
||||||
|
context = ""
|
||||||
context = ""
|
|
||||||
if file_content:
|
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.
|
analysis_prompt = (
|
||||||
|
f"You are an expert programmer/debugger analyzing a screenshot.\n\n"
|
||||||
User's question: {user_question}{context}
|
f"User question: {user_question}{context}\n\n"
|
||||||
|
f"Identify errors, explain the cause, and provide a fix. "
|
||||||
Please:
|
f"If you see code, show the corrected version."
|
||||||
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 = response.text.strip()
|
resp = _req.post(
|
||||||
print(f"[Code] ✅ Screen analysis complete")
|
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:
|
try:
|
||||||
screenshot_path.unlink()
|
screenshot_path.unlink()
|
||||||
@@ -486,7 +439,6 @@ Be specific and actionable. If you see an error message, quote it exactly."""
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
if file_path and file_content:
|
if file_path and file_content:
|
||||||
|
|
||||||
code_match = re.search(r"```[a-zA-Z]*\n(.*?)```", analysis, re.DOTALL)
|
code_match = re.search(r"```[a-zA-Z]*\n(.*?)```", analysis, re.DOTALL)
|
||||||
if code_match:
|
if code_match:
|
||||||
fixed_code = code_match.group(1).strip()
|
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
|
return analysis
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
||||||
try:
|
try:
|
||||||
screenshot_path.unlink()
|
screenshot_path.unlink()
|
||||||
except Exception:
|
except Exception:
|
||||||
|
|||||||
+28
-20
@@ -40,12 +40,13 @@ def _load_config() -> dict:
|
|||||||
return {}
|
return {}
|
||||||
|
|
||||||
def _get_os() -> str:
|
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 = (
|
_SAFE_SCREENSHOT_ROOTS = (
|
||||||
Path.home(),
|
Path.home(),
|
||||||
)
|
)
|
||||||
@@ -297,23 +298,27 @@ def _focus_window(title: str) -> str:
|
|||||||
return f"focus_window: unknown OS '{os_name}'"
|
return f"focus_window: unknown OS '{os_name}'"
|
||||||
|
|
||||||
def _screen_find(description: str) -> tuple[int, int] | None:
|
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:
|
try:
|
||||||
from google import genai
|
import base64
|
||||||
from google.genai import types as gtypes
|
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()
|
_require_pyautogui()
|
||||||
w, h = pyautogui.size()
|
w, h = pyautogui.size()
|
||||||
img = pyautogui.screenshot()
|
img = pyautogui.screenshot()
|
||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
img.save(buf, format="PNG")
|
img.save(buf, format="PNG")
|
||||||
image_bytes = buf.getvalue()
|
b64 = base64.b64encode(buf.getvalue()).decode("ascii")
|
||||||
|
|
||||||
client = genai.Client(api_key=api_key)
|
|
||||||
prompt = (
|
prompt = (
|
||||||
f"This is a screenshot of a {w}×{h} pixel screen. "
|
f"This is a screenshot of a {w}×{h} pixel screen. "
|
||||||
f"Locate the UI element described as: '{description}'. "
|
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"
|
f"If the element is not visible, reply: NOT_FOUND"
|
||||||
)
|
)
|
||||||
|
|
||||||
response = client.models.generate_content(
|
resp = _req.post(
|
||||||
model="gemini-2.5-flash-lite",
|
f"{ollama_url}/api/chat",
|
||||||
contents=[
|
json={
|
||||||
gtypes.Part.from_bytes(data=image_bytes, mime_type="image/png"),
|
"model": vision_model,
|
||||||
prompt,
|
"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():
|
if "NOT_FOUND" in text.upper():
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|||||||
@@ -29,11 +29,6 @@ def _get_base_dir() -> Path:
|
|||||||
return Path(sys.executable).parent
|
return Path(sys.executable).parent
|
||||||
return Path(__file__).resolve().parent.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:
|
def _get_macos_wifi_interface() -> str:
|
||||||
try:
|
try:
|
||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
@@ -569,35 +564,24 @@ _DANGEROUS_ACTIONS = {"restart", "shutdown"}
|
|||||||
|
|
||||||
|
|
||||||
def _detect_action(description: str) -> dict:
|
def _detect_action(description: str) -> dict:
|
||||||
|
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-lite")
|
|
||||||
|
|
||||||
available = ", ".join(sorted(ACTION_MAP.keys())) + \
|
available = ", ".join(sorted(ACTION_MAP.keys())) + \
|
||||||
", volume_set, type_text, press_key, reload_n"
|
", volume_set, type_text, press_key, reload_n"
|
||||||
|
|
||||||
prompt = f"""You are an intent detector for a computer control assistant.
|
system = (
|
||||||
|
"You are an intent detector. Return ONLY a valid JSON object — "
|
||||||
The user issued a command (possibly in any language): "{description}"
|
"no explanation, no markdown."
|
||||||
|
)
|
||||||
Available actions: {available}
|
prompt = (
|
||||||
|
f'User command (any language): "{description}"\n\n'
|
||||||
Return ONLY a valid JSON object:
|
f"Available actions: {available}\n\n"
|
||||||
{{"action": "action_name", "value": null_or_value}}
|
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."
|
||||||
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."""
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
resp = model.generate_content(prompt)
|
text = call_llm_text(prompt, system=system)
|
||||||
text = re.sub(r"```(?:json)?", "", resp.text).strip().rstrip("`").strip()
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
return json.loads(text)
|
return json.loads(text)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[Settings] Intent detection failed: {e}")
|
print(f"[Settings] Intent detection failed: {e}")
|
||||||
|
|||||||
+15
-40
@@ -23,11 +23,6 @@ def _get_base_dir() -> Path:
|
|||||||
return Path(sys.executable).parent
|
return Path(sys.executable).parent
|
||||||
return Path(__file__).resolve().parent.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:
|
def _get_desktop() -> Path:
|
||||||
if _OS == "Linux":
|
if _OS == "Linux":
|
||||||
xdg = os.environ.get("XDG_DESKTOP_DIR", "")
|
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:
|
def _ask_gemini_for_desktop_action(task: str) -> str:
|
||||||
|
from core.llm_client import call_llm_text
|
||||||
|
|
||||||
import google.generativeai as genai
|
desktop = str(_get_desktop())
|
||||||
genai.configure(api_key=_get_api_key())
|
|
||||||
model = genai.GenerativeModel("gemini-2.5-flash")
|
|
||||||
|
|
||||||
desktop = str(_get_desktop())
|
|
||||||
|
|
||||||
os_specific = ""
|
os_specific = ""
|
||||||
if _OS == "Windows":
|
if _OS == "Windows":
|
||||||
os_specific = "- ctypes (Windows API calls, read-only)\n- winreg (registry READ only)"
|
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:
|
else:
|
||||||
os_specific = "- subprocess is NOT available; use pyautogui or Path only"
|
os_specific = "- subprocess is NOT available; use pyautogui or Path only"
|
||||||
|
|
||||||
prompt = f"""You are a desktop automation assistant.
|
system = (
|
||||||
Current OS: {_OS}
|
"You are a desktop automation code generator. "
|
||||||
Desktop path: {desktop}
|
"Output ONLY raw Python code — no explanation, no markdown, no backticks."
|
||||||
|
)
|
||||||
Generate safe Python code to accomplish the task below.
|
prompt = (
|
||||||
Allowed modules ONLY:
|
f"Current OS: {_OS}\nDesktop path: {desktop}\n\n"
|
||||||
- pyautogui (mouse, keyboard — if needed)
|
f"Allowed modules: pyautogui, pathlib.Path, shutil.copy2, shutil.disk_usage, time.sleep\n"
|
||||||
- pathlib.Path (file/folder inspection only, no deletion)
|
f"{os_specific}\n\n"
|
||||||
- shutil.copy2, shutil.copytree, shutil.disk_usage (NO move, NO rmtree)
|
f"Rules: NO deletion, NO subprocess, NO exec/eval, NO imports.\n"
|
||||||
- os_path (os.path equivalent, read-only)
|
f"If unsafe, output exactly: UNSAFE\n\n"
|
||||||
- time.sleep
|
f"Task: {task}"
|
||||||
{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}"""
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
code = call_llm_text(prompt, system=system).strip()
|
||||||
code = response.text.strip()
|
|
||||||
if code.startswith("```"):
|
if code.startswith("```"):
|
||||||
lines = code.split("\n")
|
lines = code.split("\n")
|
||||||
code = "\n".join(lines[1:-1]).strip()
|
code = "\n".join(lines[1:-1]).strip()
|
||||||
|
|||||||
+51
-130
@@ -13,21 +13,10 @@ def get_base_dir():
|
|||||||
|
|
||||||
|
|
||||||
BASE_DIR = get_base_dir()
|
BASE_DIR = get_base_dir()
|
||||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
|
||||||
PROJECTS_DIR = Path.home() / "Desktop" / "JarvisProjects"
|
PROJECTS_DIR = Path.home() / "Desktop" / "JarvisProjects"
|
||||||
MAX_FIX_ATTEMPTS = 5
|
MAX_FIX_ATTEMPTS = 5
|
||||||
MODEL_PLANNER = "gemini-2.5-flash"
|
|
||||||
MODEL_WRITER = "gemini-2.5-flash"
|
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
from core.llm_client import call_llm_text as _llm
|
||||||
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)
|
|
||||||
|
|
||||||
|
|
||||||
def _strip_fences(text: str) -> str:
|
def _strip_fences(text: str) -> str:
|
||||||
@@ -97,26 +86,28 @@ class RateLimitError(Exception):
|
|||||||
|
|
||||||
|
|
||||||
def _plan_project(description: str, language: str) -> dict:
|
def _plan_project(description: str, language: str) -> dict:
|
||||||
model = _get_model(MODEL_PLANNER)
|
system = (
|
||||||
|
"You are a senior software architect. "
|
||||||
prompt = f"""You are a senior software architect. Create a minimal, complete file plan for this project.
|
"Return ONLY valid JSON — no markdown, no explanation."
|
||||||
|
)
|
||||||
|
prompt = f"""Create a minimal, complete file plan for this project.
|
||||||
|
|
||||||
Language: {language}
|
Language: {language}
|
||||||
Description: {description}
|
Description: {description}
|
||||||
|
|
||||||
Return ONLY valid JSON — no markdown, no explanation:
|
Return ONLY valid JSON:
|
||||||
{{
|
{{
|
||||||
"project_name": "snake_case_name",
|
"project_name": "snake_case_name",
|
||||||
"entry_point": "main.py",
|
"entry_point": "main.py",
|
||||||
"files": [
|
"files": [
|
||||||
{{
|
{{
|
||||||
"path": "main.py",
|
"path": "main.py",
|
||||||
"description": "Entry point — what it does and which modules it imports",
|
"description": "Entry point",
|
||||||
"imports": ["utils.helpers", "core.engine"]
|
"imports": ["utils.helpers"]
|
||||||
}},
|
}},
|
||||||
{{
|
{{
|
||||||
"path": "utils/helpers.py",
|
"path": "utils/helpers.py",
|
||||||
"description": "Helper utilities — what functions it exposes",
|
"description": "Helpers",
|
||||||
"imports": []
|
"imports": []
|
||||||
}}
|
}}
|
||||||
],
|
],
|
||||||
@@ -124,25 +115,16 @@ Return ONLY valid JSON — no markdown, no explanation:
|
|||||||
"dependencies": ["requests"]
|
"dependencies": ["requests"]
|
||||||
}}
|
}}
|
||||||
|
|
||||||
Critical rules:
|
Rules: dependency order, relative paths, entry point last, stdlib NOT in dependencies.
|
||||||
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".
|
|
||||||
|
|
||||||
JSON:"""
|
JSON:"""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
raw = _strip_fences(_llm(prompt, system=system))
|
||||||
raw = _strip_fences(response.text)
|
|
||||||
return json.loads(raw)
|
return json.loads(raw)
|
||||||
except json.JSONDecodeError as e:
|
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:
|
except Exception as e:
|
||||||
if _is_rate_limit(e):
|
|
||||||
raise RateLimitError(str(e))
|
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def _write_file(
|
def _write_file(
|
||||||
@@ -153,80 +135,43 @@ def _write_file(
|
|||||||
project_dir: Path,
|
project_dir: Path,
|
||||||
already_written: dict[str, str],
|
already_written: dict[str, 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_imports = file_info.get("imports", [])
|
||||||
|
|
||||||
file_list = "\n".join(
|
file_list = "\n".join(
|
||||||
f" [{i+1}] {f['path']}: {f.get('description', '')}"
|
f" [{i+1}] {f['path']}: {f.get('description', '')}"
|
||||||
for i, f in enumerate(all_files)
|
for i, f in enumerate(all_files)
|
||||||
)
|
)
|
||||||
|
dep_ctx = ""
|
||||||
dependency_context = ""
|
|
||||||
for dep_dotted in file_imports:
|
for dep_dotted in file_imports:
|
||||||
dep_path = dep_dotted.replace(".", "/") + ".py"
|
dep_path = dep_dotted.replace(".", "/") + ".py"
|
||||||
if dep_path in already_written:
|
if dep_path in already_written:
|
||||||
code_snippet = already_written[dep_path][:2000]
|
dep_ctx += f"\n\n--- {dep_path} ---\n{already_written[dep_path][:2000]}"
|
||||||
dependency_context += f"\n\n--- {dep_path} (you must import from this) ---\n{code_snippet}"
|
|
||||||
|
|
||||||
lang_rules = ""
|
system = (
|
||||||
if language.lower() == "python":
|
f"You are a senior {language} developer. "
|
||||||
lang_rules = """
|
"Output ONLY raw code — no explanation, no markdown, no backticks."
|
||||||
Python-specific rules:
|
)
|
||||||
- Use type hints for all function signatures.
|
prompt = (
|
||||||
- Add docstrings for all public functions and classes.
|
f"Project goal: {project_description}\n\n"
|
||||||
- Use if __name__ == "__main__": guard in the entry point.
|
f"Files (dependency order):\n{file_list}\n"
|
||||||
- For relative imports within the project, use: from utils.helpers import foo (match the project structure exactly).
|
f"{dep_ctx}\n\n"
|
||||||
- Do NOT use implicit relative imports (from . import ...) unless it's a proper package with __init__.py.
|
f"Write complete code for: {file_path}\n"
|
||||||
- If this is a package subdirectory, create __init__.py files where needed."""
|
f"Purpose: {file_desc}\n"
|
||||||
elif language.lower() in ("javascript", "typescript", "js", "ts"):
|
f"{'Imports from: ' + ', '.join(file_imports) if file_imports else 'No project-internal imports.'}\n\n"
|
||||||
lang_rules = """
|
f"Rules: COMPLETE & RUNNABLE code, no placeholders, match import paths exactly.\n\n"
|
||||||
JS/TS-specific rules:
|
f"Code for {file_path}:"
|
||||||
- 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}:"""
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
code = _strip_fences(_llm(prompt, system=system))
|
||||||
code = _strip_fences(response.text)
|
|
||||||
|
|
||||||
full_path = project_dir / file_path
|
full_path = project_dir / file_path
|
||||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
full_path.write_text(code, encoding="utf-8")
|
full_path.write_text(code, encoding="utf-8")
|
||||||
|
|
||||||
print(f"[DevAgent] ✅ Written: {file_path} ({len(code)} chars)")
|
print(f"[DevAgent] ✅ Written: {file_path} ({len(code)} chars)")
|
||||||
return code
|
return code
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if _is_rate_limit(e):
|
|
||||||
raise RateLimitError(str(e))
|
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def _install_dependencies(dependencies: list[str], project_dir: Path) -> str:
|
def _install_dependencies(dependencies: list[str], project_dir: Path) -> str:
|
||||||
@@ -350,13 +295,10 @@ def _fix_files(
|
|||||||
entry_point: str,
|
entry_point: str,
|
||||||
) -> dict[str, str]:
|
) -> dict[str, str]:
|
||||||
|
|
||||||
model = _get_model(MODEL_PLANNER)
|
|
||||||
|
|
||||||
error_file, error_line = _parse_traceback(error_output, list(file_codes.keys()))
|
error_file, error_line = _parse_traceback(error_output, list(file_codes.keys()))
|
||||||
error_type = _classify_error(error_output)
|
error_type = _classify_error(error_output)
|
||||||
|
|
||||||
files_to_fix: list[str] = []
|
files_to_fix: list[str] = []
|
||||||
|
|
||||||
if error_file:
|
if error_file:
|
||||||
files_to_fix.append(error_file)
|
files_to_fix.append(error_file)
|
||||||
if error_type == "import_error":
|
if error_type == "import_error":
|
||||||
@@ -370,61 +312,40 @@ def _fix_files(
|
|||||||
|
|
||||||
updated_codes: dict[str, str] = {}
|
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:
|
for fix_path in files_to_fix:
|
||||||
current_code = file_codes.get(fix_path, "")
|
current_code = file_codes.get(fix_path, "")
|
||||||
|
|
||||||
other_ctx = ""
|
other_ctx = ""
|
||||||
for fp, code in file_codes.items():
|
for fp, code in file_codes.items():
|
||||||
if fp != fix_path and code:
|
if fp != fix_path and code:
|
||||||
snippet = code[:1500] + ("..." if len(code) > 1500 else "")
|
other_ctx += f"\n--- {fp} ---\n{code[:1500]}\n"
|
||||||
other_ctx += f"\n--- {fp} ---\n{snippet}\n"
|
|
||||||
|
|
||||||
line_hint = f"\nError appears to be near line {error_line} in this file." if (
|
line_hint = (
|
||||||
error_line and fix_path == error_file
|
f"\nError near line {error_line} in this file."
|
||||||
) else ""
|
if error_line and fix_path == error_file else ""
|
||||||
|
)
|
||||||
|
|
||||||
prompt = f"""You are an expert {language} debugger. Fix the broken file below.
|
prompt = (
|
||||||
|
f"Project goal: {project_description}\n\n"
|
||||||
Project goal: {project_description}
|
f"All files:\n"
|
||||||
|
+ "\n".join(f" - {f['path']}: {f.get('description', '')}" for f in all_files)
|
||||||
All project files:
|
+ f"\n\nOther files (context):\n{other_ctx[:3500]}\n\n"
|
||||||
{chr(10).join(f" - {f['path']}: {f.get('description', '')}" for f in all_files)}
|
f"File to fix: {fix_path}{line_hint}\n"
|
||||||
|
f"Error type: {error_type}\n\n"
|
||||||
Other files for context (read-only — fix only the target file):
|
f"Error output:\n{error_output[:2500]}\n\n"
|
||||||
{other_ctx[:3500]}
|
f"Current code:\n{current_code}\n\n"
|
||||||
|
f"Fixed code for {fix_path}:"
|
||||||
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}:"""
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
fixed = _strip_fences(_llm(prompt, system=system))
|
||||||
fixed = _strip_fences(response.text)
|
|
||||||
|
|
||||||
full_path = project_dir / fix_path
|
full_path = project_dir / fix_path
|
||||||
full_path.parent.mkdir(parents=True, exist_ok=True)
|
full_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
full_path.write_text(fixed, encoding="utf-8")
|
full_path.write_text(fixed, encoding="utf-8")
|
||||||
|
|
||||||
updated_codes[fix_path] = fixed
|
updated_codes[fix_path] = fixed
|
||||||
print(f"[DevAgent] 🔧 Fixed: {fix_path}")
|
print(f"[DevAgent] 🔧 Fixed: {fix_path}")
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
if _is_rate_limit(e):
|
|
||||||
raise RateLimitError(str(e))
|
|
||||||
print(f"[DevAgent] ⚠️ Could not fix {fix_path}: {e}")
|
print(f"[DevAgent] ⚠️ Could not fix {fix_path}: {e}")
|
||||||
|
|
||||||
return updated_codes
|
return updated_codes
|
||||||
|
|||||||
@@ -25,18 +25,19 @@ import tempfile
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
import google.generativeai as genai
|
from core.llm_client import call_llm_text as _llm_text
|
||||||
|
|
||||||
|
|
||||||
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"]
|
|
||||||
|
|
||||||
|
|
||||||
def _gemini_client():
|
def _gemini_client():
|
||||||
genai.configure(api_key=_get_api_key())
|
# Compatibility shim — returns an object with .generate_content()
|
||||||
return genai.GenerativeModel("gemini-2.5-flash")
|
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:
|
def _detect_type(path: Path) -> str:
|
||||||
|
|||||||
+14
-27
@@ -18,10 +18,6 @@ BASE_DIR = _get_base_dir()
|
|||||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
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] = {
|
_MONTH_MAP: dict[str, int] = {
|
||||||
|
|
||||||
"january": 1, "february": 2, "march": 3, "april": 4,
|
"january": 1, "february": 2, "march": 3, "april": 4,
|
||||||
@@ -62,19 +58,16 @@ def _parse_date(raw: str) -> str:
|
|||||||
return val.strftime("%Y-%m-%d")
|
return val.strftime("%Y-%m-%d")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import google.generativeai as genai
|
from core.llm_client import call_llm_text
|
||||||
genai.configure(api_key=_get_api_key())
|
result = call_llm_text(
|
||||||
model = genai.GenerativeModel("gemini-2.5-flash-lite")
|
|
||||||
response = model.generate_content(
|
|
||||||
f"Today is {today.strftime('%Y-%m-%d')}. "
|
f"Today is {today.strftime('%Y-%m-%d')}. "
|
||||||
f"Convert this date expression to YYYY-MM-DD: '{raw}'. "
|
f"Convert this date expression to YYYY-MM-DD: '{raw}'. "
|
||||||
f"Return ONLY the date string, nothing else."
|
f"Return ONLY the date string, nothing else."
|
||||||
)
|
).strip()
|
||||||
result = response.text.strip()
|
|
||||||
if re.match(r"\d{4}-\d{2}-\d{2}", result):
|
if re.match(r"\d{4}-\d{2}-\d{2}", result):
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
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():
|
for month_name, month_num in _MONTH_MAP.items():
|
||||||
if month_name in lower:
|
if month_name in lower:
|
||||||
@@ -152,34 +145,28 @@ def _parse_flights_with_gemini(
|
|||||||
destination: str,
|
destination: str,
|
||||||
date: str,
|
date: str,
|
||||||
) -> list[dict]:
|
) -> list[dict]:
|
||||||
import google.generativeai as genai
|
from core.llm_client import call_llm_text
|
||||||
|
|
||||||
genai.configure(api_key=_get_api_key())
|
system = (
|
||||||
model = genai.GenerativeModel(
|
"You are a flight data extraction expert. "
|
||||||
model_name="gemini-2.5-flash",
|
"Extract flight information from raw webpage text. "
|
||||||
system_instruction=(
|
"Return ONLY valid JSON — no markdown, no explanation."
|
||||||
"You are a flight data extraction expert. "
|
|
||||||
"Extract flight information from raw webpage text. "
|
|
||||||
"Return ONLY valid JSON — no markdown, no explanation."
|
|
||||||
),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
prompt = (
|
prompt = (
|
||||||
f"Extract flight options from {origin} to {destination} on {date} "
|
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"Return a JSON array of up to 5 flights:\n"
|
||||||
f'[{{"airline":"...","departure":"HH:MM","arrival":"HH:MM",'
|
f'[{{"airline":"...","departure":"HH:MM","arrival":"HH:MM",'
|
||||||
f'"duration":"Xh Ym","stops":0,"price":"...","currency":"USD"}}]\n'
|
f'"duration":"Xh Ym","stops":0,"price":"...","currency":"USD"}}]\n'
|
||||||
f"If no flights found, return: []"
|
f"If no flights found, return: []"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
text = call_llm_text(prompt, system=system)
|
||||||
text = re.sub(r"```(?:json)?", "", response.text).strip().rstrip("`").strip()
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
flights = json.loads(text)
|
flights = json.loads(text)
|
||||||
return flights if isinstance(flights, list) else []
|
return flights if isinstance(flights, list) else []
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[FlightFinder] ⚠️ Gemini parse failed: {e}")
|
print(f"[FlightFinder] ⚠️ LLM parse failed: {e}")
|
||||||
return []
|
return []
|
||||||
|
|
||||||
def _format_spoken(
|
def _format_spoken(
|
||||||
|
|||||||
+272
-442
@@ -1,442 +1,272 @@
|
|||||||
from __future__ import annotations
|
"""
|
||||||
|
MARK XL — Screen / Camera Processor
|
||||||
import asyncio
|
Replaces Gemini Live vision session with a direct Ollama vision-model call.
|
||||||
import base64
|
The analysis text is returned (and optionally spoken via the `speak` callback).
|
||||||
import io
|
"""
|
||||||
import json
|
from __future__ import annotations
|
||||||
import re
|
|
||||||
import sys
|
import base64
|
||||||
import threading
|
import io
|
||||||
import time
|
import json
|
||||||
from pathlib import Path
|
import sys
|
||||||
from typing import Optional
|
from pathlib import Path
|
||||||
|
from typing import Optional, Callable
|
||||||
import numpy as np
|
|
||||||
import sounddevice as sd
|
try:
|
||||||
|
import cv2
|
||||||
try:
|
_CV2 = True
|
||||||
import cv2
|
except ImportError:
|
||||||
_CV2 = True
|
_CV2 = False
|
||||||
except ImportError:
|
|
||||||
_CV2 = False
|
try:
|
||||||
|
import mss
|
||||||
try:
|
import mss.tools
|
||||||
import mss
|
_MSS = True
|
||||||
import mss.tools
|
except ImportError:
|
||||||
_MSS = True
|
_MSS = False
|
||||||
except ImportError:
|
|
||||||
_MSS = False
|
try:
|
||||||
|
import PIL.Image
|
||||||
try:
|
_PIL = True
|
||||||
import PIL.Image
|
except ImportError:
|
||||||
_PIL = True
|
_PIL = False
|
||||||
except ImportError:
|
|
||||||
_PIL = False
|
import platform
|
||||||
|
|
||||||
from google import genai
|
import requests
|
||||||
from google.genai import types as gtypes
|
|
||||||
|
|
||||||
def _base_dir() -> Path:
|
def _base_dir() -> Path:
|
||||||
if getattr(sys, "frozen", False):
|
if getattr(sys, "frozen", False):
|
||||||
return Path(sys.executable).parent
|
return Path(sys.executable).parent
|
||||||
return Path(__file__).resolve().parent.parent
|
return Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
_BASE = _base_dir()
|
_BASE = _base_dir()
|
||||||
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
||||||
|
|
||||||
|
_IMG_MAX_W = 640
|
||||||
def _load_config() -> dict:
|
_IMG_MAX_H = 360
|
||||||
try:
|
_JPEG_Q = 60
|
||||||
return json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
|
|
||||||
except Exception:
|
|
||||||
return {}
|
def _load_config() -> dict:
|
||||||
|
try:
|
||||||
|
return json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
|
||||||
def _save_config_key(key: str, value) -> None:
|
except Exception:
|
||||||
try:
|
return {}
|
||||||
cfg = _load_config()
|
|
||||||
cfg[key] = value
|
|
||||||
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
def _save_config_key(key: str, value) -> None:
|
||||||
except Exception as e:
|
try:
|
||||||
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
cfg = _load_config()
|
||||||
|
cfg[key] = value
|
||||||
|
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
||||||
def _get_api_key() -> str:
|
except Exception as e:
|
||||||
key = _load_config().get("gemini_api_key", "")
|
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
||||||
if not key:
|
|
||||||
raise RuntimeError("gemini_api_key not found in config.")
|
|
||||||
return key
|
def _get_os() -> str:
|
||||||
|
s = platform.system().lower()
|
||||||
|
if s == "darwin": return "mac"
|
||||||
def _get_os() -> str:
|
if s == "windows": return "windows"
|
||||||
return _load_config().get("os_system", "windows").lower()
|
return "linux"
|
||||||
|
|
||||||
_LIVE_MODEL = "models/gemini-2.5-flash-native-audio-preview-12-2025"
|
|
||||||
_CHANNELS = 1
|
# ---------------------------------------------------------------------------
|
||||||
_RECEIVE_SAMPLE_RATE = 24_000
|
# Image capture helpers (unchanged from original)
|
||||||
_CHUNK_SIZE = 1_024
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
_IMG_MAX_W = 640
|
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
||||||
_IMG_MAX_H = 360
|
if not _PIL:
|
||||||
_JPEG_Q = 60
|
return img_bytes, f"image/{source_format.lower()}"
|
||||||
|
try:
|
||||||
_SYSTEM_PROMPT = (
|
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
||||||
"You are JARVIS, an advanced AI assistant. "
|
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||||
"Analyze the provided image with precision and intelligence. "
|
buf = io.BytesIO()
|
||||||
"Be concise and direct — maximum two sentences unless the user's question "
|
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
||||||
"requires more detail. "
|
return buf.getvalue(), "image/jpeg"
|
||||||
"Address the user respectfully. "
|
except Exception as e:
|
||||||
"Always call the appropriate tool; never simulate results."
|
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
||||||
)
|
return img_bytes, f"image/{source_format.lower()}"
|
||||||
|
|
||||||
|
|
||||||
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
def _capture_screen() -> tuple[bytes, str]:
|
||||||
if not _PIL:
|
if not _MSS:
|
||||||
return img_bytes, f"image/{source_format.lower()}"
|
raise RuntimeError("mss is not installed. Run: pip install mss")
|
||||||
|
with mss.mss() as sct:
|
||||||
try:
|
monitors = sct.monitors
|
||||||
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
||||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
shot = sct.grab(target)
|
||||||
buf = io.BytesIO()
|
png = mss.tools.to_png(shot.rgb, shot.size)
|
||||||
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
return _compress(png, "PNG")
|
||||||
return buf.getvalue(), "image/jpeg"
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
def _cv2_backend() -> int:
|
||||||
return img_bytes, f"image/{source_format.lower()}"
|
if not _CV2:
|
||||||
|
return 0
|
||||||
def _capture_screen() -> tuple[bytes, str]:
|
os_name = _get_os()
|
||||||
|
if os_name == "windows":
|
||||||
if not _MSS:
|
return cv2.CAP_DSHOW
|
||||||
raise RuntimeError("mss is not installed. Run: pip install mss")
|
if os_name == "mac":
|
||||||
|
return cv2.CAP_AVFOUNDATION
|
||||||
with mss.mss() as sct:
|
return cv2.CAP_ANY
|
||||||
monitors = sct.monitors # [0] = all combined, [1..n] = real screens
|
|
||||||
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
|
||||||
shot = sct.grab(target)
|
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
||||||
png = mss.tools.to_png(shot.rgb, shot.size)
|
if not _CV2:
|
||||||
|
return False
|
||||||
return _compress(png, "PNG")
|
import numpy as np
|
||||||
|
cap = cv2.VideoCapture(index, backend)
|
||||||
|
if not cap.isOpened():
|
||||||
def _cv2_backend() -> int:
|
cap.release(); return False
|
||||||
"""Return the best OpenCV camera backend for the current OS."""
|
for _ in range(warmup):
|
||||||
if not _CV2:
|
cap.read()
|
||||||
return 0
|
ret, frame = cap.read()
|
||||||
os_name = _get_os()
|
cap.release()
|
||||||
if os_name == "windows":
|
if not ret or frame is None:
|
||||||
return cv2.CAP_DSHOW
|
return False
|
||||||
if os_name == "mac":
|
return bool(np.mean(frame) > 8)
|
||||||
return cv2.CAP_AVFOUNDATION
|
|
||||||
return cv2.CAP_ANY
|
|
||||||
|
def _detect_camera_index() -> int:
|
||||||
|
backend = _cv2_backend()
|
||||||
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
print("[Vision] 🔍 Auto-detecting camera…")
|
||||||
|
for idx in range(6):
|
||||||
if not _CV2:
|
if _probe_camera(idx, backend):
|
||||||
return False
|
print(f"[Vision] ✅ Camera found at index {idx}")
|
||||||
cap = cv2.VideoCapture(index, backend)
|
_save_config_key("camera_index", idx)
|
||||||
if not cap.isOpened():
|
return idx
|
||||||
cap.release()
|
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
||||||
return False
|
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
||||||
for _ in range(warmup):
|
_save_config_key("camera_index", 0)
|
||||||
cap.read()
|
return 0
|
||||||
ret, frame = cap.read()
|
|
||||||
cap.release()
|
|
||||||
if not ret or frame is None:
|
def _get_camera_index() -> int:
|
||||||
return False
|
cfg = _load_config()
|
||||||
return bool(np.mean(frame) > 8)
|
if "camera_index" in cfg:
|
||||||
|
return int(cfg["camera_index"])
|
||||||
|
return _detect_camera_index()
|
||||||
def _detect_camera_index() -> int:
|
|
||||||
|
|
||||||
backend = _cv2_backend()
|
def _capture_camera() -> tuple[bytes, str]:
|
||||||
print("[Vision] 🔍 Auto-detecting camera...")
|
if not _CV2:
|
||||||
for idx in range(6):
|
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
||||||
if _probe_camera(idx, backend):
|
import numpy as np
|
||||||
print(f"[Vision] ✅ Camera found at index {idx}")
|
index = _get_camera_index()
|
||||||
_save_config_key("camera_index", idx)
|
backend = _cv2_backend()
|
||||||
return idx
|
cap = cv2.VideoCapture(index, backend)
|
||||||
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
if not cap.isOpened():
|
||||||
|
raise RuntimeError(f"Camera index {index} could not be opened.")
|
||||||
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
for _ in range(10):
|
||||||
_save_config_key("camera_index", 0)
|
cap.read()
|
||||||
return 0
|
ret, frame = cap.read()
|
||||||
|
cap.release()
|
||||||
|
if not ret or frame is None:
|
||||||
def _get_camera_index() -> int:
|
raise RuntimeError("Camera returned no frame.")
|
||||||
cfg = _load_config()
|
if _PIL:
|
||||||
if "camera_index" in cfg:
|
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||||
return int(cfg["camera_index"])
|
img = PIL.Image.fromarray(rgb)
|
||||||
return _detect_camera_index()
|
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||||
|
buf = io.BytesIO()
|
||||||
|
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
||||||
def _capture_camera() -> tuple[bytes, str]:
|
return buf.getvalue(), "image/jpeg"
|
||||||
if not _CV2:
|
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
||||||
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
return buf.tobytes(), "image/jpeg"
|
||||||
|
|
||||||
index = _get_camera_index()
|
|
||||||
backend = _cv2_backend()
|
# ---------------------------------------------------------------------------
|
||||||
cap = cv2.VideoCapture(index, backend)
|
# Vision analysis via Ollama
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
if not cap.isOpened():
|
|
||||||
raise RuntimeError(f"Camera index {index} could not be opened.")
|
_SYSTEM_PROMPT = (
|
||||||
|
"You are JARVIS, an advanced AI assistant. "
|
||||||
for _ in range(10):
|
"Analyze the provided image with precision and intelligence. "
|
||||||
cap.read()
|
"Be concise and direct — maximum two sentences unless the user's question "
|
||||||
|
"requires more detail. "
|
||||||
ret, frame = cap.read()
|
"Address the user respectfully."
|
||||||
cap.release()
|
)
|
||||||
|
|
||||||
if not ret or frame is None:
|
|
||||||
raise RuntimeError("Camera returned no frame.")
|
def _call_vision(image_bytes: bytes, mime: str, user_text: str) -> str:
|
||||||
|
cfg = _load_config()
|
||||||
if _PIL:
|
url = cfg.get("llm_url", "http://localhost:11434").rstrip("/")
|
||||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
vision_model = cfg.get("vision_model") or cfg.get("llm_model", "llava")
|
||||||
img = PIL.Image.fromarray(rgb)
|
|
||||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
b64 = base64.b64encode(image_bytes).decode("ascii")
|
||||||
buf = io.BytesIO()
|
|
||||||
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
payload = {
|
||||||
return buf.getvalue(), "image/jpeg"
|
"model": vision_model,
|
||||||
|
"stream": False,
|
||||||
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
"messages": [
|
||||||
return buf.tobytes(), "image/jpeg"
|
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||||
|
{
|
||||||
class _VisionSession:
|
"role": "user",
|
||||||
def __init__(self):
|
"content": user_text,
|
||||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
"images": [b64],
|
||||||
self._thread: Optional[threading.Thread] = None
|
},
|
||||||
self._session = None
|
],
|
||||||
self._out_queue: Optional[asyncio.Queue] = None
|
}
|
||||||
self._audio_in: Optional[asyncio.Queue] = None
|
try:
|
||||||
self._ready_evt: threading.Event = threading.Event()
|
resp = requests.post(f"{url}/api/chat", json=payload, timeout=60)
|
||||||
self._player = None
|
resp.raise_for_status()
|
||||||
self._lock: threading.Lock = threading.Lock()
|
return (resp.json().get("message", {}).get("content") or "").strip()
|
||||||
|
except requests.exceptions.ConnectionError:
|
||||||
def start(self, player=None, timeout: float = 25.0) -> None:
|
return "Cannot connect to Ollama. Make sure Ollama is running."
|
||||||
with self._lock:
|
except Exception as e:
|
||||||
if self._thread and self._thread.is_alive():
|
return f"Vision analysis failed: {e}"
|
||||||
if player is not None:
|
|
||||||
self._player = player
|
|
||||||
return
|
# ---------------------------------------------------------------------------
|
||||||
self._player = player
|
# Public entry point
|
||||||
self._thread = threading.Thread(
|
# ---------------------------------------------------------------------------
|
||||||
target=self._run_event_loop,
|
|
||||||
daemon=True,
|
def screen_process(
|
||||||
name="VisionSessionThread",
|
parameters: dict,
|
||||||
)
|
response=None,
|
||||||
self._thread.start()
|
player=None,
|
||||||
|
session_memory=None,
|
||||||
if not self._ready_evt.wait(timeout=timeout):
|
speak: Optional[Callable[[str], None]] = None,
|
||||||
raise RuntimeError(f"Vision session did not connect within {timeout}s.")
|
) -> str:
|
||||||
print("[Vision] ✅ Session ready")
|
"""
|
||||||
|
Capture screen or camera, analyse with Ollama vision model.
|
||||||
def analyze(self, image_bytes: bytes, mime_type: str, user_text: str) -> None:
|
|
||||||
if not self._loop or not self._out_queue:
|
Returns the analysis text (str).
|
||||||
print("[Vision] ⚠️ Session not started — dropping request")
|
Optionally speaks via `speak` callback and logs to `player`.
|
||||||
return
|
"""
|
||||||
asyncio.run_coroutine_threadsafe(
|
params = parameters or {}
|
||||||
self._out_queue.put((image_bytes, mime_type, user_text)),
|
user_text = (params.get("text") or params.get("user_text") or "").strip()
|
||||||
self._loop,
|
angle = params.get("angle", "screen").lower().strip()
|
||||||
)
|
|
||||||
|
if not user_text:
|
||||||
def is_ready(self) -> bool:
|
user_text = "What do you see? Describe briefly."
|
||||||
return self._session is not None
|
|
||||||
|
if player:
|
||||||
def _run_event_loop(self) -> None:
|
player.write_log(f"SYS: Vision [{angle}] — {user_text[:60]}")
|
||||||
self._loop = asyncio.new_event_loop()
|
|
||||||
asyncio.set_event_loop(self._loop)
|
# Capture
|
||||||
self._loop.run_until_complete(self._session_loop())
|
try:
|
||||||
|
if angle == "camera":
|
||||||
async def _session_loop(self) -> None:
|
image_bytes, mime = _capture_camera()
|
||||||
self._out_queue = asyncio.Queue(maxsize=30)
|
print(f"[Vision] 📷 Camera: {len(image_bytes):,} bytes")
|
||||||
self._audio_in = asyncio.Queue()
|
else:
|
||||||
|
image_bytes, mime = _capture_screen()
|
||||||
client = genai.Client(
|
print(f"[Vision] 🖥️ Screen: {len(image_bytes):,} bytes")
|
||||||
api_key=_get_api_key(),
|
except Exception as e:
|
||||||
http_options={"api_version": "v1beta"},
|
msg = f"Capture error: {e}"
|
||||||
)
|
print(f"[Vision] ❌ {msg}")
|
||||||
config = gtypes.LiveConnectConfig(
|
if player: player.write_log(f"ERR: {msg}")
|
||||||
response_modalities=["AUDIO"],
|
return msg
|
||||||
output_audio_transcription={},
|
|
||||||
system_instruction=_SYSTEM_PROMPT,
|
# Analyse
|
||||||
speech_config=gtypes.SpeechConfig(
|
analysis = _call_vision(image_bytes, mime, user_text)
|
||||||
voice_config=gtypes.VoiceConfig(
|
print(f"[Vision] 💬 {analysis[:120]}")
|
||||||
prebuilt_voice_config=gtypes.PrebuiltVoiceConfig(
|
|
||||||
voice_name="Charon"
|
if player:
|
||||||
)
|
player.write_log(f"Jarvis: {analysis}")
|
||||||
)
|
|
||||||
),
|
if speak and analysis:
|
||||||
)
|
speak(analysis)
|
||||||
|
|
||||||
backoff = 2.0
|
return analysis
|
||||||
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.")
|
|
||||||
+117
-141
@@ -1,141 +1,117 @@
|
|||||||
#web_search.py
|
# web_search.py
|
||||||
import json
|
# Gemini grounded-search replaced with DuckDuckGo + Ollama LLM summarization.
|
||||||
import sys
|
import json
|
||||||
from pathlib import Path
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
def _get_base_dir() -> Path:
|
|
||||||
if getattr(sys, "frozen", False):
|
|
||||||
return Path(sys.executable).parent
|
def _get_base_dir() -> Path:
|
||||||
return Path(__file__).resolve().parent.parent
|
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"
|
|
||||||
|
BASE_DIR = _get_base_dir()
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||||
return json.load(f)["gemini_api_key"]
|
try:
|
||||||
|
from ddgs import DDGS
|
||||||
|
except ImportError:
|
||||||
def _gemini_search(query: str) -> str:
|
from duckduckgo_search import DDGS
|
||||||
from google import genai
|
|
||||||
|
results = []
|
||||||
client = genai.Client(api_key=_get_api_key())
|
with DDGS() as ddgs:
|
||||||
response = client.models.generate_content(
|
for r in ddgs.text(query, max_results=max_results):
|
||||||
model="gemini-2.5-flash",
|
results.append({
|
||||||
contents=query,
|
"title": r.get("title", ""),
|
||||||
config={"tools": [{"google_search": {}}]},
|
"snippet": r.get("body", ""),
|
||||||
)
|
"url": r.get("href", ""),
|
||||||
|
})
|
||||||
text = ""
|
return results
|
||||||
for part in response.candidates[0].content.parts:
|
|
||||||
if hasattr(part, "text") and part.text:
|
|
||||||
text += part.text
|
def _format_ddg(query: str, results: list[dict]) -> str:
|
||||||
|
if not results:
|
||||||
text = text.strip()
|
return f"No results found for: {query}"
|
||||||
if not text:
|
lines = [f"Search results for: {query}\n"]
|
||||||
raise ValueError("Gemini returned an empty response.")
|
for i, r in enumerate(results, 1):
|
||||||
return text
|
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']}")
|
||||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
lines.append("")
|
||||||
try:
|
return "\n".join(lines).strip()
|
||||||
from ddgs import DDGS
|
|
||||||
except ImportError:
|
|
||||||
from duckduckgo_search import DDGS
|
def _llm_summarize(query: str, raw_results: str) -> str:
|
||||||
|
try:
|
||||||
results = []
|
from core.llm_client import call_llm_text
|
||||||
with DDGS() as ddgs:
|
system = (
|
||||||
for r in ddgs.text(query, max_results=max_results):
|
"You are JARVIS. Summarize web search results clearly and concisely. "
|
||||||
results.append({
|
"Answer the user's query directly. Be factual. Address user as 'sir'."
|
||||||
"title": r.get("title", ""),
|
)
|
||||||
"snippet": r.get("body", ""),
|
prompt = (
|
||||||
"url": r.get("href", ""),
|
f"User question: {query}\n\n"
|
||||||
})
|
f"Web search results:\n{raw_results[:4000]}\n\n"
|
||||||
return results
|
"Answer the question based on these results:"
|
||||||
|
)
|
||||||
|
return call_llm_text(prompt, system=system)
|
||||||
def _format_ddg(query: str, results: list[dict]) -> str:
|
except Exception:
|
||||||
if not results:
|
return raw_results
|
||||||
return f"No results found for: {query}"
|
|
||||||
|
|
||||||
lines = [f"Search results for: {query}\n"]
|
def _compare(items: list[str], aspect: str) -> str:
|
||||||
for i, r in enumerate(results, 1):
|
all_results: dict[str, list] = {}
|
||||||
if r.get("title"): lines.append(f"{i}. {r['title']}")
|
for item in items:
|
||||||
if r.get("snippet"): lines.append(f" {r['snippet']}")
|
try:
|
||||||
if r.get("url"): lines.append(f" {r['url']}")
|
all_results[item] = _ddg_search(f"{item} {aspect}", max_results=3)
|
||||||
lines.append("")
|
except Exception:
|
||||||
return "\n".join(lines).strip()
|
all_results[item] = []
|
||||||
|
|
||||||
def _compare(items: list[str], aspect: str) -> str:
|
lines = [f"Comparison — {aspect.upper()}", "─" * 40]
|
||||||
query = (
|
for item in items:
|
||||||
f"Compare {', '.join(items)} in terms of {aspect}. "
|
lines.append(f"\n▸ {item}")
|
||||||
"Give specific facts and data."
|
for r in all_results.get(item, [])[:2]:
|
||||||
)
|
if r.get("snippet"):
|
||||||
try:
|
lines.append(f" • {r['snippet']}")
|
||||||
return _gemini_search(query)
|
raw = "\n".join(lines)
|
||||||
except Exception as e:
|
return _llm_summarize(f"Compare {', '.join(items)} regarding {aspect}", raw)
|
||||||
print(f"[WebSearch] ⚠️ Gemini compare failed: {e} — falling back to DDG")
|
|
||||||
|
|
||||||
# DDG fallback: fetch results per item and merge
|
def web_search(
|
||||||
all_results: dict[str, list] = {}
|
parameters: dict,
|
||||||
for item in items:
|
response=None,
|
||||||
try:
|
player=None,
|
||||||
all_results[item] = _ddg_search(f"{item} {aspect}", max_results=3)
|
session_memory=None,
|
||||||
except Exception:
|
) -> str:
|
||||||
all_results[item] = []
|
params = parameters or {}
|
||||||
|
query = params.get("query", "").strip()
|
||||||
lines = [f"Comparison — {aspect.upper()}", "─" * 40]
|
mode = params.get("mode", "search").lower().strip()
|
||||||
for item in items:
|
items = params.get("items", [])
|
||||||
lines.append(f"\n▸ {item}")
|
aspect = params.get("aspect", "general").strip() or "general"
|
||||||
for r in all_results.get(item, [])[:2]:
|
|
||||||
if r.get("snippet"):
|
if not query and not items:
|
||||||
lines.append(f" • {r['snippet']}")
|
return "Please provide a search query, sir."
|
||||||
return "\n".join(lines)
|
|
||||||
|
if items and mode != "compare":
|
||||||
def web_search(
|
mode = "compare"
|
||||||
parameters: dict,
|
|
||||||
response=None,
|
if player:
|
||||||
player=None,
|
player.write_log(f"[Search] {query or ', '.join(items)}")
|
||||||
session_memory=None,
|
|
||||||
) -> str:
|
print(f"[WebSearch] 🔍 Query: {query!r} Mode: {mode}")
|
||||||
params = parameters or {}
|
|
||||||
query = params.get("query", "").strip()
|
try:
|
||||||
mode = params.get("mode", "search").lower().strip()
|
if mode == "compare" and items:
|
||||||
items = params.get("items", [])
|
print(f"[WebSearch] 📊 Comparing: {items}")
|
||||||
aspect = params.get("aspect", "general").strip() or "general"
|
return _compare(items, aspect)
|
||||||
|
|
||||||
if not query and not items:
|
results = _ddg_search(query)
|
||||||
return "Please provide a search query, sir."
|
raw = _format_ddg(query, results)
|
||||||
|
print(f"[WebSearch] ✅ DDG: {len(results)} result(s).")
|
||||||
if items and mode != "compare":
|
# Let Ollama summarise the results for a cleaner spoken response
|
||||||
mode = "compare"
|
return _llm_summarize(query, raw)
|
||||||
|
|
||||||
if player:
|
except Exception as e:
|
||||||
player.write_log(f"[Search] {query or ', '.join(items)}")
|
print(f"[WebSearch] ❌ Failed: {e}")
|
||||||
|
return f"Search failed, sir: {e}"
|
||||||
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}"
|
|
||||||
+11
-22
@@ -48,11 +48,6 @@ HEADERS = {
|
|||||||
_YT_VIDEO_FILTER = "EgIQAQ%3D%3D"
|
_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:
|
def _open_url(url: str) -> None:
|
||||||
try:
|
try:
|
||||||
if is_mac():
|
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:
|
def _summarize_with_gemini(transcript: str, video_url: str) -> str:
|
||||||
import google.generativeai as genai
|
from core.llm_client import call_llm_text
|
||||||
|
system = (
|
||||||
genai.configure(api_key=_get_api_key())
|
"You are JARVIS, an AI assistant. "
|
||||||
model = genai.GenerativeModel(
|
"Summarize YouTube video transcripts clearly and concisely. "
|
||||||
model_name="gemini-2.5-flash",
|
"Structure: 1-sentence overview, then 3-5 key points. "
|
||||||
system_instruction=(
|
"Be direct. Address the user as 'sir'. "
|
||||||
"You are JARVIS, an AI assistant. "
|
"Match the language of the transcript."
|
||||||
"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 = 12000
|
||||||
max_chars = 80000
|
|
||||||
truncated = transcript[:max_chars] + ("..." if len(transcript) > max_chars else "")
|
truncated = transcript[:max_chars] + ("..." if len(transcript) > max_chars else "")
|
||||||
response = model.generate_content(
|
return call_llm_text(
|
||||||
f"Please summarize this YouTube video transcript:\n\n{truncated}"
|
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:
|
def _save_summary(content: str, video_url: str) -> str:
|
||||||
|
|||||||
+149
-197
@@ -1,197 +1,149 @@
|
|||||||
import json
|
"""
|
||||||
import re
|
MARK XL — Error Handler
|
||||||
import sys
|
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||||
from pathlib import Path
|
"""
|
||||||
from enum import Enum
|
import json
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
def get_base_dir() -> Path:
|
from enum import Enum
|
||||||
if getattr(sys, "frozen", False):
|
from pathlib import Path
|
||||||
return Path(sys.executable).parent
|
|
||||||
return Path(__file__).resolve().parent.parent
|
from core.llm_client import call_llm_text
|
||||||
|
|
||||||
|
|
||||||
BASE_DIR = get_base_dir()
|
def get_base_dir() -> Path:
|
||||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
if getattr(sys, "frozen", False):
|
||||||
|
return Path(sys.executable).parent
|
||||||
|
return Path(__file__).resolve().parent.parent
|
||||||
class ErrorDecision(Enum):
|
|
||||||
RETRY = "retry"
|
|
||||||
SKIP = "skip"
|
BASE_DIR = get_base_dir()
|
||||||
REPLAN = "replan"
|
|
||||||
ABORT = "abort"
|
|
||||||
|
class ErrorDecision(Enum):
|
||||||
|
RETRY = "retry"
|
||||||
ERROR_ANALYST_PROMPT = """You are the error recovery module of MARK XXV AI assistant.
|
SKIP = "skip"
|
||||||
|
REPLAN = "replan"
|
||||||
A task step has failed. Analyze the error and decide what to do.
|
ABORT = "abort"
|
||||||
|
|
||||||
DECISIONS:
|
|
||||||
- retry : Transient error (network timeout, temporary file lock, race condition).
|
ERROR_ANALYST_PROMPT = """You are the error recovery module of MARK XL AI assistant.
|
||||||
The same step can succeed if tried again.
|
|
||||||
- skip : This step is not critical and the task can succeed without it.
|
A task step has failed. Analyze the error and decide what to do.
|
||||||
- replan : The approach was wrong. A different tool or method should be tried.
|
|
||||||
- abort : The task is fundamentally impossible or unsafe to continue.
|
DECISIONS:
|
||||||
|
- retry : Transient error (network timeout, temporary file lock, race condition).
|
||||||
Also provide:
|
- skip : This step is not critical and the task can succeed without it.
|
||||||
- A brief explanation of WHY it failed (1 sentence)
|
- replan : The approach was wrong. A different tool or method should be tried.
|
||||||
- A fix suggestion if decision is replan (what to try instead)
|
- abort : The task is fundamentally impossible or unsafe to continue.
|
||||||
- Max retries: how many times to retry if decision is retry (1 or 2)
|
|
||||||
|
Return ONLY valid JSON:
|
||||||
Return ONLY valid JSON:
|
{
|
||||||
{
|
"decision": "retry|skip|replan|abort",
|
||||||
"decision": "retry|skip|replan|abort",
|
"reason": "why it failed",
|
||||||
"reason": "why it failed",
|
"fix_suggestion": "what to try instead (for replan)",
|
||||||
"fix_suggestion": "what to try instead (for replan)",
|
"max_retries": 1,
|
||||||
"max_retries": 1,
|
"user_message": "Short message to tell the user (max 15 words)"
|
||||||
"user_message": "Short message to tell the user (max 15 words)"
|
}
|
||||||
}
|
"""
|
||||||
"""
|
|
||||||
|
|
||||||
|
def analyze_error(
|
||||||
def _get_api_key() -> str:
|
step: dict,
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
error: str,
|
||||||
return json.load(f)["gemini_api_key"]
|
attempt: int = 1,
|
||||||
|
max_attempts: int = 2,
|
||||||
|
) -> dict:
|
||||||
def analyze_error(
|
if attempt >= max_attempts:
|
||||||
step: dict,
|
print(f"[ErrorHandler] ⚠️ Max attempts for step {step.get('step')} — forcing replan")
|
||||||
error: str,
|
return {
|
||||||
attempt: int = 1,
|
"decision": ErrorDecision.REPLAN,
|
||||||
max_attempts: int = 2
|
"reason": f"Failed {attempt} times: {error[:100]}",
|
||||||
) -> dict:
|
"fix_suggestion": "Try a completely different approach or tool",
|
||||||
"""
|
"max_retries": 0,
|
||||||
Analyzes a failed step and returns a recovery decision.
|
"user_message": "Trying a different approach, sir.",
|
||||||
|
}
|
||||||
Args:
|
|
||||||
step : The step dict that failed
|
prompt = f"""Failed step:
|
||||||
error : Error message/traceback
|
Tool: {step.get('tool')}
|
||||||
attempt : Current attempt number
|
Description: {step.get('description')}
|
||||||
max_attempts : How many times we've already tried
|
Parameters: {json.dumps(step.get('parameters', {}), indent=2)}
|
||||||
|
Critical: {step.get('critical', False)}
|
||||||
Returns:
|
|
||||||
{
|
Error:
|
||||||
"decision": ErrorDecision,
|
{error[:500]}
|
||||||
"reason": str,
|
|
||||||
"fix_suggestion": str,
|
Attempt number: {attempt}"""
|
||||||
"max_retries": int,
|
|
||||||
"user_message": str
|
try:
|
||||||
}
|
text = call_llm_text(prompt, system=ERROR_ANALYST_PROMPT)
|
||||||
"""
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
import google.generativeai as genai
|
result = json.loads(text)
|
||||||
|
|
||||||
if attempt >= max_attempts:
|
decision_str = result.get("decision", "replan").lower()
|
||||||
print(f"[ErrorHandler] ⚠️ Max attempts reached for step {step.get('step')} — forcing replan")
|
decision_map = {
|
||||||
return {
|
"retry": ErrorDecision.RETRY,
|
||||||
"decision": ErrorDecision.REPLAN,
|
"skip": ErrorDecision.SKIP,
|
||||||
"reason": f"Failed {attempt} times: {error[:100]}",
|
"replan": ErrorDecision.REPLAN,
|
||||||
"fix_suggestion": "Try a completely different approach or tool",
|
"abort": ErrorDecision.ABORT,
|
||||||
"max_retries": 0,
|
}
|
||||||
"user_message": "Trying a different approach, sir."
|
result["decision"] = decision_map.get(decision_str, ErrorDecision.REPLAN)
|
||||||
}
|
|
||||||
|
if step.get("critical") and result["decision"] == ErrorDecision.SKIP:
|
||||||
genai.configure(api_key=_get_api_key())
|
result["decision"] = ErrorDecision.REPLAN
|
||||||
model = genai.GenerativeModel(
|
result["user_message"] = "This step is critical — finding alternative approach, sir."
|
||||||
model_name="gemini-2.5-flash-lite",
|
|
||||||
system_instruction=ERROR_ANALYST_PROMPT
|
print(f"[ErrorHandler] Decision: {result['decision'].value} — {result.get('reason', '')}")
|
||||||
)
|
return result
|
||||||
|
|
||||||
prompt = f"""Failed step:
|
except Exception as e:
|
||||||
Tool: {step.get('tool')}
|
print(f"[ErrorHandler] ⚠️ Analysis failed: {e} — defaulting to replan")
|
||||||
Description: {step.get('description')}
|
return {
|
||||||
Parameters: {json.dumps(step.get('parameters', {}), indent=2)}
|
"decision": ErrorDecision.REPLAN,
|
||||||
Critical: {step.get('critical', False)}
|
"reason": str(e),
|
||||||
|
"fix_suggestion": "Try alternative approach",
|
||||||
Error:
|
"max_retries": 1,
|
||||||
{error[:500]}
|
"user_message": "Encountered an issue, adjusting approach, sir.",
|
||||||
|
}
|
||||||
Attempt number: {attempt}"""
|
|
||||||
|
|
||||||
try:
|
def generate_fix(step: dict, error: str, fix_suggestion: str) -> dict:
|
||||||
response = model.generate_content(prompt)
|
prompt = f"""A task step failed. Generate a replacement step.
|
||||||
text = response.text.strip()
|
|
||||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
Original step:
|
||||||
|
Tool: {step.get('tool')}
|
||||||
result = json.loads(text)
|
Description: {step.get('description')}
|
||||||
decision_str = result.get("decision", "replan").lower()
|
Parameters: {json.dumps(step.get('parameters', {}), indent=2)}
|
||||||
decision_map = {
|
|
||||||
"retry": ErrorDecision.RETRY,
|
Error: {error[:300]}
|
||||||
"skip": ErrorDecision.SKIP,
|
Fix suggestion: {fix_suggestion}
|
||||||
"replan": ErrorDecision.REPLAN,
|
|
||||||
"abort": ErrorDecision.ABORT,
|
Write a Python script that accomplishes the same goal differently.
|
||||||
}
|
Return ONLY the Python code, no explanation."""
|
||||||
result["decision"] = decision_map.get(decision_str, ErrorDecision.REPLAN)
|
|
||||||
|
try:
|
||||||
|
code = call_llm_text(prompt)
|
||||||
if step.get("critical") and result["decision"] == ErrorDecision.SKIP:
|
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||||
result["decision"] = ErrorDecision.REPLAN
|
return {
|
||||||
result["user_message"] = "This step is critical — finding alternative approach, sir."
|
"step": step.get("step"),
|
||||||
|
"tool": "code_helper",
|
||||||
print(f"[ErrorHandler] Decision: {result['decision'].value} — {result.get('reason', '')}")
|
"description": f"Auto-fix for: {step.get('description')}",
|
||||||
return result
|
"parameters": {
|
||||||
|
"action": "run",
|
||||||
except Exception as e:
|
"description": fix_suggestion,
|
||||||
print(f"[ErrorHandler] ⚠️ Analysis failed: {e} — defaulting to replan")
|
"code": code,
|
||||||
return {
|
"language": "python",
|
||||||
"decision": ErrorDecision.REPLAN,
|
},
|
||||||
"reason": str(e),
|
"depends_on": step.get("depends_on", []),
|
||||||
"fix_suggestion": "Try alternative approach",
|
"critical": step.get("critical", False),
|
||||||
"max_retries": 1,
|
}
|
||||||
"user_message": "Encountered an issue, adjusting approach, sir."
|
except Exception as e:
|
||||||
}
|
print(f"[ErrorHandler] ⚠️ Fix generation failed: {e}")
|
||||||
|
return {
|
||||||
|
"step": step.get("step"),
|
||||||
def generate_fix(step: dict, error: str, fix_suggestion: str) -> dict:
|
"tool": "generated_code",
|
||||||
"""
|
"description": f"Fallback for: {step.get('description')}",
|
||||||
When decision is REPLAN and a fix suggestion exists,
|
"parameters": {"description": step.get("description", "")},
|
||||||
generates a replacement step using generated_code as fallback.
|
"depends_on": step.get("depends_on", []),
|
||||||
|
"critical": step.get("critical", False),
|
||||||
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)
|
|
||||||
}
|
|
||||||
+394
-396
@@ -1,396 +1,394 @@
|
|||||||
import json
|
"""
|
||||||
import re
|
MARK XL — Agent Executor
|
||||||
import sys
|
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||||
import threading
|
"""
|
||||||
import subprocess
|
import json
|
||||||
import tempfile
|
import re
|
||||||
import os
|
import sys
|
||||||
from pathlib import Path
|
import threading
|
||||||
from typing import Callable
|
import subprocess
|
||||||
|
import tempfile
|
||||||
from agent.planner import create_plan, replan
|
import os
|
||||||
from agent.error_handler import analyze_error, generate_fix, ErrorDecision
|
from pathlib import Path
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
def get_base_dir() -> Path:
|
from agent.planner import create_plan, replan
|
||||||
if getattr(sys, "frozen", False):
|
from agent.error_handler import analyze_error, generate_fix, ErrorDecision
|
||||||
return Path(sys.executable).parent
|
from core.llm_client import call_llm_text
|
||||||
return Path(__file__).resolve().parent.parent
|
|
||||||
|
|
||||||
|
def get_base_dir() -> Path:
|
||||||
BASE_DIR = get_base_dir()
|
if getattr(sys, "frozen", False):
|
||||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
return Path(sys.executable).parent
|
||||||
|
return Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
BASE_DIR = get_base_dir()
|
||||||
return json.load(f)["gemini_api_key"]
|
|
||||||
|
|
||||||
def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
# ---------------------------------------------------------------------------
|
||||||
import google.generativeai as genai
|
# Code generation helper (replaces _run_generated_code with Gemini)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
if speak:
|
|
||||||
speak("Writing custom code for this task, sir.")
|
def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
||||||
|
if speak:
|
||||||
home = Path.home()
|
speak("Writing custom code for this task, sir.")
|
||||||
desktop = home / "Desktop"
|
|
||||||
downloads = home / "Downloads"
|
home = Path.home()
|
||||||
documents = home / "Documents"
|
desktop = home / "Desktop"
|
||||||
|
downloads = home / "Downloads"
|
||||||
if not desktop.exists():
|
documents = home / "Documents"
|
||||||
try:
|
|
||||||
import winreg
|
if not desktop.exists():
|
||||||
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
|
try:
|
||||||
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
|
import winreg
|
||||||
desktop = Path(winreg.QueryValueEx(key, "Desktop")[0])
|
key = winreg.OpenKey(
|
||||||
except Exception:
|
winreg.HKEY_CURRENT_USER,
|
||||||
pass
|
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders",
|
||||||
|
)
|
||||||
genai.configure(api_key=_get_api_key())
|
desktop = Path(winreg.QueryValueEx(key, "Desktop")[0])
|
||||||
model = genai.GenerativeModel(
|
except Exception:
|
||||||
model_name="gemini-2.5-flash",
|
pass
|
||||||
system_instruction=(
|
|
||||||
"You are an expert Python developer. "
|
system = (
|
||||||
"Write clean, complete, working Python code. "
|
"You are an expert Python developer. "
|
||||||
"Use standard library + common packages. "
|
"Write clean, complete, working Python code. "
|
||||||
"Install missing packages with subprocess + pip if needed. "
|
"Use standard library + common packages. "
|
||||||
"Return ONLY the Python code. No explanation, no markdown, no backticks.\n\n"
|
"Install missing packages with subprocess + pip if needed. "
|
||||||
f"SYSTEM PATHS:\n"
|
"Return ONLY the Python code. No explanation, no markdown, no backticks.\n\n"
|
||||||
f" Desktop = r'{desktop}'\n"
|
f"SYSTEM PATHS:\n"
|
||||||
f" Downloads = r'{downloads}'\n"
|
f" Desktop = r'{desktop}'\n"
|
||||||
f" Documents = r'{documents}'\n"
|
f" Downloads = r'{downloads}'\n"
|
||||||
f" Home = r'{home}'\n"
|
f" Documents = r'{documents}'\n"
|
||||||
)
|
f" Home = r'{home}'\n"
|
||||||
)
|
)
|
||||||
|
prompt = f"Write Python code to accomplish this task:\n\n{description}"
|
||||||
try:
|
|
||||||
response = model.generate_content(
|
try:
|
||||||
f"Write Python code to accomplish this task:\n\n{description}"
|
code = call_llm_text(prompt, system=system)
|
||||||
)
|
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||||
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"
|
||||||
with tempfile.NamedTemporaryFile(
|
) as f:
|
||||||
mode="w", suffix=".py", delete=False, encoding="utf-8"
|
f.write(code)
|
||||||
) as f:
|
tmp_path = f.name
|
||||||
f.write(code)
|
|
||||||
tmp_path = f.name
|
print(f"[Executor] 🐍 Running generated code: {tmp_path}")
|
||||||
|
|
||||||
print(f"[Executor] 🐍 Running generated code: {tmp_path}")
|
result = subprocess.run(
|
||||||
|
[sys.executable, tmp_path],
|
||||||
result = subprocess.run(
|
capture_output=True, text=True,
|
||||||
[sys.executable, tmp_path],
|
timeout=120, cwd=str(Path.home()),
|
||||||
capture_output=True, text=True,
|
)
|
||||||
timeout=120, cwd=str(Path.home())
|
|
||||||
)
|
try:
|
||||||
|
os.unlink(tmp_path)
|
||||||
try:
|
except Exception:
|
||||||
os.unlink(tmp_path)
|
pass
|
||||||
except Exception:
|
|
||||||
pass
|
output = result.stdout.strip()
|
||||||
|
error = result.stderr.strip()
|
||||||
output = result.stdout.strip()
|
|
||||||
error = result.stderr.strip()
|
if result.returncode == 0 and output:
|
||||||
|
return output
|
||||||
if result.returncode == 0 and output:
|
elif result.returncode == 0:
|
||||||
return output
|
return "Task completed successfully."
|
||||||
elif result.returncode == 0:
|
elif error:
|
||||||
return "Task completed successfully."
|
raise RuntimeError(f"Code error: {error[:400]}")
|
||||||
elif error:
|
return "Completed."
|
||||||
raise RuntimeError(f"Code error: {error[:400]}")
|
|
||||||
return "Completed."
|
except subprocess.TimeoutExpired:
|
||||||
|
raise RuntimeError("Generated code timed out after 120 seconds.")
|
||||||
except subprocess.TimeoutExpired:
|
except RuntimeError:
|
||||||
raise RuntimeError("Generated code timed out after 120 seconds.")
|
raise
|
||||||
except RuntimeError:
|
except Exception as e:
|
||||||
raise
|
raise RuntimeError(f"Generated code failed: {e}")
|
||||||
except Exception as e:
|
|
||||||
raise RuntimeError(f"Generated code failed: {e}")
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
def _inject_context(params: dict, tool: str, step_results: dict, goal: str = "") -> dict:
|
# Context injection
|
||||||
if not step_results:
|
# ---------------------------------------------------------------------------
|
||||||
return params
|
|
||||||
|
def _detect_language(text: str) -> str:
|
||||||
params = dict(params)
|
try:
|
||||||
|
return call_llm_text(
|
||||||
if tool == "file_controller" and params.get("action") in ("write", "create_file"):
|
f"What language is this text written in? "
|
||||||
content = params.get("content", "")
|
f"Reply with ONLY the language name in English (e.g. Turkish, English, French).\n\n"
|
||||||
if not content or len(content) < 50:
|
f"Text: {text[:200]}"
|
||||||
all_results = [
|
).strip()
|
||||||
v for v in step_results.values()
|
except Exception:
|
||||||
if v and len(v) > 100 and v not in ("Done.", "Completed.")
|
return "English"
|
||||||
]
|
|
||||||
if all_results:
|
|
||||||
combined = "\n\n---\n\n".join(all_results)
|
def _translate_to_goal_language(content: str, goal: str) -> str:
|
||||||
translated = _translate_to_goal_language(combined, goal)
|
if not goal:
|
||||||
params["content"] = translated
|
return content
|
||||||
print(f"[Executor] 💉 Injected + translated content")
|
try:
|
||||||
|
target_lang = _detect_language(goal)
|
||||||
return params
|
print(f"[Executor] 🌐 Translating to: {target_lang}")
|
||||||
def _detect_language(text: str) -> str:
|
prompt = (
|
||||||
import google.generativeai as genai
|
f"You are a professional translator. "
|
||||||
genai.configure(api_key=_get_api_key())
|
f"Translate the following text into {target_lang}.\n"
|
||||||
model = genai.GenerativeModel("gemini-2.5-flash-lite")
|
f"IMPORTANT:\n"
|
||||||
try:
|
f"- Translate EVERYTHING, leave nothing in English\n"
|
||||||
response = model.generate_content(
|
f"- Keep all facts, numbers, and data intact\n"
|
||||||
f"What language is this text written in? "
|
f"- Keep the structure and formatting\n"
|
||||||
f"Reply with ONLY the language name in English (e.g. Turkish, English, French).\n\n"
|
f"- Output ONLY the translated text, nothing else\n\n"
|
||||||
f"Text: {text[:200]}"
|
f"Text to translate:\n{content[:4000]}"
|
||||||
)
|
)
|
||||||
return response.text.strip()
|
translated = call_llm_text(prompt)
|
||||||
except Exception:
|
print(f"[Executor] ✅ Translation done ({target_lang})")
|
||||||
return "English"
|
return translated
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[Executor] ⚠️ Translation failed: {e}")
|
||||||
def _translate_to_goal_language(content: str, goal: str) -> str:
|
return content
|
||||||
if not goal:
|
|
||||||
return content
|
|
||||||
try:
|
def _inject_context(params: dict, tool: str, step_results: dict, goal: str = "") -> dict:
|
||||||
import google.generativeai as genai
|
if not step_results:
|
||||||
genai.configure(api_key=_get_api_key())
|
return params
|
||||||
model = genai.GenerativeModel("gemini-2.5-flash")
|
params = dict(params)
|
||||||
|
if tool == "file_controller" and params.get("action") in ("write", "create_file"):
|
||||||
target_lang = _detect_language(goal)
|
content = params.get("content", "")
|
||||||
print(f"[Executor] 🌐 Translating to: {target_lang}")
|
if not content or len(content) < 50:
|
||||||
|
all_results = [
|
||||||
prompt = (
|
v for v in step_results.values()
|
||||||
f"You are a professional translator. "
|
if v and len(v) > 100 and v not in ("Done.", "Completed.")
|
||||||
f"Translate the following text into {target_lang}.\n"
|
]
|
||||||
f"IMPORTANT:\n"
|
if all_results:
|
||||||
f"- Translate EVERYTHING, leave nothing in English\n"
|
combined = "\n\n---\n\n".join(all_results)
|
||||||
f"- Keep all facts, numbers, and data intact\n"
|
translated = _translate_to_goal_language(combined, goal)
|
||||||
f"- Keep the structure and formatting\n"
|
params["content"] = translated
|
||||||
f"- Output ONLY the translated text, nothing else\n\n"
|
print("[Executor] 💉 Injected + translated content")
|
||||||
f"Text to translate:\n{content[:4000]}"
|
return params
|
||||||
)
|
|
||||||
response = model.generate_content(prompt)
|
|
||||||
translated = response.text.strip()
|
# ---------------------------------------------------------------------------
|
||||||
print(f"[Executor] ✅ Translation done ({target_lang})")
|
# Tool routing
|
||||||
return translated
|
# ---------------------------------------------------------------------------
|
||||||
except Exception as e:
|
|
||||||
print(f"[Executor] ⚠️ Translation failed: {e}")
|
def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
||||||
return content
|
if tool == "open_app":
|
||||||
|
from actions.open_app import open_app
|
||||||
def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
return open_app(parameters=parameters, player=None) or "Done."
|
||||||
|
|
||||||
if tool == "open_app":
|
elif tool == "web_search":
|
||||||
from actions.open_app import open_app
|
from actions.web_search import web_search
|
||||||
return open_app(parameters=parameters, player=None) or "Done."
|
return web_search(parameters=parameters, player=None) or "Done."
|
||||||
|
|
||||||
elif tool == "web_search":
|
elif tool == "game_updater":
|
||||||
from actions.web_search import web_search
|
from actions.game_updater import game_updater
|
||||||
return web_search(parameters=parameters, player=None) or "Done."
|
return game_updater(parameters=parameters, player=None, speak=speak) or "Done."
|
||||||
elif tool == "game_updater":
|
|
||||||
from actions.game_updater import game_updater
|
elif tool == "browser_control":
|
||||||
return game_updater(parameters=parameters, player=None, speak=speak) or "Done."
|
from actions.browser_control import browser_control
|
||||||
elif tool == "browser_control":
|
return browser_control(parameters=parameters, player=None) or "Done."
|
||||||
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
|
||||||
elif tool == "file_controller":
|
return file_controller(parameters=parameters, player=None) or "Done."
|
||||||
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
|
||||||
elif tool == "code_helper":
|
return code_helper(parameters=parameters, player=None, speak=speak) or "Done."
|
||||||
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
|
||||||
elif tool == "dev_agent":
|
return dev_agent(parameters=parameters, player=None, speak=speak) or "Done."
|
||||||
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
|
||||||
elif tool == "screen_process":
|
result = screen_process(parameters=parameters, player=None)
|
||||||
from actions.screen_processor import screen_process
|
return result if isinstance(result, str) else "Screen captured and analyzed."
|
||||||
screen_process(parameters=parameters, player=None)
|
|
||||||
return "Screen captured and analyzed."
|
elif tool == "send_message":
|
||||||
|
from actions.send_message import send_message
|
||||||
elif tool == "send_message":
|
return send_message(parameters=parameters, player=None) or "Done."
|
||||||
from actions.send_message import send_message
|
|
||||||
return send_message(parameters=parameters, player=None) or "Done."
|
elif tool == "reminder":
|
||||||
|
from actions.reminder import reminder
|
||||||
elif tool == "reminder":
|
return reminder(parameters=parameters, player=None) or "Done."
|
||||||
from actions.reminder import reminder
|
|
||||||
return reminder(parameters=parameters, player=None) or "Done."
|
elif tool == "youtube_video":
|
||||||
|
from actions.youtube_video import youtube_video
|
||||||
elif tool == "youtube_video":
|
return youtube_video(parameters=parameters, player=None) or "Done."
|
||||||
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
|
||||||
elif tool == "weather_report":
|
return weather_action(parameters=parameters, player=None) or "Done."
|
||||||
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
|
||||||
elif tool == "computer_settings":
|
return computer_settings(parameters=parameters, player=None) or "Done."
|
||||||
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
|
||||||
elif tool == "desktop_control":
|
return desktop_control(parameters=parameters, player=None) or "Done."
|
||||||
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
|
||||||
elif tool == "computer_control":
|
return computer_control(parameters=parameters, player=None) or "Done."
|
||||||
from actions.computer_control import computer_control
|
|
||||||
return computer_control(parameters=parameters, player=None) or "Done."
|
elif tool == "generated_code":
|
||||||
|
description = parameters.get("description", "")
|
||||||
elif tool == "generated_code":
|
if not description:
|
||||||
description = parameters.get("description", "")
|
raise ValueError("generated_code requires a 'description' parameter.")
|
||||||
if not description:
|
return _run_generated_code(description, speak=speak)
|
||||||
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
|
||||||
elif tool == "flight_finder":
|
return flight_finder(parameters=parameters, player=None, speak=speak) or "Done."
|
||||||
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")
|
||||||
else:
|
return _run_generated_code(f"Accomplish this task: {parameters}", speak=speak)
|
||||||
print(f"[Executor] ⚠️ Unknown tool '{tool}' — falling back to generated_code")
|
|
||||||
return _run_generated_code(f"Accomplish this task: {parameters}", speak=speak)
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
class AgentExecutor:
|
# AgentExecutor
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
MAX_REPLAN_ATTEMPTS = 2
|
|
||||||
|
class AgentExecutor:
|
||||||
def execute(
|
|
||||||
self,
|
MAX_REPLAN_ATTEMPTS = 2
|
||||||
goal: str,
|
|
||||||
speak: Callable | None = None,
|
def execute(
|
||||||
cancel_flag: threading.Event | None = None,
|
self,
|
||||||
) -> str:
|
goal: str,
|
||||||
print(f"\n[Executor] 🎯 Goal: {goal}")
|
speak: Callable | None = None,
|
||||||
|
cancel_flag: threading.Event | None = None,
|
||||||
replan_attempts = 0
|
) -> str:
|
||||||
completed_steps = []
|
print(f"\n[Executor] 🎯 Goal: {goal}")
|
||||||
step_results = {}
|
|
||||||
plan = create_plan(goal)
|
replan_attempts = 0
|
||||||
|
completed_steps: list = []
|
||||||
while True:
|
step_results: dict = {}
|
||||||
steps = plan.get("steps", [])
|
plan = create_plan(goal)
|
||||||
|
|
||||||
if not steps:
|
while True:
|
||||||
msg = "I couldn't create a valid plan for this task, sir."
|
steps = plan.get("steps", [])
|
||||||
if speak: speak(msg)
|
if not steps:
|
||||||
return msg
|
msg = "I couldn't create a valid plan for this task, sir."
|
||||||
|
if speak: speak(msg)
|
||||||
success = True
|
return msg
|
||||||
failed_step = None
|
|
||||||
failed_error = ""
|
success = True
|
||||||
|
failed_step = None
|
||||||
for step in steps:
|
failed_error = ""
|
||||||
if cancel_flag and cancel_flag.is_set():
|
|
||||||
if speak: speak("Task cancelled, sir.")
|
for step in steps:
|
||||||
return "Task cancelled."
|
if cancel_flag and cancel_flag.is_set():
|
||||||
|
if speak: speak("Task cancelled, sir.")
|
||||||
step_num = step.get("step", "?")
|
return "Task cancelled."
|
||||||
tool = step.get("tool", "generated_code")
|
|
||||||
desc = step.get("description", "")
|
step_num = step.get("step", "?")
|
||||||
params = step.get("parameters", {})
|
tool = step.get("tool", "generated_code")
|
||||||
|
desc = step.get("description", "")
|
||||||
params = _inject_context(params, tool, step_results, goal=goal)
|
params = step.get("parameters", {})
|
||||||
|
params = _inject_context(params, tool, step_results, goal=goal)
|
||||||
print(f"\n[Executor] ▶️ Step {step_num}: [{tool}] {desc}")
|
|
||||||
|
print(f"\n[Executor] ▶️ Step {step_num}: [{tool}] {desc}")
|
||||||
attempt = 1
|
|
||||||
step_ok = False
|
attempt = 1
|
||||||
|
step_ok = False
|
||||||
while attempt <= 3:
|
|
||||||
if cancel_flag and cancel_flag.is_set():
|
while attempt <= 3:
|
||||||
break
|
if cancel_flag and cancel_flag.is_set():
|
||||||
try:
|
break
|
||||||
result = _call_tool(tool, params, speak)
|
try:
|
||||||
step_results[step_num] = result
|
result = _call_tool(tool, params, speak)
|
||||||
completed_steps.append(step)
|
step_results[step_num] = result
|
||||||
print(f"[Executor] ✅ Step {step_num} done: {str(result)[:100]}")
|
completed_steps.append(step)
|
||||||
step_ok = True
|
print(f"[Executor] ✅ Step {step_num} done: {str(result)[:100]}")
|
||||||
break
|
step_ok = True
|
||||||
|
break
|
||||||
except Exception as e:
|
|
||||||
error_msg = str(e)
|
except Exception as e:
|
||||||
print(f"[Executor] ❌ Step {step_num} attempt {attempt} failed: {error_msg}")
|
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"]
|
recovery = analyze_error(step, error_msg, attempt=attempt)
|
||||||
user_msg = recovery.get("user_message", "")
|
decision = recovery["decision"]
|
||||||
|
user_msg = recovery.get("user_message", "")
|
||||||
if speak and user_msg:
|
|
||||||
speak(user_msg)
|
if speak and user_msg:
|
||||||
|
speak(user_msg)
|
||||||
if decision == ErrorDecision.RETRY:
|
|
||||||
attempt += 1
|
if decision == ErrorDecision.RETRY:
|
||||||
import time; time.sleep(2)
|
attempt += 1
|
||||||
continue
|
import time; time.sleep(2)
|
||||||
|
continue
|
||||||
elif decision == ErrorDecision.SKIP:
|
|
||||||
print(f"[Executor] ⏭️ Skipping step {step_num}")
|
elif decision == ErrorDecision.SKIP:
|
||||||
completed_steps.append(step)
|
print(f"[Executor] ⏭️ Skipping step {step_num}")
|
||||||
step_ok = True
|
completed_steps.append(step)
|
||||||
break
|
step_ok = True
|
||||||
|
break
|
||||||
elif decision == ErrorDecision.ABORT:
|
|
||||||
msg = f"Task aborted, sir. {recovery.get('reason', '')}"
|
elif decision == ErrorDecision.ABORT:
|
||||||
if speak: speak(msg)
|
msg = f"Task aborted, sir. {recovery.get('reason', '')}"
|
||||||
return msg
|
if speak: speak(msg)
|
||||||
|
return msg
|
||||||
else:
|
|
||||||
fix_suggestion = recovery.get("fix_suggestion", "")
|
else: # REPLAN
|
||||||
if fix_suggestion and tool != "generated_code":
|
fix_suggestion = recovery.get("fix_suggestion", "")
|
||||||
try:
|
if fix_suggestion and tool != "generated_code":
|
||||||
fixed_step = generate_fix(step, error_msg, fix_suggestion)
|
try:
|
||||||
if speak: speak("Trying an alternative approach, sir.")
|
fixed_step = generate_fix(step, error_msg, fix_suggestion)
|
||||||
res = _call_tool(
|
if speak: speak("Trying an alternative approach, sir.")
|
||||||
fixed_step["tool"],
|
res = _call_tool(
|
||||||
fixed_step["parameters"],
|
fixed_step["tool"],
|
||||||
speak
|
fixed_step["parameters"],
|
||||||
)
|
speak,
|
||||||
step_results[step_num] = res
|
)
|
||||||
completed_steps.append(step)
|
step_results[step_num] = res
|
||||||
step_ok = True
|
completed_steps.append(step)
|
||||||
break
|
step_ok = True
|
||||||
except Exception as fix_err:
|
break
|
||||||
print(f"[Executor] ⚠️ Fix failed: {fix_err}")
|
except Exception as fix_err:
|
||||||
|
print(f"[Executor] ⚠️ Fix failed: {fix_err}")
|
||||||
failed_step = step
|
|
||||||
failed_error = error_msg
|
failed_step = step
|
||||||
success = False
|
failed_error = error_msg
|
||||||
break
|
success = False
|
||||||
|
break
|
||||||
if not step_ok and not failed_step:
|
|
||||||
failed_step = step
|
if not step_ok and not failed_step:
|
||||||
failed_error = "Max retries exceeded"
|
failed_step = step
|
||||||
success = False
|
failed_error = "Max retries exceeded"
|
||||||
|
success = False
|
||||||
if not success:
|
|
||||||
break
|
if not success:
|
||||||
|
break
|
||||||
if success:
|
|
||||||
return self._summarize(goal, completed_steps, speak)
|
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 replan_attempts >= self.MAX_REPLAN_ATTEMPTS:
|
||||||
if speak: speak(msg)
|
msg = f"Task failed after {replan_attempts} replan attempts, sir."
|
||||||
return msg
|
if speak: speak(msg)
|
||||||
|
return msg
|
||||||
if speak: speak("Adjusting my approach, sir.")
|
|
||||||
|
if speak: speak("Adjusting my approach, sir.")
|
||||||
replan_attempts += 1
|
replan_attempts += 1
|
||||||
plan = replan(goal, completed_steps, failed_step, failed_error)
|
plan = replan(goal, completed_steps, failed_step, failed_error)
|
||||||
|
|
||||||
def _summarize(self, goal: str, completed_steps: list, speak: Callable | None) -> str:
|
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]}."
|
fallback = f"All done, sir. Completed {len(completed_steps)} steps for: {goal[:60]}."
|
||||||
try:
|
steps_str = "\n".join(f"- {s.get('description', '')}" for s in completed_steps)
|
||||||
import google.generativeai as genai
|
prompt = (
|
||||||
genai.configure(api_key=_get_api_key())
|
f'User goal: "{goal}"\n'
|
||||||
model = genai.GenerativeModel(model_name="gemini-2.5-flash-lite")
|
f"Completed steps:\n{steps_str}\n\n"
|
||||||
steps_str = "\n".join(f"- {s.get('description', '')}" for s in completed_steps)
|
"Write a single natural sentence summarising what was accomplished. "
|
||||||
prompt = (
|
"Address the user as 'sir'. Be direct and positive."
|
||||||
f'User goal: "{goal}"\n'
|
)
|
||||||
f"Completed steps:\n{steps_str}\n\n"
|
try:
|
||||||
"Write a single natural sentence summarizing what was accomplished. "
|
summary = call_llm_text(prompt)
|
||||||
"Address the user as 'sir'. Be direct and positive."
|
if summary:
|
||||||
)
|
if speak: speak(summary)
|
||||||
response = model.generate_content(prompt)
|
return summary
|
||||||
summary = response.text.strip()
|
except Exception:
|
||||||
if speak: speak(summary)
|
pass
|
||||||
return summary
|
if speak: speak(fallback)
|
||||||
except Exception:
|
return fallback
|
||||||
if speak: speak(fallback)
|
|
||||||
return fallback
|
|
||||||
+211
-272
@@ -1,272 +1,211 @@
|
|||||||
import json
|
"""
|
||||||
import re
|
MARK XL — Task Planner
|
||||||
import sys
|
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||||
from pathlib import Path
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
def get_base_dir() -> Path:
|
import sys
|
||||||
if getattr(sys, "frozen", False):
|
from pathlib import Path
|
||||||
return Path(sys.executable).parent
|
|
||||||
return Path(__file__).resolve().parent.parent
|
from core.llm_client import call_llm_text
|
||||||
|
|
||||||
|
|
||||||
BASE_DIR = get_base_dir()
|
def get_base_dir() -> Path:
|
||||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
if getattr(sys, "frozen", False):
|
||||||
|
return Path(sys.executable).parent
|
||||||
|
return Path(__file__).resolve().parent.parent
|
||||||
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.
|
|
||||||
|
BASE_DIR = get_base_dir()
|
||||||
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.
|
PLANNER_PROMPT = """You are the planning module of MARK XL, a personal AI assistant.
|
||||||
- Use web_search for ANY information retrieval, research, or current data.
|
Your job: break any user goal into a sequence of steps using ONLY the tools listed below.
|
||||||
- Use file_controller to save content to disk.
|
|
||||||
- Max 5 steps. Use the minimum steps needed.
|
ABSOLUTE RULES:
|
||||||
|
- NEVER use generated_code or write Python scripts. It does not exist.
|
||||||
AVAILABLE TOOLS AND THEIR PARAMETERS:
|
- NEVER reference previous step results in parameters. Every step is independent.
|
||||||
|
- Use web_search for ANY information retrieval, research, or current data.
|
||||||
open_app
|
- Use file_controller to save content to disk.
|
||||||
app_name: string (required)
|
- Max 5 steps. Use the minimum steps needed.
|
||||||
|
|
||||||
web_search
|
AVAILABLE TOOLS AND THEIR PARAMETERS:
|
||||||
query: string (required) — write a clear, focused search query
|
|
||||||
mode: "search" or "compare" (optional, default: search)
|
open_app
|
||||||
items: list of strings (optional, for compare mode)
|
app_name: string (required)
|
||||||
aspect: string (optional, for compare mode)
|
|
||||||
|
web_search
|
||||||
game_updater
|
query: string (required) — write a clear, focused search query
|
||||||
action: "update" | "install" | "list" | "download_status" | "schedule" (required)
|
mode: "search" or "compare" (optional, default: search)
|
||||||
platform: "steam" | "epic" | "both" (optional, default: both)
|
items: list of strings (optional, for compare mode)
|
||||||
game_name: string (optional)
|
aspect: string (optional, for compare mode)
|
||||||
app_id: string (optional)
|
|
||||||
shutdown_when_done: boolean (optional)
|
game_updater
|
||||||
|
action: "update" | "install" | "list" | "download_status" | "schedule" (required)
|
||||||
browser_control
|
platform: "steam" | "epic" | "both" (optional, default: both)
|
||||||
action: "go_to" | "search" | "click" | "type" | "scroll" | "get_text" | "press" | "close" (required)
|
game_name: string (optional)
|
||||||
url: string (for go_to)
|
app_id: string (optional)
|
||||||
query: string (for search)
|
shutdown_when_done: boolean (optional)
|
||||||
text: string (for click/type)
|
|
||||||
direction: "up" | "down" (for scroll)
|
browser_control
|
||||||
|
action: "go_to" | "search" | "click" | "type" | "scroll" | "get_text" | "press" | "close" (required)
|
||||||
file_controller
|
url: string (for go_to)
|
||||||
action: "write" | "create_file" | "read" | "list" | "delete" | "move" | "copy" | "find" | "disk_usage" (required)
|
query: string (for search)
|
||||||
path: string — use "desktop" for Desktop folder
|
text: string (for click/type)
|
||||||
name: string — filename
|
direction: "up" | "down" (for scroll)
|
||||||
content: string — file content (for write/create_file)
|
|
||||||
|
file_controller
|
||||||
computer_settings
|
action: "write" | "create_file" | "read" | "list" | "delete" | "move" | "copy" | "find" | "disk_usage" (required)
|
||||||
action: string (required)
|
path: string — use "desktop" for Desktop folder
|
||||||
description: string — natural language description
|
name: string — filename
|
||||||
value: string (optional)
|
content: string — file content (for write/create_file)
|
||||||
|
|
||||||
computer_control
|
computer_settings
|
||||||
action: "type" | "click" | "hotkey" | "press" | "scroll" | "screenshot" | "screen_find" | "screen_click" (required)
|
action: string (required)
|
||||||
text: string (for type)
|
description: string — natural language description
|
||||||
x, y: int (for click)
|
value: string (optional)
|
||||||
keys: string (for hotkey, e.g. "ctrl+c")
|
|
||||||
key: string (for press)
|
computer_control
|
||||||
direction: "up" | "down" (for scroll)
|
action: "type" | "click" | "hotkey" | "press" | "scroll" | "screenshot" | "screen_find" | "screen_click" (required)
|
||||||
description: string (for screen_find/screen_click)
|
text: string (for type)
|
||||||
|
x, y: int (for click)
|
||||||
screen_process
|
keys: string (for hotkey, e.g. "ctrl+c")
|
||||||
text: string (required) — what to analyze or ask about the screen
|
key: string (for press)
|
||||||
angle: "screen" | "camera" (optional)
|
direction: "up" | "down" (for scroll)
|
||||||
|
description: string (for screen_find/screen_click)
|
||||||
send_message
|
|
||||||
receiver: string (required)
|
screen_process
|
||||||
message_text: string (required)
|
text: string (required) — what to analyze or ask about the screen
|
||||||
platform: string (required)
|
angle: "screen" | "camera" (optional)
|
||||||
|
|
||||||
reminder
|
send_message
|
||||||
date: string YYYY-MM-DD (required)
|
receiver: string (required)
|
||||||
time: string HH:MM (required)
|
message_text: string (required)
|
||||||
message: string (required)
|
platform: string (required)
|
||||||
|
|
||||||
desktop_control
|
reminder
|
||||||
action: "wallpaper" | "organize" | "clean" | "list" | "task" (required)
|
date: string YYYY-MM-DD (required)
|
||||||
path: string (optional)
|
time: string HH:MM (required)
|
||||||
task: string (optional)
|
message: string (required)
|
||||||
|
|
||||||
youtube_video
|
desktop_control
|
||||||
action: "play" | "summarize" | "trending" (required)
|
action: "wallpaper" | "organize" | "clean" | "list" | "task" (required)
|
||||||
query: string (for play)
|
path: string (optional)
|
||||||
|
task: string (optional)
|
||||||
weather_report
|
|
||||||
city: string (required)
|
youtube_video
|
||||||
|
action: "play" | "summarize" | "trending" (required)
|
||||||
flight_finder
|
query: string (for play)
|
||||||
origin: string (required)
|
|
||||||
destination: string (required)
|
weather_report
|
||||||
date: string (required)
|
city: string (required)
|
||||||
|
|
||||||
code_helper
|
flight_finder
|
||||||
action: "write" | "edit" | "run" | "explain" (required)
|
origin: string (required)
|
||||||
description: string (required)
|
destination: string (required)
|
||||||
language: string (optional)
|
date: string (required)
|
||||||
output_path: string (optional)
|
|
||||||
file_path: string (optional)
|
code_helper
|
||||||
|
action: "write" | "edit" | "run" | "explain" (required)
|
||||||
dev_agent
|
description: string (required)
|
||||||
description: string (required)
|
language: string (optional)
|
||||||
language: string (optional)
|
output_path: string (optional)
|
||||||
EXAMPLES:
|
file_path: string (optional)
|
||||||
|
|
||||||
Goal: "research mechanical engineering and save it to a notepad file"
|
dev_agent
|
||||||
Steps:
|
description: string (required)
|
||||||
|
language: string (optional)
|
||||||
web_search | query: "mechanical engineering overview definition history"
|
|
||||||
web_search | query: "mechanical engineering applications and future trends"
|
OUTPUT — return ONLY valid JSON, no markdown, no explanation, no code blocks:
|
||||||
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": "...",
|
||||||
Goal: "What is the price of Bitcoin"
|
"steps": [
|
||||||
Steps:
|
{
|
||||||
|
"step": 1,
|
||||||
web_search | query: "Bitcoin price today USD"
|
"tool": "tool_name",
|
||||||
|
"description": "what this step does",
|
||||||
Goal: "List the files on the desktop and find the largest 5 files"
|
"parameters": {},
|
||||||
Steps:
|
"critical": true
|
||||||
|
}
|
||||||
file_controller | action: list, path: desktop
|
]
|
||||||
file_controller | action: largest, path: desktop, count: 5
|
}
|
||||||
|
"""
|
||||||
Goal: "Install PUBG from Steam"
|
|
||||||
Steps:
|
|
||||||
|
def create_plan(goal: str, context: str = "") -> dict:
|
||||||
game_updater | action: install, platform: steam, game_name: "PUBG"
|
user_input = f"Goal: {goal}"
|
||||||
|
if context:
|
||||||
Goal: "Update all my Steam games"
|
user_input += f"\n\nContext: {context}"
|
||||||
Steps:
|
|
||||||
|
try:
|
||||||
game_updater | action: update, platform: steam
|
text = call_llm_text(user_input, system=PLANNER_PROMPT)
|
||||||
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
Goal: "Send John a message on WhatsApp saying there is a meeting tomorrow"
|
|
||||||
Steps:
|
plan = json.loads(text)
|
||||||
|
if "steps" not in plan or not isinstance(plan["steps"], list):
|
||||||
send_message | receiver: John, message_text: "There is a meeting tomorrow", platform: WhatsApp
|
raise ValueError("Invalid plan structure")
|
||||||
|
|
||||||
Goal: "Open the clock and set a reminder for 30 minutes later"
|
for step in plan["steps"]:
|
||||||
Steps:
|
if step.get("tool") == "generated_code":
|
||||||
|
print(f"[Planner] ⚠️ generated_code in step {step.get('step')} — replacing with web_search")
|
||||||
reminder | date: [today], time: [now+30min], message: "Reminder"
|
step["tool"] = "web_search"
|
||||||
|
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
||||||
OUTPUT — return ONLY valid JSON, no markdown, no explanation, no code blocks:
|
|
||||||
{
|
print(f"[Planner] ✅ Plan: {len(plan['steps'])} steps")
|
||||||
"goal": "...",
|
for s in plan["steps"]:
|
||||||
"steps": [
|
print(f" Step {s['step']}: [{s['tool']}] {s['description']}")
|
||||||
{
|
return plan
|
||||||
"step": 1,
|
|
||||||
"tool": "tool_name",
|
except json.JSONDecodeError as e:
|
||||||
"description": "what this step does",
|
print(f"[Planner] ⚠️ JSON parse failed: {e}")
|
||||||
"parameters": {},
|
return _fallback_plan(goal)
|
||||||
"critical": true
|
except Exception as e:
|
||||||
}
|
print(f"[Planner] ⚠️ Planning failed: {e}")
|
||||||
]
|
return _fallback_plan(goal)
|
||||||
}
|
|
||||||
"""
|
|
||||||
|
def _fallback_plan(goal: str) -> dict:
|
||||||
|
print("[Planner] 🔄 Fallback plan")
|
||||||
def _get_api_key() -> str:
|
return {
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
"goal": goal,
|
||||||
return json.load(f)["gemini_api_key"]
|
"steps": [
|
||||||
|
{
|
||||||
|
"step": 1,
|
||||||
def create_plan(goal: str, context: str = "") -> dict:
|
"tool": "web_search",
|
||||||
import google.generativeai as genai
|
"description": f"Search for: {goal}",
|
||||||
|
"parameters": {"query": goal},
|
||||||
genai.configure(api_key=_get_api_key())
|
"critical": True,
|
||||||
model = genai.GenerativeModel(
|
}
|
||||||
model_name="gemini-2.5-flash-lite",
|
],
|
||||||
system_instruction=PLANNER_PROMPT
|
}
|
||||||
)
|
|
||||||
|
|
||||||
user_input = f"Goal: {goal}"
|
def replan(goal: str, completed_steps: list, failed_step: dict, error: str) -> dict:
|
||||||
if context:
|
completed_summary = "\n".join(
|
||||||
user_input += f"\n\nContext: {context}"
|
f" - Step {s['step']} ({s['tool']}): DONE" for s in completed_steps
|
||||||
|
)
|
||||||
try:
|
prompt = f"""Goal: {goal}
|
||||||
response = model.generate_content(user_input)
|
|
||||||
text = response.text.strip()
|
Already completed:
|
||||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
{completed_summary if completed_summary else ' (none)'}
|
||||||
|
|
||||||
plan = json.loads(text)
|
Failed step: [{failed_step.get('tool')}] {failed_step.get('description')}
|
||||||
|
Error: {error}
|
||||||
if "steps" not in plan or not isinstance(plan["steps"], list):
|
|
||||||
raise ValueError("Invalid plan structure")
|
Create a REVISED plan for the remaining work only. Do not repeat completed steps."""
|
||||||
|
|
||||||
for step in plan["steps"]:
|
try:
|
||||||
if step.get("tool") in ("generated_code",):
|
text = call_llm_text(prompt, system=PLANNER_PROMPT)
|
||||||
print(f"[Planner] ⚠️ generated_code detected in step {step.get('step')} — replacing with web_search")
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
desc = step.get("description", goal)
|
plan = json.loads(text)
|
||||||
step["tool"] = "web_search"
|
|
||||||
step["parameters"] = {"query": desc[:200]}
|
for step in plan.get("steps", []):
|
||||||
|
if step.get("tool") == "generated_code":
|
||||||
print(f"[Planner] ✅ Plan: {len(plan['steps'])} steps")
|
step["tool"] = "web_search"
|
||||||
for s in plan["steps"]:
|
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
||||||
print(f" Step {s['step']}: [{s['tool']}] {s['description']}")
|
|
||||||
|
print(f"[Planner] 🔄 Revised plan: {len(plan['steps'])} steps")
|
||||||
return plan
|
return plan
|
||||||
|
except Exception as e:
|
||||||
except json.JSONDecodeError as e:
|
print(f"[Planner] ⚠️ Replan failed: {e}")
|
||||||
print(f"[Planner] ⚠️ JSON parse failed: {e}")
|
return _fallback_plan(goal)
|
||||||
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)
|
|
||||||
+26
-17
@@ -1,17 +1,26 @@
|
|||||||
# config/__init__.py
|
# config/__init__.py
|
||||||
import json, os
|
import json
|
||||||
from pathlib import Path
|
import platform
|
||||||
|
from pathlib import Path
|
||||||
_CONFIG_PATH = Path(__file__).parent / "api_keys.json"
|
|
||||||
|
_CONFIG_PATH = Path(__file__).parent / "api_keys.json"
|
||||||
def get_config() -> dict:
|
|
||||||
with open(_CONFIG_PATH, "r", encoding="utf-8") as f:
|
def get_config() -> dict:
|
||||||
return json.load(f)
|
try:
|
||||||
|
with open(_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||||
def get_os() -> str:
|
return json.load(f)
|
||||||
"""Returns: 'windows' | 'mac' | 'linux'"""
|
except Exception:
|
||||||
return get_config().get("os_system", "windows").lower()
|
return {}
|
||||||
|
|
||||||
def is_windows() -> bool: return get_os() == "windows"
|
def get_os() -> str:
|
||||||
def is_mac() -> bool: return get_os() == "mac"
|
"""Returns 'windows' | 'mac' | 'linux' — detected at runtime, not from config."""
|
||||||
def is_linux() -> bool: return get_os() == "linux"
|
s = platform.system().lower()
|
||||||
|
if s == "darwin":
|
||||||
|
return "mac"
|
||||||
|
if s == "windows":
|
||||||
|
return "windows"
|
||||||
|
return "linux"
|
||||||
|
|
||||||
|
def is_windows() -> bool: return get_os() == "windows"
|
||||||
|
def is_mac() -> bool: return get_os() == "mac"
|
||||||
|
def is_linux() -> bool: return get_os() == "linux"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# core package
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""
|
||||||
|
MARK XL — Dependency auto-installer.
|
||||||
|
|
||||||
|
Called automatically on first launch and after engine reconfiguration.
|
||||||
|
Installs only the packages that are actually missing, then exits cleanly.
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import importlib.util
|
||||||
|
import platform
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
# ── Package lists ─────────────────────────────────────────────────────────
|
||||||
|
# Each entry: (import_name, pip_package_name)
|
||||||
|
|
||||||
|
_CORE: list[tuple[str, str]] = [
|
||||||
|
("psutil", "psutil"),
|
||||||
|
("PIL", "pillow"),
|
||||||
|
("sounddevice", "sounddevice"),
|
||||||
|
("numpy", "numpy"),
|
||||||
|
("requests", "requests"),
|
||||||
|
("bs4", "beautifulsoup4"),
|
||||||
|
("duckduckgo_search", "duckduckgo-search"),
|
||||||
|
("pyautogui", "pyautogui"),
|
||||||
|
("pyperclip", "pyperclip"),
|
||||||
|
("pygetwindow", "pygetwindow"),
|
||||||
|
("mss", "mss"),
|
||||||
|
("cv2", "opencv-python"),
|
||||||
|
("soundfile", "soundfile"),
|
||||||
|
("miniaudio", "miniaudio"),
|
||||||
|
("send2trash", "send2trash"),
|
||||||
|
("pptx", "python-pptx"),
|
||||||
|
("youtube_transcript_api", "youtube-transcript-api"),
|
||||||
|
]
|
||||||
|
|
||||||
|
# Windows-only (pywinauto, pycaw, win10toast, comtypes)
|
||||||
|
_WINDOWS: list[tuple[str, str]] = [
|
||||||
|
("comtypes", "comtypes"),
|
||||||
|
("pycaw", "pycaw"),
|
||||||
|
("win10toast", "win10toast"),
|
||||||
|
("pywinauto", "pywinauto"),
|
||||||
|
]
|
||||||
|
|
||||||
|
# STT engine packages
|
||||||
|
_STT: dict[str, list[tuple[str, str]]] = {
|
||||||
|
"whisper": [("faster_whisper", "faster-whisper")],
|
||||||
|
"vosk": [("vosk", "vosk")],
|
||||||
|
}
|
||||||
|
|
||||||
|
# TTS engine packages
|
||||||
|
_TTS: dict[str, list[tuple[str, str]]] = {
|
||||||
|
"edgetts": [("edge_tts", "edge-tts")],
|
||||||
|
"kokoro": [("kokoro", "kokoro")],
|
||||||
|
"elevenlabs": [], # uses only requests, already in core
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# ── Helpers ───────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def _available(module: str) -> bool:
|
||||||
|
"""Return True if the module can be imported (no actual import)."""
|
||||||
|
return importlib.util.find_spec(module) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _pip(package: str, log: Callable | None = None) -> bool:
|
||||||
|
if log:
|
||||||
|
log(f"SYS: pip install {package} …")
|
||||||
|
result = subprocess.run(
|
||||||
|
[
|
||||||
|
sys.executable, "-m", "pip", "install", package,
|
||||||
|
"--quiet", "--disable-pip-version-check",
|
||||||
|
],
|
||||||
|
capture_output=True,
|
||||||
|
)
|
||||||
|
ok = result.returncode == 0
|
||||||
|
if not ok and log:
|
||||||
|
stderr = result.stderr.decode(errors="replace").strip()
|
||||||
|
log(f"ERR: {package} install failed — {stderr[:140]}")
|
||||||
|
return ok
|
||||||
|
|
||||||
|
|
||||||
|
# ── Public API ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
def install_for_config(config: dict, log: Callable | None = None) -> None:
|
||||||
|
"""
|
||||||
|
Install all missing packages required by *config*.
|
||||||
|
|
||||||
|
Blocking — always call from a background thread.
|
||||||
|
Progress is reported via the optional *log* callback (receives a str).
|
||||||
|
"""
|
||||||
|
stt = config.get("stt_engine", "whisper").lower()
|
||||||
|
tts = config.get("tts_engine", "edgetts").lower()
|
||||||
|
|
||||||
|
needed: list[tuple[str, str]] = list(_CORE)
|
||||||
|
needed += _STT.get(stt, [])
|
||||||
|
needed += _TTS.get(tts, [])
|
||||||
|
if platform.system() == "Windows":
|
||||||
|
needed += _WINDOWS
|
||||||
|
|
||||||
|
# Deduplicate (preserve order, key = pip name)
|
||||||
|
seen: set[str] = set()
|
||||||
|
unique: list[tuple[str, str]] = []
|
||||||
|
for mod, pkg in needed:
|
||||||
|
if pkg not in seen:
|
||||||
|
seen.add(pkg)
|
||||||
|
unique.append((mod, pkg))
|
||||||
|
|
||||||
|
missing = [(mod, pkg) for mod, pkg in unique if not _available(mod)]
|
||||||
|
|
||||||
|
if not missing:
|
||||||
|
if log:
|
||||||
|
log("SYS: All dependencies already installed ✓")
|
||||||
|
return
|
||||||
|
|
||||||
|
pkg_names = ", ".join(p for _, p in missing)
|
||||||
|
if log:
|
||||||
|
log(f"SYS: Installing {len(missing)} package(s): {pkg_names}")
|
||||||
|
|
||||||
|
for _mod, pkg in missing:
|
||||||
|
_pip(pkg, log)
|
||||||
|
|
||||||
|
# Playwright: install the package + download Chromium browser
|
||||||
|
if not _available("playwright"):
|
||||||
|
_pip("playwright", log)
|
||||||
|
if log:
|
||||||
|
log("SYS: Downloading Playwright browser (Chromium, ~150 MB — one-time)…")
|
||||||
|
subprocess.run(
|
||||||
|
[sys.executable, "-m", "playwright", "install", "chromium"],
|
||||||
|
capture_output=True,
|
||||||
|
)
|
||||||
|
if log:
|
||||||
|
log("SYS: Playwright browser ready.")
|
||||||
|
|
||||||
|
if log:
|
||||||
|
log("SYS: All dependencies ready ✓")
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
"""
|
||||||
|
Ollama LLM client for MARK XL.
|
||||||
|
Replaces Google Gemini API with local Ollama inference.
|
||||||
|
All modules that previously used google.generativeai import from here.
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Generator
|
||||||
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
# Matches a sentence boundary: [.!?] followed by whitespace, or a blank line.
|
||||||
|
# Avoids splitting on decimals (3.5) because those have no space after the dot.
|
||||||
|
_SENT_END = re.compile(r'(?<=[.!?])\s+|(?<=\n)\s*\n')
|
||||||
|
|
||||||
|
def get_base_dir() -> Path:
|
||||||
|
if getattr(sys, "frozen", False):
|
||||||
|
return Path(sys.executable).parent
|
||||||
|
return Path(__file__).resolve().parent.parent
|
||||||
|
|
||||||
|
|
||||||
|
BASE_DIR = get_base_dir()
|
||||||
|
CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
||||||
|
|
||||||
|
_DEFAULTS = {
|
||||||
|
"llm_url": "http://localhost:11434",
|
||||||
|
"llm_model": "llama3.2",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _load_config() -> dict:
|
||||||
|
try:
|
||||||
|
return json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_ollama_running(timeout: int = 15) -> bool:
|
||||||
|
"""
|
||||||
|
Ping Ollama; if it's not responding, launch 'ollama serve' in the background
|
||||||
|
and wait up to `timeout` seconds for it to become ready.
|
||||||
|
Returns True if Ollama is available, False otherwise.
|
||||||
|
"""
|
||||||
|
url, _ = get_llm_settings()
|
||||||
|
health = f"{url}/api/tags"
|
||||||
|
|
||||||
|
def _is_up() -> bool:
|
||||||
|
try:
|
||||||
|
return requests.get(health, timeout=3).status_code == 200
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
if _is_up():
|
||||||
|
return True
|
||||||
|
|
||||||
|
print("[LLM] Ollama not running — launching 'ollama serve'…")
|
||||||
|
try:
|
||||||
|
kwargs: dict = {"stdout": subprocess.DEVNULL, "stderr": subprocess.DEVNULL}
|
||||||
|
if sys.platform == "win32":
|
||||||
|
kwargs["creationflags"] = subprocess.CREATE_NO_WINDOW
|
||||||
|
subprocess.Popen(["ollama", "serve"], **kwargs)
|
||||||
|
except FileNotFoundError:
|
||||||
|
print("[LLM] 'ollama' command not found. Install Ollama from https://ollama.com")
|
||||||
|
return False
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[LLM] Could not launch Ollama: {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
deadline = time.time() + timeout
|
||||||
|
while time.time() < deadline:
|
||||||
|
time.sleep(1.0)
|
||||||
|
if _is_up():
|
||||||
|
print("[LLM] Ollama started successfully.")
|
||||||
|
return True
|
||||||
|
|
||||||
|
print("[LLM] Ollama did not respond within the timeout.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def warmup_model() -> bool:
|
||||||
|
"""
|
||||||
|
Pre-load the model into Ollama memory so the first real request is instant.
|
||||||
|
Sends a minimal 1-token request with keep_alive=-1.
|
||||||
|
Returns True on success, False if warmup failed (non-fatal).
|
||||||
|
"""
|
||||||
|
url, model = get_llm_settings()
|
||||||
|
print(f"[LLM] Warming up '{model}'…")
|
||||||
|
payload = {
|
||||||
|
"model": model,
|
||||||
|
"messages": [{"role": "user", "content": "hi"}],
|
||||||
|
"stream": False,
|
||||||
|
"keep_alive": -1,
|
||||||
|
"options": {"num_predict": 1},
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
resp = requests.post(f"{url}/api/chat", json=payload, timeout=120)
|
||||||
|
resp.raise_for_status()
|
||||||
|
print(f"[LLM] '{model}' loaded and ready.")
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[LLM] Warmup failed (non-fatal): {e}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def get_llm_settings() -> tuple[str, str]:
|
||||||
|
"""Returns (base_url, model_name)."""
|
||||||
|
cfg = _load_config()
|
||||||
|
url = cfg.get("llm_url", _DEFAULTS["llm_url"]).rstrip("/")
|
||||||
|
model = cfg.get("llm_model", _DEFAULTS["llm_model"])
|
||||||
|
return url, model
|
||||||
|
|
||||||
|
|
||||||
|
def call_llm(
|
||||||
|
messages: list,
|
||||||
|
tools: list | None = None,
|
||||||
|
timeout: int = 120,
|
||||||
|
) -> dict:
|
||||||
|
"""
|
||||||
|
Chat request to Ollama (with optional tool declarations).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
{"content": str, "tool_calls": list}
|
||||||
|
"""
|
||||||
|
url, model = get_llm_settings()
|
||||||
|
endpoint = f"{url}/api/chat"
|
||||||
|
|
||||||
|
payload: dict = {
|
||||||
|
"model": model,
|
||||||
|
"messages": messages,
|
||||||
|
"stream": False,
|
||||||
|
"keep_alive": -1,
|
||||||
|
"options": {"num_predict": 600},
|
||||||
|
}
|
||||||
|
if tools:
|
||||||
|
payload["tools"] = tools
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = requests.post(endpoint, json=payload, timeout=timeout)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
msg = data.get("message", {})
|
||||||
|
return {
|
||||||
|
"content": (msg.get("content") or "").strip(),
|
||||||
|
"tool_calls": msg.get("tool_calls") or [],
|
||||||
|
}
|
||||||
|
except requests.exceptions.ConnectionError as e:
|
||||||
|
print(f"[LLM] ConnectionError — trying to restart Ollama… ({e})")
|
||||||
|
if ensure_ollama_running():
|
||||||
|
try:
|
||||||
|
resp = requests.post(endpoint, json=payload, timeout=timeout)
|
||||||
|
resp.raise_for_status()
|
||||||
|
data = resp.json()
|
||||||
|
msg = data.get("message", {})
|
||||||
|
return {
|
||||||
|
"content": (msg.get("content") or "").strip(),
|
||||||
|
"tool_calls": msg.get("tool_calls") or [],
|
||||||
|
}
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Cannot connect to Ollama at {url}. "
|
||||||
|
"Make sure Ollama is installed and run: ollama serve"
|
||||||
|
)
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
raise RuntimeError("Ollama request timed out after 120 s.")
|
||||||
|
except requests.exceptions.HTTPError as e:
|
||||||
|
print(f"[LLM] HTTPError: {e.response.status_code} — {e.response.text[:200]}")
|
||||||
|
raise RuntimeError(f"Ollama HTTP error: {e.response.status_code}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[LLM] Unexpected error: {type(e).__name__}: {e}")
|
||||||
|
raise RuntimeError(f"LLM call failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
def call_llm_text(
|
||||||
|
prompt: str,
|
||||||
|
system: str | None = None,
|
||||||
|
model: str | None = None,
|
||||||
|
timeout: int = 120,
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Simple text-only generation (no tools).
|
||||||
|
Used by planner, executor, error_handler, code_helper, dev_agent.
|
||||||
|
"""
|
||||||
|
url, default_model = get_llm_settings()
|
||||||
|
endpoint = f"{url}/api/chat"
|
||||||
|
m = model or default_model
|
||||||
|
|
||||||
|
messages: list[dict] = []
|
||||||
|
if system:
|
||||||
|
messages.append({"role": "system", "content": system})
|
||||||
|
messages.append({"role": "user", "content": prompt})
|
||||||
|
|
||||||
|
payload = {"model": m, "messages": messages, "stream": False, "keep_alive": -1, "options": {"num_predict": 600}}
|
||||||
|
|
||||||
|
try:
|
||||||
|
resp = requests.post(endpoint, json=payload, timeout=timeout)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return (resp.json().get("message", {}).get("content") or "").strip()
|
||||||
|
except requests.exceptions.ConnectionError:
|
||||||
|
if ensure_ollama_running():
|
||||||
|
try:
|
||||||
|
resp = requests.post(endpoint, json=payload, timeout=timeout)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return (resp.json().get("message", {}).get("content") or "").strip()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Cannot connect to Ollama at {url}. "
|
||||||
|
"Make sure Ollama is installed and run: ollama serve"
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
raise RuntimeError(f"LLM text call failed: {e}")
|
||||||
|
|
||||||
|
|
||||||
|
def call_llm_stream(
|
||||||
|
messages: list,
|
||||||
|
tools: list | None = None,
|
||||||
|
timeout: int = 120,
|
||||||
|
) -> Generator[dict, None, None]:
|
||||||
|
"""
|
||||||
|
Streaming chat request to Ollama.
|
||||||
|
|
||||||
|
Yields:
|
||||||
|
{"type": "sentence", "text": str} — each complete sentence as it arrives
|
||||||
|
{"type": "done", "content": str, "tool_calls": list} — when stream ends
|
||||||
|
|
||||||
|
Sentences are split on [.!?] + whitespace so TTS can start immediately.
|
||||||
|
Tool calls (if any) always appear in the final "done" event with empty content.
|
||||||
|
"""
|
||||||
|
url, model = get_llm_settings()
|
||||||
|
endpoint = f"{url}/api/chat"
|
||||||
|
|
||||||
|
payload: dict = {
|
||||||
|
"model": model,
|
||||||
|
"messages": messages,
|
||||||
|
"stream": True,
|
||||||
|
"keep_alive": -1,
|
||||||
|
"options": {"num_predict": 600},
|
||||||
|
}
|
||||||
|
if tools:
|
||||||
|
payload["tools"] = tools
|
||||||
|
|
||||||
|
def _do_stream() -> Generator[dict, None, None]:
|
||||||
|
with requests.post(endpoint, json=payload, timeout=timeout, stream=True) as resp:
|
||||||
|
resp.raise_for_status()
|
||||||
|
full_content = ""
|
||||||
|
tool_calls: list = []
|
||||||
|
buf = ""
|
||||||
|
|
||||||
|
for raw in resp.iter_lines():
|
||||||
|
if not raw:
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
chunk = json.loads(raw)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
continue
|
||||||
|
|
||||||
|
msg = chunk.get("message", {})
|
||||||
|
delta = msg.get("content") or ""
|
||||||
|
full_content += delta
|
||||||
|
buf += delta
|
||||||
|
|
||||||
|
# Yield complete sentences as they accumulate
|
||||||
|
while True:
|
||||||
|
m = _SENT_END.search(buf)
|
||||||
|
if not m:
|
||||||
|
break
|
||||||
|
sentence = buf[: m.start() + 1].strip()
|
||||||
|
buf = buf[m.end() :]
|
||||||
|
if sentence:
|
||||||
|
yield {"type": "sentence", "text": sentence}
|
||||||
|
|
||||||
|
tc = msg.get("tool_calls")
|
||||||
|
if tc:
|
||||||
|
tool_calls.extend(tc)
|
||||||
|
|
||||||
|
if chunk.get("done"):
|
||||||
|
if buf.strip():
|
||||||
|
yield {"type": "sentence", "text": buf.strip()}
|
||||||
|
yield {
|
||||||
|
"type": "done",
|
||||||
|
"content": full_content.strip(),
|
||||||
|
"tool_calls": tool_calls,
|
||||||
|
}
|
||||||
|
return
|
||||||
|
|
||||||
|
try:
|
||||||
|
yield from _do_stream()
|
||||||
|
except requests.exceptions.ConnectionError as e:
|
||||||
|
print(f"[LLM] Stream ConnectionError — trying to restart Ollama… ({e})")
|
||||||
|
if ensure_ollama_running():
|
||||||
|
yield from _do_stream()
|
||||||
|
return
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Cannot connect to Ollama at {url}. "
|
||||||
|
"Make sure Ollama is installed and run: ollama serve"
|
||||||
|
)
|
||||||
|
except requests.exceptions.Timeout:
|
||||||
|
raise RuntimeError("Ollama stream timed out.")
|
||||||
|
except requests.exceptions.HTTPError as e:
|
||||||
|
raise RuntimeError(f"Ollama HTTP error: {e.response.status_code}")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[LLM] Stream error: {type(e).__name__}: {e}")
|
||||||
|
raise RuntimeError(f"LLM stream failed: {e}")
|
||||||
+1
-2
@@ -1,5 +1,5 @@
|
|||||||
🧠 JARVIS CORE PROTOCOL
|
🧠 JARVIS CORE PROTOCOL
|
||||||
IDENTITY: Efficient, professional, direct assistant. No fluff.
|
IDENTITY: You are Jarvis. Efficient, professional, direct assistant. No fluff.
|
||||||
|
|
||||||
EXECUTION RULES:
|
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.
|
Language: Respond in user's language; extract parameters in English.
|
||||||
Do not call agent_task while you can accomplish it with a tool
|
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.
|
CRITICAL: Speak/Take action immediately based on available info. Assume and proceed.
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
"""
|
||||||
|
Speech-to-Text engines for MARK XL.
|
||||||
|
|
||||||
|
Whisper – offline transcription via faster-whisper (VAD-buffered)
|
||||||
|
Vosk – offline streaming transcription (lighter)
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import numpy as np
|
||||||
|
|
||||||
|
|
||||||
|
class WhisperSTT:
|
||||||
|
"""Offline transcription using faster-whisper."""
|
||||||
|
|
||||||
|
def __init__(self, model_name: str = "base", language: str | None = None):
|
||||||
|
from faster_whisper import WhisperModel
|
||||||
|
print(f"[STT] Loading Whisper '{model_name}'…")
|
||||||
|
self._model = WhisperModel(model_name, device="cpu", compute_type="int8")
|
||||||
|
# None → auto-detect; explicit code (e.g. "tr", "de") forces that language
|
||||||
|
self._language = None if (not language or language.strip().lower() == "auto") else language.strip().lower()
|
||||||
|
print("[STT] Whisper ready.")
|
||||||
|
|
||||||
|
def transcribe(self, audio: np.ndarray) -> str:
|
||||||
|
"""
|
||||||
|
Transcribe a float32 mono 16 kHz numpy array.
|
||||||
|
Returns transcript string (may be empty).
|
||||||
|
"""
|
||||||
|
segments, _ = self._model.transcribe(
|
||||||
|
audio,
|
||||||
|
language=self._language,
|
||||||
|
vad_filter=True,
|
||||||
|
vad_parameters={"min_silence_duration_ms": 300},
|
||||||
|
)
|
||||||
|
return " ".join(s.text for s in segments).strip()
|
||||||
|
|
||||||
|
|
||||||
|
class VoskSTT:
|
||||||
|
"""Streaming transcription using Vosk."""
|
||||||
|
|
||||||
|
def __init__(self, model_path: str | None = None, language: str = "en-us"):
|
||||||
|
from vosk import Model, KaldiRecognizer
|
||||||
|
print("[STT] Loading Vosk model…")
|
||||||
|
if model_path:
|
||||||
|
model = Model(model_path)
|
||||||
|
else:
|
||||||
|
lang = language.strip().lower() if language and language.strip().lower() != "auto" else "en-us"
|
||||||
|
model = Model(lang=lang)
|
||||||
|
self._rec = KaldiRecognizer(model, 16000)
|
||||||
|
print("[STT] Vosk ready.")
|
||||||
|
|
||||||
|
def process_chunk(self, audio_bytes: bytes) -> tuple[str, bool]:
|
||||||
|
"""
|
||||||
|
Feed raw int16 LE PCM bytes.
|
||||||
|
Returns (text, is_final).
|
||||||
|
"""
|
||||||
|
if self._rec.AcceptWaveform(audio_bytes):
|
||||||
|
result = json.loads(self._rec.Result())
|
||||||
|
return result.get("text", ""), True
|
||||||
|
partial = json.loads(self._rec.PartialResult())
|
||||||
|
return partial.get("partial", ""), False
|
||||||
+276
@@ -0,0 +1,276 @@
|
|||||||
|
"""
|
||||||
|
Text-to-Speech engines for MARK XL.
|
||||||
|
|
||||||
|
EdgeTTS – free Microsoft TTS (internet required, no API key)
|
||||||
|
Kokoro – fully offline neural TTS (~330 MB model)
|
||||||
|
ElevenLabs – cloud API (API key required, best quality)
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import threading
|
||||||
|
from typing import Callable, Optional
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import sounddevice as sd
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Audio playback helpers
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _to_numpy(samples) -> np.ndarray:
|
||||||
|
"""Convert samples to float32 numpy array.
|
||||||
|
|
||||||
|
Handles both numpy arrays and PyTorch tensors (Kokoro >= 0.9).
|
||||||
|
|
||||||
|
PyTorch built against numpy 1.x raises RuntimeError('Numpy is not available')
|
||||||
|
when numpy 2.x is installed. The .tolist() fallback always works regardless
|
||||||
|
of PyTorch / numpy version pairing.
|
||||||
|
"""
|
||||||
|
if hasattr(samples, "detach"): # PyTorch tensor
|
||||||
|
t = samples.detach().cpu().float()
|
||||||
|
try:
|
||||||
|
return t.numpy() # fast path (compatible versions)
|
||||||
|
except RuntimeError:
|
||||||
|
# PyTorch/numpy version mismatch — convert via Python list (always safe)
|
||||||
|
return np.asarray(t.tolist(), dtype=np.float32)
|
||||||
|
return np.asarray(samples, dtype=np.float32)
|
||||||
|
|
||||||
|
|
||||||
|
def _compress_silence(
|
||||||
|
arr: np.ndarray,
|
||||||
|
sample_rate: int = 24_000,
|
||||||
|
max_silence_ms: int = 300, # cap long pauses to this many ms
|
||||||
|
threshold: float = 0.0015, # RMS below this = silence (very conservative)
|
||||||
|
) -> np.ndarray:
|
||||||
|
"""
|
||||||
|
Shorten excessively long silent segments in Kokoro audio.
|
||||||
|
|
||||||
|
Kokoro can produce 1-2 s pauses after punctuation. This caps them
|
||||||
|
to max_silence_ms while leaving natural short pauses intact.
|
||||||
|
|
||||||
|
threshold is intentionally low (0.0015) so soft consonants like
|
||||||
|
's', 'f', 'h' are never misidentified as silence.
|
||||||
|
"""
|
||||||
|
max_samp = int(max_silence_ms * sample_rate / 1000)
|
||||||
|
frame_len = 240 # ~10 ms at 24 kHz
|
||||||
|
out: list[np.ndarray] = []
|
||||||
|
silent_acc = 0
|
||||||
|
|
||||||
|
for i in range(0, len(arr), frame_len):
|
||||||
|
chunk = arr[i : i + frame_len]
|
||||||
|
if np.sqrt(np.mean(chunk ** 2) + 1e-12) < threshold:
|
||||||
|
silent_acc += len(chunk)
|
||||||
|
if silent_acc <= max_samp:
|
||||||
|
out.append(chunk)
|
||||||
|
else:
|
||||||
|
silent_acc = 0
|
||||||
|
out.append(chunk)
|
||||||
|
|
||||||
|
return np.concatenate(out) if out else arr
|
||||||
|
|
||||||
|
|
||||||
|
def _play_np(samples, sample_rate: int) -> None:
|
||||||
|
"""Play float32 mono (or stereo) audio via sounddevice.
|
||||||
|
Accepts numpy arrays or PyTorch tensors.
|
||||||
|
"""
|
||||||
|
sd.play(_to_numpy(samples), sample_rate)
|
||||||
|
sd.wait()
|
||||||
|
|
||||||
|
|
||||||
|
def _play_audio_bytes(audio_bytes: bytes) -> None:
|
||||||
|
"""Decode MP3/WAV/OGG bytes and play via sounddevice (uses miniaudio)."""
|
||||||
|
import miniaudio
|
||||||
|
decoded = miniaudio.decode(
|
||||||
|
audio_bytes,
|
||||||
|
output_format=miniaudio.SampleFormat.FLOAT32,
|
||||||
|
nchannels=1,
|
||||||
|
)
|
||||||
|
samples = np.array(decoded.samples, dtype=np.float32)
|
||||||
|
sd.play(samples, decoded.sample_rate)
|
||||||
|
sd.wait()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Engines
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class EdgeTTSEngine:
|
||||||
|
"""Microsoft EdgeTTS – free, requires internet."""
|
||||||
|
|
||||||
|
def __init__(self, voice: str = "en-US-GuyNeural"):
|
||||||
|
self.voice = voice
|
||||||
|
|
||||||
|
def speak(self, text: str) -> None:
|
||||||
|
loop = asyncio.new_event_loop()
|
||||||
|
try:
|
||||||
|
audio_bytes = loop.run_until_complete(self._synth(text))
|
||||||
|
finally:
|
||||||
|
loop.close()
|
||||||
|
if audio_bytes:
|
||||||
|
_play_audio_bytes(audio_bytes)
|
||||||
|
|
||||||
|
async def _synth(self, text: str) -> bytes:
|
||||||
|
import edge_tts
|
||||||
|
comm = edge_tts.Communicate(text, self.voice)
|
||||||
|
buf = bytearray()
|
||||||
|
async for chunk in comm.stream():
|
||||||
|
if chunk["type"] == "audio":
|
||||||
|
buf.extend(chunk["data"])
|
||||||
|
return bytes(buf)
|
||||||
|
|
||||||
|
|
||||||
|
# Kokoro voice prefix → KPipeline lang_code mapping
|
||||||
|
_KOKORO_LANG_CODES = {
|
||||||
|
"a": "a", # American English (af_*, am_*)
|
||||||
|
"b": "b", # British English (bf_*, bm_*)
|
||||||
|
"j": "j", # Japanese (jf_*, jm_*)
|
||||||
|
"z": "z", # Mandarin Chinese (zf_*, zm_*)
|
||||||
|
"s": "s", # Spanish (sf_*, sm_*)
|
||||||
|
"f": "f", # French (ff_*, fm_*)
|
||||||
|
"h": "h", # Hindi (hf_*, hm_*)
|
||||||
|
"i": "i", # Italian (if_*, im_*)
|
||||||
|
"p": "p", # Brazilian Portuguese
|
||||||
|
"r": "r", # Russian (rf_*, rm_*)
|
||||||
|
"e": "e", # German (ef_*, em_*)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class KokoroTTSEngine:
|
||||||
|
"""Fully offline Kokoro neural TTS.
|
||||||
|
|
||||||
|
Model (~330 MB) is downloaded from HuggingFace on first use.
|
||||||
|
Subsequent runs load from local cache instantly.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, voice: str = "af_heart", speed: float = 1.2):
|
||||||
|
self.voice = voice
|
||||||
|
self.speed = speed # 1.0 = normal, 1.2 = 20% faster (recommended)
|
||||||
|
self._pipeline = None
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
# Eager init: download/load model now so it's ready before first speak()
|
||||||
|
self._init()
|
||||||
|
|
||||||
|
# Detect lang_code from voice prefix (e.g. "af_heart" → "a")
|
||||||
|
@property
|
||||||
|
def _lang_code(self) -> str:
|
||||||
|
prefix = self.voice[0].lower() if self.voice else "a"
|
||||||
|
return _KOKORO_LANG_CODES.get(prefix, "a")
|
||||||
|
|
||||||
|
def _init(self) -> None:
|
||||||
|
if self._pipeline is not None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
from kokoro import KPipeline
|
||||||
|
lang = self._lang_code
|
||||||
|
print(f"[TTS] Loading Kokoro pipeline (lang='{lang}', voice='{self.voice}')…")
|
||||||
|
print("[TTS] Kokoro model will be downloaded (~330 MB) if not cached.")
|
||||||
|
self._pipeline = KPipeline(lang_code=lang)
|
||||||
|
print("[TTS] Kokoro pipeline ready.")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[TTS] Kokoro init error: {e}")
|
||||||
|
raise
|
||||||
|
|
||||||
|
def speak(self, text: str) -> None:
|
||||||
|
with self._lock:
|
||||||
|
if self._pipeline is None:
|
||||||
|
self._init()
|
||||||
|
for _, _, audio in self._pipeline(text, voice=self.voice, speed=self.speed):
|
||||||
|
if audio is not None:
|
||||||
|
arr = _to_numpy(audio)
|
||||||
|
arr = _compress_silence(arr) # shorten long punctuation pauses
|
||||||
|
if arr.size > 0:
|
||||||
|
_play_np(arr, 24000)
|
||||||
|
|
||||||
|
|
||||||
|
class ElevenLabsTTSEngine:
|
||||||
|
"""ElevenLabs cloud TTS – API key required."""
|
||||||
|
|
||||||
|
def __init__(self, api_key: str, voice_id: str = "pNInz6obpgDQGcFmaJgB"):
|
||||||
|
self.api_key = api_key
|
||||||
|
self.voice_id = voice_id
|
||||||
|
|
||||||
|
def speak(self, text: str) -> None:
|
||||||
|
import requests
|
||||||
|
headers = {
|
||||||
|
"xi-api-key": self.api_key,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
payload = {
|
||||||
|
"text": text,
|
||||||
|
"model_id": "eleven_multilingual_v2",
|
||||||
|
"voice_settings": {"stability": 0.5, "similarity_boost": 0.75},
|
||||||
|
}
|
||||||
|
resp = requests.post(
|
||||||
|
f"https://api.elevenlabs.io/v1/text-to-speech/{self.voice_id}",
|
||||||
|
json=payload, headers=headers, timeout=30,
|
||||||
|
)
|
||||||
|
resp.raise_for_status()
|
||||||
|
_play_audio_bytes(resp.content)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Thread-safe player wrapper
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
class TTSPlayer:
|
||||||
|
"""
|
||||||
|
Wraps any *Engine. Exposes a blocking speak() method
|
||||||
|
meant to be called from a dedicated background thread.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, engine):
|
||||||
|
self._engine = engine
|
||||||
|
self._playing = False
|
||||||
|
self._lock = threading.Lock()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def is_playing(self) -> bool:
|
||||||
|
return self._playing
|
||||||
|
|
||||||
|
def speak(
|
||||||
|
self,
|
||||||
|
text: str,
|
||||||
|
on_start: Optional[Callable] = None,
|
||||||
|
on_done: Optional[Callable] = None,
|
||||||
|
) -> None:
|
||||||
|
"""Synthesise and play text. BLOCKING – call from a dedicated thread."""
|
||||||
|
try:
|
||||||
|
with self._lock:
|
||||||
|
self._playing = True
|
||||||
|
if on_start:
|
||||||
|
on_start()
|
||||||
|
self._engine.speak(text)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[TTS] Error: {e}")
|
||||||
|
finally:
|
||||||
|
with self._lock:
|
||||||
|
self._playing = False
|
||||||
|
if on_done:
|
||||||
|
on_done()
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
sd.stop()
|
||||||
|
with self._lock:
|
||||||
|
self._playing = False
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Factory
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def create_tts_player(config: dict) -> TTSPlayer:
|
||||||
|
engine_name = config.get("tts_engine", "edgetts").lower()
|
||||||
|
if engine_name == "kokoro":
|
||||||
|
voice = config.get("tts_voice", "af_heart")
|
||||||
|
speed = float(config.get("tts_speed", 1.2))
|
||||||
|
engine = KokoroTTSEngine(voice=voice, speed=speed)
|
||||||
|
elif engine_name == "elevenlabs":
|
||||||
|
api_key = config.get("elevenlabs_api_key", "")
|
||||||
|
voice_id = config.get("tts_voice", "pNInz6obpgDQGcFmaJgB")
|
||||||
|
engine = ElevenLabsTTSEngine(api_key=api_key, voice_id=voice_id)
|
||||||
|
else: # edgetts (default)
|
||||||
|
voice = config.get("tts_voice", "en-US-GuyNeural")
|
||||||
|
engine = EdgeTTSEngine(voice=voice)
|
||||||
|
return TTSPlayer(engine)
|
||||||
+54
-51
@@ -1,51 +1,54 @@
|
|||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
def get_base_dir() -> Path:
|
|
||||||
if getattr(sys, "frozen", False):
|
def get_base_dir() -> Path:
|
||||||
return Path(sys.executable).parent
|
if getattr(sys, "frozen", False):
|
||||||
return Path(__file__).resolve().parent.parent
|
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"
|
BASE_DIR = get_base_dir()
|
||||||
|
CONFIG_DIR = BASE_DIR / "config"
|
||||||
def ensure_config_dir() -> None:
|
CONFIG_FILE = CONFIG_DIR / "api_keys.json"
|
||||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
|
||||||
|
|
||||||
def config_exists() -> bool:
|
def ensure_config_dir() -> None:
|
||||||
return CONFIG_FILE.exists()
|
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
def save_api_keys(gemini_api_key: str) -> None:
|
|
||||||
ensure_config_dir()
|
def config_exists() -> bool:
|
||||||
|
return CONFIG_FILE.exists()
|
||||||
data: dict = {}
|
|
||||||
if CONFIG_FILE.exists():
|
|
||||||
try:
|
def save_config(cfg: dict) -> None:
|
||||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
ensure_config_dir()
|
||||||
except Exception:
|
existing: dict = {}
|
||||||
data = {}
|
if CONFIG_FILE.exists():
|
||||||
|
try:
|
||||||
data["gemini_api_key"] = gemini_api_key.strip()
|
existing = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||||
|
except Exception:
|
||||||
CONFIG_FILE.write_text(
|
existing = {}
|
||||||
json.dumps(data, indent=2),
|
existing.update(cfg)
|
||||||
encoding="utf-8"
|
CONFIG_FILE.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||||
)
|
|
||||||
|
|
||||||
def load_api_keys() -> dict:
|
def load_api_keys() -> dict:
|
||||||
if not CONFIG_FILE.exists():
|
if not CONFIG_FILE.exists():
|
||||||
return {}
|
return {}
|
||||||
try:
|
try:
|
||||||
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
return json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ Failed to load api_keys.json: {e}")
|
print(f"❌ Failed to load api_keys.json: {e}")
|
||||||
return {}
|
return {}
|
||||||
|
|
||||||
def get_gemini_key() -> str | None:
|
|
||||||
return load_api_keys().get("gemini_api_key")
|
def is_configured() -> bool:
|
||||||
|
cfg = load_api_keys()
|
||||||
def is_configured() -> bool:
|
return (
|
||||||
key = get_gemini_key()
|
bool(cfg.get("os_system")) and
|
||||||
return bool(key and len(key) > 15)
|
bool(cfg.get("llm_model")) and
|
||||||
|
bool(cfg.get("stt_engine")) and
|
||||||
|
bool(cfg.get("tts_engine"))
|
||||||
|
)
|
||||||
@@ -1,81 +1,159 @@
|
|||||||
# 🤖 MARK XXXIX (39)
|
# 🤖 MARK XL — Local AI Assistant
|
||||||
### The Ultimate Cross-Platform Personal AI Assistant — By FatihMakes
|
|
||||||
|
> **J.A.R.V.I.S** — Just A Rather Very Intelligent System
|
||||||
> 📺 **[Watch the full setup video on YouTube](https://youtu.be/ej1f5OE3SNQ?si=lCxDhJix9ungq1Ry)**
|
> Cross-platform voice AI assistant running entirely on local hardware. No cloud APIs required.
|
||||||
|
|
||||||
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
|
||||||
|
|
||||||
## ✨ 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.
|
||||||
|
|
||||||
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.
|
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.
|
||||||
|
|
||||||
It's not just an assistant — it's an extension of your digital life.
|
---
|
||||||
|
|
||||||
---
|
## Architecture
|
||||||
|
|
||||||
## 🚀 Capabilities
|
```
|
||||||
|
Microphone → STT (Whisper / Vosk)
|
||||||
### Core Features
|
↓
|
||||||
| Feature | Description |
|
Ollama LLM (tool calling + streaming)
|
||||||
|---|---|
|
↓
|
||||||
| 🎙️ Real-time Voice | Ultra-low latency conversation in any language |
|
Tool Execution (OS, Browser, Files …)
|
||||||
| 🖥️ System Control | Launch apps, manage files, execute terminal commands |
|
↓
|
||||||
| 🧩 Autonomous Tasks | High-level planning for complex, multi-step goals |
|
TTS (EdgeTTS / Kokoro / ElevenLabs)
|
||||||
| 👁️ Visual Awareness | Real-time screen processing and webcam vision |
|
↓
|
||||||
| 🧠 Persistent Memory | Deeply remembers your projects, preferences, and personal context |
|
Speaker
|
||||||
| ⌨️ Hybrid Input | Seamlessly switch between keyboard typing and voice commands |
|
```
|
||||||
|
|
||||||
---
|
### Core Components
|
||||||
|
|
||||||
## 🆕 What's New in XXXIX
|
| Layer | Technology | Notes |
|
||||||
|
|-------|-----------|-------|
|
||||||
- 📂 **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.
|
| **STT** | faster-whisper / Vosk | Fully offline. Auto language detection or forced locale. |
|
||||||
- 🎨 **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.
|
| **LLM** | Ollama (any model) | qwen2.5, llama3.2, mistral, etc. Streaming + tool calling. |
|
||||||
- 🐧🍎 **Refined Cross-Platform Stability** — Major fixes for macOS and Linux compatibility. Core system actions are now more consistent across all three major operating systems.
|
| **TTS** | EdgeTTS / Kokoro / ElevenLabs | EdgeTTS = free + internet. Kokoro = fully offline. |
|
||||||
- ⚡ **Optimized Core Engine** — Significant performance boost in tool-calling logic and response generation, resulting in a 40% faster interaction speed.
|
| **UI** | PyQt6 | HUD overlay with system monitor, log panel, file drop zone. |
|
||||||
|
| **Agent** | Custom task queue | Multi-step planner + executor + error recovery. |
|
||||||
---
|
|
||||||
|
---
|
||||||
## ⚡ Quick Start
|
|
||||||
|
## Features
|
||||||
```bash
|
|
||||||
git clone https://github.com/FatihMakes/Mark-XXXIX.git
|
- **Streaming responses** — TTS starts speaking on the first sentence, not after the full response
|
||||||
cd Mark-XXXIX
|
- **Tool calling** — 18 built-in tools: browser control, file management, weather, YouTube, messaging, screen analysis, code helper, game updater, flight finder, and more
|
||||||
pip install -r requirements.txt
|
- **Long-term memory** — Silently saves personal facts; recalled in every conversation
|
||||||
playwright install
|
- **Live configuration** — Change LLM model, STT engine, TTS voice without restarting (⚙ Configure button)
|
||||||
python main.py
|
- **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`, …)
|
||||||
> ⚠️ **Installation Note:** To keep the repository lightweight, some OS-specific dependencies are not bundled in `requirements.txt`. If you run into a `ModuleNotFoundError`, simply install the missing package via `pip install <module_name>` for your specific system.
|
- **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
|
|
||||||
|
## Requirements
|
||||||
| Requirement | Details |
|
|
||||||
|---|---|
|
- Python 3.11 or 3.12
|
||||||
| **OS** | Windows 10/11, macOS, or Linux |
|
- [Ollama](https://ollama.com) installed and a model pulled (e.g. `ollama pull qwen2.5:7b`)
|
||||||
| **Python** | 3.11 or 3.12 |
|
- A microphone
|
||||||
| **Microphone** | Required for voice interaction |
|
|
||||||
| **API Key** | Free Gemini API key |
|
---
|
||||||
|
|
||||||
---
|
## Quick Start
|
||||||
|
|
||||||
## ⚠️ License
|
```bash
|
||||||
|
# 1. Install Ollama → https://ollama.com
|
||||||
Personal and non-commercial use only.
|
# Then pull a model:
|
||||||
Licensed under **[Creative Commons BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/)**.
|
ollama pull qwen2.5:7b
|
||||||
|
|
||||||
---
|
# 2. Clone / download the project and launch
|
||||||
|
cd Mark-XL
|
||||||
## 👤 Connect with the Creator
|
python main.py
|
||||||
|
```
|
||||||
Engineered by a developer building a real-world JARVIS-style assistant.
|
|
||||||
⭐ **Star the repository to support the journey to Mark 100.**
|
That's it. On first run MARK XL:
|
||||||
|
1. Auto-installs base packages (PyQt6, numpy …) and restarts once
|
||||||
| Platform | Link |
|
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)
|
||||||
| YouTube | [@FatihMakes](https://www.youtube.com/@FatihMakes) |
|
4. JARVIS comes online
|
||||||
| Instagram | [@fatihmakes](https://www.instagram.com/fatihmakes) |
|
|
||||||
|
After setup, use the **⚙ CONFIGURE** button in the right panel to change any setting at any time without restarting.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Configuration (`config/api_keys.json`)
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"stt_engine": "whisper",
|
||||||
|
"stt_model": "base",
|
||||||
|
"stt_language": "auto",
|
||||||
|
"llm_url": "http://localhost:11434",
|
||||||
|
"llm_model": "qwen2.5:7b",
|
||||||
|
"tts_engine": "edgetts",
|
||||||
|
"tts_voice": "en-US-GuyNeural",
|
||||||
|
"elevenlabs_api_key": ""
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| Key | Values | Default |
|
||||||
|
|-----|--------|---------|
|
||||||
|
| `stt_engine` | `whisper` / `vosk` | `whisper` |
|
||||||
|
| `stt_model` | `tiny` / `base` / `small` / `medium` / `large-v3` | `base` |
|
||||||
|
| `stt_language` | `auto` or ISO code (`tr`, `en`, `de` …) | `auto` |
|
||||||
|
| `llm_url` | Ollama API base URL | `http://localhost:11434` |
|
||||||
|
| `llm_model` | Any model pulled in Ollama | `qwen2.5:7b` |
|
||||||
|
| `tts_engine` | `edgetts` / `kokoro` / `elevenlabs` | `edgetts` |
|
||||||
|
| `tts_voice` | Voice name / ID depending on engine | `en-US-GuyNeural` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Built-in Tools
|
||||||
|
|
||||||
|
| Tool | Description |
|
||||||
|
|------|-------------|
|
||||||
|
| `open_app` | Opens any application or website |
|
||||||
|
| `web_search` | Web search and compare mode |
|
||||||
|
| `weather_report` | Current weather for any city |
|
||||||
|
| `send_message` | WhatsApp / Telegram messaging |
|
||||||
|
| `reminder` | Timed reminders via Task Scheduler |
|
||||||
|
| `youtube_video` | Play, summarize, trending videos |
|
||||||
|
| `screen_process` | Screen capture + vision model analysis |
|
||||||
|
| `computer_settings` | Volume, brightness, window management, shortcuts |
|
||||||
|
| `browser_control` | Full Playwright browser automation |
|
||||||
|
| `file_controller` | File/folder CRUD, search, disk usage |
|
||||||
|
| `desktop_control` | Wallpaper, organize, clean desktop |
|
||||||
|
| `code_helper` | Write, edit, explain, run code |
|
||||||
|
| `dev_agent` | Build complete multi-file projects |
|
||||||
|
| `agent_task` | Multi-step autonomous task execution |
|
||||||
|
| `computer_control` | Direct mouse/keyboard control |
|
||||||
|
| `game_updater` | Steam / Epic Games install & update |
|
||||||
|
| `flight_finder` | Google Flights search |
|
||||||
|
| `file_processor` | Process images, PDFs, CSV, audio, video |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Keyboard Shortcuts
|
||||||
|
|
||||||
|
| Key | Action |
|
||||||
|
|-----|--------|
|
||||||
|
| `F4` | Mute / unmute microphone |
|
||||||
|
| `F11` | Toggle fullscreen |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## TTS Engine Comparison
|
||||||
|
|
||||||
|
| Engine | Internet | Quality | Cost |
|
||||||
|
|--------|----------|---------|------|
|
||||||
|
| EdgeTTS | Required | Good | Free |
|
||||||
|
| Kokoro | No | Excellent | Free (local model ~100 MB) |
|
||||||
|
| ElevenLabs | Required | Best | Paid API |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT — FatihMakes Industries
|
||||||
+54
-24
@@ -1,24 +1,54 @@
|
|||||||
sounddevice
|
# MARK XL — Python dependencies
|
||||||
google-genai
|
#
|
||||||
google-generativeai
|
# Normal users: just run python main.py
|
||||||
pillow
|
# All packages are installed automatically on first launch.
|
||||||
requests
|
#
|
||||||
beautifulsoup4
|
# Developers / manual setup:
|
||||||
duckduckgo-search
|
# pip install -r requirements.txt
|
||||||
playwright
|
# Platform-specific packages install only on the matching OS.
|
||||||
pyautogui
|
|
||||||
pyperclip
|
# ── Core UI & system ──────────────────────────────────────────────────────
|
||||||
pygetwindow
|
PyQt6
|
||||||
opencv-python
|
psutil
|
||||||
numpy
|
pillow
|
||||||
mss
|
sounddevice
|
||||||
Pillow
|
numpy
|
||||||
psutil
|
soundfile
|
||||||
comtypes
|
requests
|
||||||
pycaw
|
|
||||||
win10toast
|
# ── Web automation & search ───────────────────────────────────────────────
|
||||||
send2trash
|
playwright
|
||||||
youtube-transcript-api
|
beautifulsoup4
|
||||||
pywinauto
|
duckduckgo-search
|
||||||
python-pptx
|
|
||||||
pyqt6
|
# ── OS control (cross-platform) ───────────────────────────────────────────
|
||||||
|
pyautogui
|
||||||
|
pyperclip
|
||||||
|
pygetwindow
|
||||||
|
send2trash
|
||||||
|
mss
|
||||||
|
opencv-python
|
||||||
|
|
||||||
|
# ── OS control (Windows only) ─────────────────────────────────────────────
|
||||||
|
pywinauto ; sys_platform == "win32"
|
||||||
|
comtypes ; sys_platform == "win32"
|
||||||
|
pycaw ; sys_platform == "win32"
|
||||||
|
win10toast; sys_platform == "win32"
|
||||||
|
|
||||||
|
# ── Media & file processing ───────────────────────────────────────────────
|
||||||
|
youtube-transcript-api
|
||||||
|
python-pptx
|
||||||
|
miniaudio
|
||||||
|
|
||||||
|
# ── STT — choose one (auto-installed by main.py based on your config) ─────
|
||||||
|
faster-whisper # Whisper (default, recommended)
|
||||||
|
# vosk # Vosk (alternative — uncomment if preferred)
|
||||||
|
|
||||||
|
# ── TTS — choose one (auto-installed by main.py based on your config) ─────
|
||||||
|
edge-tts # EdgeTTS (default, free, requires internet)
|
||||||
|
# kokoro # Kokoro (fully offline — uncomment if preferred)
|
||||||
|
# elevenlabs # ElevenLabs (cloud API — uncomment if preferred)
|
||||||
|
|
||||||
|
# ── Local LLM ─────────────────────────────────────────────────────────────
|
||||||
|
# Ollama must be installed separately: https://ollama.com
|
||||||
|
# Then pull a model: ollama pull qwen2.5:7b
|
||||||
@@ -23,7 +23,7 @@ from PyQt6.QtGui import (
|
|||||||
QRadialGradient, QShortcut,
|
QRadialGradient, QShortcut,
|
||||||
)
|
)
|
||||||
from PyQt6.QtWidgets import (
|
from PyQt6.QtWidgets import (
|
||||||
QApplication, QFileDialog, QFrame, QHBoxLayout, QLabel, QLineEdit,
|
QApplication, QComboBox, QFileDialog, QFrame, QHBoxLayout, QLabel, QLineEdit,
|
||||||
QMainWindow, QPushButton, QScrollArea, QSizePolicy, QTextEdit,
|
QMainWindow, QPushButton, QScrollArea, QSizePolicy, QTextEdit,
|
||||||
QVBoxLayout, QWidget, QProgressBar,
|
QVBoxLayout, QWidget, QProgressBar,
|
||||||
)
|
)
|
||||||
@@ -856,111 +856,85 @@ class _DropCanvas(QWidget):
|
|||||||
|
|
||||||
|
|
||||||
class SetupOverlay(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)
|
super().__init__(parent)
|
||||||
|
self._mode = mode
|
||||||
|
_init = initial or {}
|
||||||
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True)
|
||||||
self.setStyleSheet(f"""
|
self.setStyleSheet(f"""
|
||||||
SetupOverlay {{
|
SetupOverlay {{
|
||||||
background: rgba(0, 6, 10, 245);
|
background: rgba(0, 6, 10, 248);
|
||||||
border: 1px solid {C.BORDER_B};
|
border: 1px solid {C.BORDER_B};
|
||||||
border-radius: 6px;
|
border-radius: 6px;
|
||||||
}}
|
}}
|
||||||
""")
|
""")
|
||||||
|
|
||||||
detected = {"darwin": "mac", "windows": "windows"}.get(
|
_INPUT = f"""
|
||||||
_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"""
|
|
||||||
QLineEdit {{
|
QLineEdit {{
|
||||||
background: #000d12; color: {C.TEXT};
|
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}; }}
|
QLineEdit:focus {{ border: 1px solid {C.PRI}; }}
|
||||||
""")
|
"""
|
||||||
layout.addWidget(self._key_input)
|
|
||||||
layout.addSpacing(12)
|
|
||||||
|
|
||||||
sep2 = QFrame(); sep2.setFrameShape(QFrame.Shape.HLine)
|
self._sel_stt = _init.get("stt_engine", "whisper")
|
||||||
sep2.setStyleSheet(f"color: {C.BORDER};"); layout.addWidget(sep2)
|
self._sel_tts = _init.get("tts_engine", "edgetts")
|
||||||
layout.addSpacing(4)
|
|
||||||
|
|
||||||
layout.addWidget(_lbl("OPERATING SYSTEM", 8, color=C.TEXT_DIM,
|
layout = QVBoxLayout(self)
|
||||||
align=Qt.AlignmentFlag.AlignLeft))
|
layout.setContentsMargins(22, 16, 22, 16)
|
||||||
det_name = {"windows": "Windows", "mac": "macOS", "linux": "Linux"}[detected]
|
layout.setSpacing(6)
|
||||||
layout.addWidget(_lbl(f"Auto-detected: {det_name}", 8, color=C.ACC2,
|
|
||||||
align=Qt.AlignmentFlag.AlignLeft))
|
|
||||||
|
|
||||||
os_row = QHBoxLayout(); os_row.setSpacing(6)
|
def _lbl(txt, sz=9, bold=False, col=C.PRI, align=Qt.AlignmentFlag.AlignCenter):
|
||||||
self._os_btns: dict[str, QPushButton] = {}
|
w = QLabel(txt); w.setAlignment(align)
|
||||||
for key, label in [("windows","⊞ Windows"),("mac"," macOS"),("linux","🐧 Linux")]:
|
w.setFont(QFont("Courier New", sz,
|
||||||
btn = QPushButton(label)
|
QFont.Weight.Bold if bold else QFont.Weight.Normal))
|
||||||
btn.setFont(QFont("Courier New", 9, QFont.Weight.Bold))
|
w.setStyleSheet(f"color: {col}; background: transparent;")
|
||||||
btn.setFixedHeight(32)
|
return w
|
||||||
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)
|
|
||||||
|
|
||||||
init_btn = QPushButton("▸ INITIALISE SYSTEMS")
|
def _sep():
|
||||||
init_btn.setFont(QFont("Courier New", 10, QFont.Weight.Bold))
|
s = QFrame(); s.setFrameShape(QFrame.Shape.HLine)
|
||||||
init_btn.setFixedHeight(36)
|
s.setStyleSheet(f"color: {C.BORDER}; margin: 2px 0;")
|
||||||
init_btn.setCursor(Qt.CursorShape.PointingHandCursor)
|
return s
|
||||||
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 _sel(self, key: str):
|
def _input(placeholder="", pw=False, fixed_h=28):
|
||||||
self._sel_os = key
|
w = QLineEdit()
|
||||||
pal = {"windows":(C.PRI,"#001a22"),"mac":(C.ACC2,"#1a1400"),"linux":(C.GREEN,"#001a0d")}
|
w.setPlaceholderText(placeholder)
|
||||||
for k, btn in self._os_btns.items():
|
w.setFixedHeight(fixed_h)
|
||||||
if k == key:
|
if pw:
|
||||||
fg, bg = pal[k]
|
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"""
|
btn.setStyleSheet(f"""
|
||||||
QPushButton {{
|
QPushButton {{
|
||||||
background: {fg}; color: {bg};
|
background: {C.PRI}; color: #001a22;
|
||||||
border: none; border-radius: 3px; font-weight: bold;
|
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}; }}
|
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):
|
def _submit(self):
|
||||||
key = self._key_input.text().strip()
|
llm_model = self._llm_model_input.text().strip()
|
||||||
if not key:
|
if not llm_model:
|
||||||
self._key_input.setStyleSheet(
|
self._llm_model_input.setStyleSheet(
|
||||||
self._key_input.styleSheet() +
|
self._llm_model_input.styleSheet() +
|
||||||
f" QLineEdit {{ border: 1px solid {C.RED}; }}"
|
f" QLineEdit {{ border: 1px solid {C.RED}; }}"
|
||||||
)
|
)
|
||||||
return
|
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):
|
class MainWindow(QMainWindow):
|
||||||
@@ -990,7 +1284,7 @@ class MainWindow(QMainWindow):
|
|||||||
|
|
||||||
def __init__(self, face_path: str):
|
def __init__(self, face_path: str):
|
||||||
super().__init__()
|
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.setMinimumSize(_MIN_W, _MIN_H)
|
||||||
self.resize(_DEFAULT_W, _DEFAULT_H)
|
self.resize(_DEFAULT_W, _DEFAULT_H)
|
||||||
|
|
||||||
@@ -1045,6 +1339,7 @@ class MainWindow(QMainWindow):
|
|||||||
self._state_sig.connect(self._apply_state)
|
self._state_sig.connect(self._apply_state)
|
||||||
|
|
||||||
self._overlay: SetupOverlay | None = None
|
self._overlay: SetupOverlay | None = None
|
||||||
|
self._on_reconfigure_cb = None
|
||||||
self._ready = self._check_config()
|
self._ready = self._check_config()
|
||||||
if not self._ready:
|
if not self._ready:
|
||||||
self._show_setup()
|
self._show_setup()
|
||||||
@@ -1063,7 +1358,7 @@ class MainWindow(QMainWindow):
|
|||||||
def resizeEvent(self, event):
|
def resizeEvent(self, event):
|
||||||
super().resizeEvent(event)
|
super().resizeEvent(event)
|
||||||
if self._overlay and self._overlay.isVisible():
|
if self._overlay and self._overlay.isVisible():
|
||||||
ow, oh = 460, 390
|
ow, oh = 520, 580
|
||||||
cw = self.centralWidget()
|
cw = self.centralWidget()
|
||||||
self._overlay.setGeometry(
|
self._overlay.setGeometry(
|
||||||
(cw.width() - ow) // 2,
|
(cw.width() - ow) // 2,
|
||||||
@@ -1135,7 +1430,7 @@ class MainWindow(QMainWindow):
|
|||||||
l.setStyleSheet(f"color: {color}; background: transparent;")
|
l.setStyleSheet(f"color: {color}; background: transparent;")
|
||||||
return l
|
return l
|
||||||
|
|
||||||
lay.addWidget(_badge("MARK XXXIX", C.PRI_DIM))
|
lay.addWidget(_badge("MARK XL", C.PRI_DIM))
|
||||||
lay.addStretch()
|
lay.addStretch()
|
||||||
|
|
||||||
mid = QVBoxLayout(); mid.setSpacing(1)
|
mid = QVBoxLayout(); mid.setSpacing(1)
|
||||||
@@ -1227,7 +1522,7 @@ class MainWindow(QMainWindow):
|
|||||||
for txt, col in [
|
for txt, col in [
|
||||||
("AI CORE\nACTIVE", C.GREEN),
|
("AI CORE\nACTIVE", C.GREEN),
|
||||||
("SEC\nCLEARED", C.PRI),
|
("SEC\nCLEARED", C.PRI),
|
||||||
("PROTOCOL\nXXXVIII", C.TEXT_DIM),
|
("PROTOCOL\nXL", C.TEXT_DIM),
|
||||||
]:
|
]:
|
||||||
lbl = QLabel(txt)
|
lbl = QLabel(txt)
|
||||||
lbl.setFont(QFont("Courier New", 7, QFont.Weight.Bold))
|
lbl.setFont(QFont("Courier New", 7, QFont.Weight.Bold))
|
||||||
@@ -1303,6 +1598,22 @@ class MainWindow(QMainWindow):
|
|||||||
fs_btn.clicked.connect(self._toggle_fullscreen)
|
fs_btn.clicked.connect(self._toggle_fullscreen)
|
||||||
lay.addWidget(fs_btn)
|
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
|
return w
|
||||||
|
|
||||||
def _build_input_row(self) -> QHBoxLayout:
|
def _build_input_row(self) -> QHBoxLayout:
|
||||||
@@ -1349,7 +1660,7 @@ class MainWindow(QMainWindow):
|
|||||||
|
|
||||||
lay.addWidget(_fl("[F4] Mute · [F11] Fullscreen"))
|
lay.addWidget(_fl("[F4] Mute · [F11] Fullscreen"))
|
||||||
lay.addStretch()
|
lay.addStretch()
|
||||||
lay.addWidget(_fl("FatihMakes Industries · MARK XXXIX · CLASSIFIED"))
|
lay.addWidget(_fl("FatihMakes Industries · MARK XL · CLASSIFIED"))
|
||||||
lay.addStretch()
|
lay.addStretch()
|
||||||
lay.addWidget(_fl("© FATIHMAKES", C.PRI_DIM))
|
lay.addWidget(_fl("© FATIHMAKES", C.PRI_DIM))
|
||||||
return w
|
return w
|
||||||
@@ -1417,14 +1728,18 @@ class MainWindow(QMainWindow):
|
|||||||
if not API_FILE.exists(): return False
|
if not API_FILE.exists(): return False
|
||||||
try:
|
try:
|
||||||
d = json.loads(API_FILE.read_text(encoding="utf-8"))
|
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:
|
except Exception:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def _show_setup(self):
|
def _show_setup(self):
|
||||||
ov = SetupOverlay(self.centralWidget())
|
ov = SetupOverlay(self.centralWidget())
|
||||||
cw = self.centralWidget()
|
cw = self.centralWidget()
|
||||||
ow, oh = 460, 390
|
ow, oh = 520, 580
|
||||||
ov.setGeometry(
|
ov.setGeometry(
|
||||||
(cw.width() - ow) // 2,
|
(cw.width() - ow) // 2,
|
||||||
(cw.height() - oh) // 2,
|
(cw.height() - oh) // 2,
|
||||||
@@ -1434,10 +1749,14 @@ class MainWindow(QMainWindow):
|
|||||||
ov.show()
|
ov.show()
|
||||||
self._overlay = ov
|
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)
|
os.makedirs(CONFIG_DIR, exist_ok=True)
|
||||||
API_FILE.write_text(
|
API_FILE.write_text(
|
||||||
json.dumps({"gemini_api_key": key, "os_system": os_name}, indent=4),
|
json.dumps(cfg, indent=4),
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
self._ready = True
|
self._ready = True
|
||||||
@@ -1445,7 +1764,50 @@ class MainWindow(QMainWindow):
|
|||||||
self._overlay.hide()
|
self._overlay.hide()
|
||||||
self._overlay = None
|
self._overlay = None
|
||||||
self._apply_state("LISTENING")
|
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:
|
class _RootShim:
|
||||||
def __init__(self, app: QApplication):
|
def __init__(self, app: QApplication):
|
||||||
@@ -1485,6 +1847,14 @@ class JarvisUI:
|
|||||||
def on_text_command(self, cb):
|
def on_text_command(self, cb):
|
||||||
self._win.on_text_command = 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):
|
def set_state(self, state: str):
|
||||||
self._win._state_sig.emit(state)
|
self._win._state_sig.emit(state)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user