Add files via upload
This commit is contained in:
1 parent
d3e8504706
commit
502309ad24
25 files changed
+2675
-1584
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(
|
||||||
|
|||||||
+97
-267
@@ -1,18 +1,16 @@
|
|||||||
|
"""
|
||||||
|
MARK XL — Screen / Camera Processor
|
||||||
|
Replaces Gemini Live vision session with a direct Ollama vision-model call.
|
||||||
|
The analysis text is returned (and optionally spoken via the `speak` callback).
|
||||||
|
"""
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import base64
|
import base64
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
import re
|
|
||||||
import sys
|
import sys
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Optional
|
from typing import Optional, Callable
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
import sounddevice as sd
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import cv2
|
import cv2
|
||||||
@@ -33,8 +31,10 @@ try:
|
|||||||
except ImportError:
|
except ImportError:
|
||||||
_PIL = False
|
_PIL = False
|
||||||
|
|
||||||
from google import genai
|
import platform
|
||||||
from google.genai import types as gtypes
|
|
||||||
|
import requests
|
||||||
|
|
||||||
|
|
||||||
def _base_dir() -> Path:
|
def _base_dir() -> Path:
|
||||||
if getattr(sys, "frozen", False):
|
if getattr(sys, "frozen", False):
|
||||||
@@ -45,6 +45,10 @@ def _base_dir() -> Path:
|
|||||||
_BASE = _base_dir()
|
_BASE = _base_dir()
|
||||||
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
||||||
|
|
||||||
|
_IMG_MAX_W = 640
|
||||||
|
_IMG_MAX_H = 360
|
||||||
|
_JPEG_Q = 60
|
||||||
|
|
||||||
|
|
||||||
def _load_config() -> dict:
|
def _load_config() -> dict:
|
||||||
try:
|
try:
|
||||||
@@ -59,42 +63,23 @@ def _save_config_key(key: str, value) -> None:
|
|||||||
cfg[key] = value
|
cfg[key] = value
|
||||||
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
||||||
|
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
|
||||||
key = _load_config().get("gemini_api_key", "")
|
|
||||||
if not key:
|
|
||||||
raise RuntimeError("gemini_api_key not found in config.")
|
|
||||||
return key
|
|
||||||
|
|
||||||
|
|
||||||
def _get_os() -> str:
|
def _get_os() -> str:
|
||||||
return _load_config().get("os_system", "windows").lower()
|
s = platform.system().lower()
|
||||||
|
if s == "darwin": return "mac"
|
||||||
|
if s == "windows": return "windows"
|
||||||
|
return "linux"
|
||||||
|
|
||||||
_LIVE_MODEL = "models/gemini-2.5-flash-native-audio-preview-12-2025"
|
|
||||||
_CHANNELS = 1
|
|
||||||
_RECEIVE_SAMPLE_RATE = 24_000
|
|
||||||
_CHUNK_SIZE = 1_024
|
|
||||||
|
|
||||||
_IMG_MAX_W = 640
|
|
||||||
_IMG_MAX_H = 360
|
|
||||||
_JPEG_Q = 60
|
|
||||||
|
|
||||||
_SYSTEM_PROMPT = (
|
|
||||||
"You are JARVIS, an advanced AI assistant. "
|
|
||||||
"Analyze the provided image with precision and intelligence. "
|
|
||||||
"Be concise and direct — maximum two sentences unless the user's question "
|
|
||||||
"requires more detail. "
|
|
||||||
"Address the user respectfully. "
|
|
||||||
"Always call the appropriate tool; never simulate results."
|
|
||||||
)
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Image capture helpers (unchanged from original)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
||||||
if not _PIL:
|
if not _PIL:
|
||||||
return img_bytes, f"image/{source_format.lower()}"
|
return img_bytes, f"image/{source_format.lower()}"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
||||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||||
@@ -102,25 +87,22 @@ def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]
|
|||||||
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
||||||
return buf.getvalue(), "image/jpeg"
|
return buf.getvalue(), "image/jpeg"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
||||||
return img_bytes, f"image/{source_format.lower()}"
|
return img_bytes, f"image/{source_format.lower()}"
|
||||||
|
|
||||||
def _capture_screen() -> tuple[bytes, str]:
|
|
||||||
|
|
||||||
|
def _capture_screen() -> tuple[bytes, str]:
|
||||||
if not _MSS:
|
if not _MSS:
|
||||||
raise RuntimeError("mss is not installed. Run: pip install mss")
|
raise RuntimeError("mss is not installed. Run: pip install mss")
|
||||||
|
|
||||||
with mss.mss() as sct:
|
with mss.mss() as sct:
|
||||||
monitors = sct.monitors # [0] = all combined, [1..n] = real screens
|
monitors = sct.monitors
|
||||||
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
||||||
shot = sct.grab(target)
|
shot = sct.grab(target)
|
||||||
png = mss.tools.to_png(shot.rgb, shot.size)
|
png = mss.tools.to_png(shot.rgb, shot.size)
|
||||||
|
|
||||||
return _compress(png, "PNG")
|
return _compress(png, "PNG")
|
||||||
|
|
||||||
|
|
||||||
def _cv2_backend() -> int:
|
def _cv2_backend() -> int:
|
||||||
"""Return the best OpenCV camera backend for the current OS."""
|
|
||||||
if not _CV2:
|
if not _CV2:
|
||||||
return 0
|
return 0
|
||||||
os_name = _get_os()
|
os_name = _get_os()
|
||||||
@@ -132,13 +114,12 @@ def _cv2_backend() -> int:
|
|||||||
|
|
||||||
|
|
||||||
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
||||||
|
|
||||||
if not _CV2:
|
if not _CV2:
|
||||||
return False
|
return False
|
||||||
|
import numpy as np
|
||||||
cap = cv2.VideoCapture(index, backend)
|
cap = cv2.VideoCapture(index, backend)
|
||||||
if not cap.isOpened():
|
if not cap.isOpened():
|
||||||
cap.release()
|
cap.release(); return False
|
||||||
return False
|
|
||||||
for _ in range(warmup):
|
for _ in range(warmup):
|
||||||
cap.read()
|
cap.read()
|
||||||
ret, frame = cap.read()
|
ret, frame = cap.read()
|
||||||
@@ -149,17 +130,15 @@ def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def _detect_camera_index() -> int:
|
def _detect_camera_index() -> int:
|
||||||
|
|
||||||
backend = _cv2_backend()
|
backend = _cv2_backend()
|
||||||
print("[Vision] 🔍 Auto-detecting camera...")
|
print("[Vision] 🔍 Auto-detecting camera…")
|
||||||
for idx in range(6):
|
for idx in range(6):
|
||||||
if _probe_camera(idx, backend):
|
if _probe_camera(idx, backend):
|
||||||
print(f"[Vision] ✅ Camera found at index {idx}")
|
print(f"[Vision] ✅ Camera found at index {idx}")
|
||||||
_save_config_key("camera_index", idx)
|
_save_config_key("camera_index", idx)
|
||||||
return idx
|
return idx
|
||||||
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
||||||
|
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
||||||
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
|
||||||
_save_config_key("camera_index", 0)
|
_save_config_key("camera_index", 0)
|
||||||
return 0
|
return 0
|
||||||
|
|
||||||
@@ -174,23 +153,18 @@ def _get_camera_index() -> int:
|
|||||||
def _capture_camera() -> tuple[bytes, str]:
|
def _capture_camera() -> tuple[bytes, str]:
|
||||||
if not _CV2:
|
if not _CV2:
|
||||||
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
||||||
|
import numpy as np
|
||||||
index = _get_camera_index()
|
index = _get_camera_index()
|
||||||
backend = _cv2_backend()
|
backend = _cv2_backend()
|
||||||
cap = cv2.VideoCapture(index, backend)
|
cap = cv2.VideoCapture(index, backend)
|
||||||
|
|
||||||
if not cap.isOpened():
|
if not cap.isOpened():
|
||||||
raise RuntimeError(f"Camera index {index} could not be opened.")
|
raise RuntimeError(f"Camera index {index} could not be opened.")
|
||||||
|
|
||||||
for _ in range(10):
|
for _ in range(10):
|
||||||
cap.read()
|
cap.read()
|
||||||
|
|
||||||
ret, frame = cap.read()
|
ret, frame = cap.read()
|
||||||
cap.release()
|
cap.release()
|
||||||
|
|
||||||
if not ret or frame is None:
|
if not ret or frame is None:
|
||||||
raise RuntimeError("Camera returned no frame.")
|
raise RuntimeError("Camera returned no frame.")
|
||||||
|
|
||||||
if _PIL:
|
if _PIL:
|
||||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||||
img = PIL.Image.fromarray(rgb)
|
img = PIL.Image.fromarray(rgb)
|
||||||
@@ -198,245 +172,101 @@ def _capture_camera() -> tuple[bytes, str]:
|
|||||||
buf = io.BytesIO()
|
buf = io.BytesIO()
|
||||||
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
||||||
return buf.getvalue(), "image/jpeg"
|
return buf.getvalue(), "image/jpeg"
|
||||||
|
|
||||||
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
||||||
return buf.tobytes(), "image/jpeg"
|
return buf.tobytes(), "image/jpeg"
|
||||||
|
|
||||||
class _VisionSession:
|
|
||||||
def __init__(self):
|
|
||||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
|
||||||
self._thread: Optional[threading.Thread] = None
|
|
||||||
self._session = None
|
|
||||||
self._out_queue: Optional[asyncio.Queue] = None
|
|
||||||
self._audio_in: Optional[asyncio.Queue] = None
|
|
||||||
self._ready_evt: threading.Event = threading.Event()
|
|
||||||
self._player = None
|
|
||||||
self._lock: threading.Lock = threading.Lock()
|
|
||||||
|
|
||||||
def start(self, player=None, timeout: float = 25.0) -> None:
|
# ---------------------------------------------------------------------------
|
||||||
with self._lock:
|
# Vision analysis via Ollama
|
||||||
if self._thread and self._thread.is_alive():
|
# ---------------------------------------------------------------------------
|
||||||
if player is not None:
|
|
||||||
self._player = player
|
|
||||||
return
|
|
||||||
self._player = player
|
|
||||||
self._thread = threading.Thread(
|
|
||||||
target=self._run_event_loop,
|
|
||||||
daemon=True,
|
|
||||||
name="VisionSessionThread",
|
|
||||||
)
|
|
||||||
self._thread.start()
|
|
||||||
|
|
||||||
if not self._ready_evt.wait(timeout=timeout):
|
_SYSTEM_PROMPT = (
|
||||||
raise RuntimeError(f"Vision session did not connect within {timeout}s.")
|
"You are JARVIS, an advanced AI assistant. "
|
||||||
print("[Vision] ✅ Session ready")
|
"Analyze the provided image with precision and intelligence. "
|
||||||
|
"Be concise and direct — maximum two sentences unless the user's question "
|
||||||
def analyze(self, image_bytes: bytes, mime_type: str, user_text: str) -> None:
|
"requires more detail. "
|
||||||
if not self._loop or not self._out_queue:
|
"Address the user respectfully."
|
||||||
print("[Vision] ⚠️ Session not started — dropping request")
|
)
|
||||||
return
|
|
||||||
asyncio.run_coroutine_threadsafe(
|
|
||||||
self._out_queue.put((image_bytes, mime_type, user_text)),
|
|
||||||
self._loop,
|
|
||||||
)
|
|
||||||
|
|
||||||
def is_ready(self) -> bool:
|
|
||||||
return self._session is not None
|
|
||||||
|
|
||||||
def _run_event_loop(self) -> None:
|
|
||||||
self._loop = asyncio.new_event_loop()
|
|
||||||
asyncio.set_event_loop(self._loop)
|
|
||||||
self._loop.run_until_complete(self._session_loop())
|
|
||||||
|
|
||||||
async def _session_loop(self) -> None:
|
|
||||||
self._out_queue = asyncio.Queue(maxsize=30)
|
|
||||||
self._audio_in = asyncio.Queue()
|
|
||||||
|
|
||||||
client = genai.Client(
|
|
||||||
api_key=_get_api_key(),
|
|
||||||
http_options={"api_version": "v1beta"},
|
|
||||||
)
|
|
||||||
config = gtypes.LiveConnectConfig(
|
|
||||||
response_modalities=["AUDIO"],
|
|
||||||
output_audio_transcription={},
|
|
||||||
system_instruction=_SYSTEM_PROMPT,
|
|
||||||
speech_config=gtypes.SpeechConfig(
|
|
||||||
voice_config=gtypes.VoiceConfig(
|
|
||||||
prebuilt_voice_config=gtypes.PrebuiltVoiceConfig(
|
|
||||||
voice_name="Charon"
|
|
||||||
)
|
|
||||||
)
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
backoff = 2.0
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
print("[Vision] 🔌 Connecting...")
|
|
||||||
async with client.aio.live.connect(
|
|
||||||
model=_LIVE_MODEL, config=config
|
|
||||||
) as session:
|
|
||||||
self._session = session
|
|
||||||
self._ready_evt.set()
|
|
||||||
backoff = 2.0
|
|
||||||
print("[Vision] ✅ Connected")
|
|
||||||
|
|
||||||
async with asyncio.TaskGroup() as tg:
|
|
||||||
tg.create_task(self._send_loop())
|
|
||||||
tg.create_task(self._recv_loop())
|
|
||||||
tg.create_task(self._play_loop())
|
|
||||||
|
|
||||||
except* Exception as eg:
|
|
||||||
for exc in eg.exceptions:
|
|
||||||
print(f"[Vision] ⚠️ Session error: {exc}")
|
|
||||||
finally:
|
|
||||||
self._session = None
|
|
||||||
self._ready_evt.clear()
|
|
||||||
|
|
||||||
print(f"[Vision] 🔄 Reconnecting in {backoff:.0f}s...")
|
|
||||||
await asyncio.sleep(backoff)
|
|
||||||
backoff = min(backoff * 1.5, 30.0)
|
|
||||||
self._ready_evt.set()
|
|
||||||
|
|
||||||
async def _send_loop(self) -> None:
|
|
||||||
while True:
|
|
||||||
image_bytes, mime_type, user_text = await self._out_queue.get()
|
|
||||||
if not self._session:
|
|
||||||
print("[Vision] ⚠️ No session — dropping image")
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
b64 = base64.b64encode(image_bytes).decode("ascii")
|
|
||||||
await self._session.send_client_content(
|
|
||||||
turns={
|
|
||||||
"parts": [
|
|
||||||
{"inline_data": {"mime_type": mime_type, "data": b64}},
|
|
||||||
{"text": user_text},
|
|
||||||
]
|
|
||||||
},
|
|
||||||
turn_complete=True,
|
|
||||||
)
|
|
||||||
print(f"[Vision] 📤 Sent {len(image_bytes):,} bytes — '{user_text[:60]}'")
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[Vision] ⚠️ Send error: {e}")
|
|
||||||
|
|
||||||
async def _recv_loop(self) -> None:
|
|
||||||
transcript: list[str] = []
|
|
||||||
try:
|
|
||||||
async for response in self._session.receive():
|
|
||||||
if response.data:
|
|
||||||
await self._audio_in.put(response.data)
|
|
||||||
|
|
||||||
sc = response.server_content
|
|
||||||
if not sc:
|
|
||||||
continue
|
|
||||||
|
|
||||||
if sc.output_transcription and sc.output_transcription.text:
|
|
||||||
chunk = sc.output_transcription.text.strip()
|
|
||||||
if chunk:
|
|
||||||
transcript.append(chunk)
|
|
||||||
|
|
||||||
if sc.turn_complete:
|
|
||||||
if transcript and self._player:
|
|
||||||
full = re.sub(r"\s+", " ", " ".join(transcript)).strip()
|
|
||||||
if full:
|
|
||||||
self._player.write_log(f"Jarvis: {full}")
|
|
||||||
print(f"[Vision] 💬 {full}")
|
|
||||||
transcript = []
|
|
||||||
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[Vision] ⚠️ Recv error: {e}")
|
|
||||||
raise
|
|
||||||
|
|
||||||
async def _play_loop(self) -> None:
|
|
||||||
stream = sd.RawOutputStream(
|
|
||||||
samplerate=_RECEIVE_SAMPLE_RATE,
|
|
||||||
channels=_CHANNELS,
|
|
||||||
dtype="int16",
|
|
||||||
blocksize=_CHUNK_SIZE,
|
|
||||||
)
|
|
||||||
stream.start()
|
|
||||||
try:
|
|
||||||
while True:
|
|
||||||
chunk = await self._audio_in.get()
|
|
||||||
await asyncio.to_thread(stream.write, chunk)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[Vision] ❌ Play error: {e}")
|
|
||||||
raise
|
|
||||||
finally:
|
|
||||||
stream.stop()
|
|
||||||
stream.close()
|
|
||||||
|
|
||||||
_session = _VisionSession()
|
|
||||||
_session_lock = threading.Lock()
|
|
||||||
_session_up = False
|
|
||||||
|
|
||||||
|
|
||||||
def _ensure_session(player=None) -> None:
|
def _call_vision(image_bytes: bytes, mime: str, user_text: str) -> str:
|
||||||
global _session_up
|
cfg = _load_config()
|
||||||
with _session_lock:
|
url = cfg.get("llm_url", "http://localhost:11434").rstrip("/")
|
||||||
if not _session_up:
|
vision_model = cfg.get("vision_model") or cfg.get("llm_model", "llava")
|
||||||
_session.start(player=player)
|
|
||||||
_session_up = True
|
|
||||||
elif player is not None:
|
|
||||||
_session._player = player
|
|
||||||
|
|
||||||
|
b64 = base64.b64encode(image_bytes).decode("ascii")
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"model": vision_model,
|
||||||
|
"stream": False,
|
||||||
|
"messages": [
|
||||||
|
{"role": "system", "content": _SYSTEM_PROMPT},
|
||||||
|
{
|
||||||
|
"role": "user",
|
||||||
|
"content": user_text,
|
||||||
|
"images": [b64],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
resp = requests.post(f"{url}/api/chat", json=payload, timeout=60)
|
||||||
|
resp.raise_for_status()
|
||||||
|
return (resp.json().get("message", {}).get("content") or "").strip()
|
||||||
|
except requests.exceptions.ConnectionError:
|
||||||
|
return "Cannot connect to Ollama. Make sure Ollama is running."
|
||||||
|
except Exception as e:
|
||||||
|
return f"Vision analysis failed: {e}"
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Public entry point
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def screen_process(
|
def screen_process(
|
||||||
parameters: dict,
|
parameters: dict,
|
||||||
response=None,
|
response=None,
|
||||||
player=None,
|
player=None,
|
||||||
session_memory=None,
|
session_memory=None,
|
||||||
) -> bool:
|
speak: Optional[Callable[[str], None]] = None,
|
||||||
|
) -> str:
|
||||||
|
"""
|
||||||
|
Capture screen or camera, analyse with Ollama vision model.
|
||||||
|
|
||||||
|
Returns the analysis text (str).
|
||||||
|
Optionally speaks via `speak` callback and logs to `player`.
|
||||||
|
"""
|
||||||
params = parameters or {}
|
params = parameters or {}
|
||||||
user_text = (params.get("text") or params.get("user_text") or "").strip()
|
user_text = (params.get("text") or params.get("user_text") or "").strip()
|
||||||
angle = params.get("angle", "screen").lower().strip()
|
angle = params.get("angle", "screen").lower().strip()
|
||||||
|
|
||||||
if not user_text:
|
if not user_text:
|
||||||
print("[Vision] ⚠️ No question provided — aborting")
|
user_text = "What do you see? Describe briefly."
|
||||||
return False
|
|
||||||
|
|
||||||
print(f"[Vision] ▶ angle={angle!r} question='{user_text[:80]}'")
|
if player:
|
||||||
|
player.write_log(f"SYS: Vision [{angle}] — {user_text[:60]}")
|
||||||
try:
|
|
||||||
_ensure_session(player=player)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[Vision] ❌ Could not start session: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
# Capture
|
||||||
try:
|
try:
|
||||||
if angle == "camera":
|
if angle == "camera":
|
||||||
image_bytes, mime_type = _capture_camera()
|
image_bytes, mime = _capture_camera()
|
||||||
print(f"[Vision] 📷 Camera: {len(image_bytes):,} bytes")
|
print(f"[Vision] 📷 Camera: {len(image_bytes):,} bytes")
|
||||||
else:
|
else:
|
||||||
image_bytes, mime_type = _capture_screen()
|
image_bytes, mime = _capture_screen()
|
||||||
print(f"[Vision] 🖥️ Screen: {len(image_bytes):,} bytes")
|
print(f"[Vision] 🖥️ Screen: {len(image_bytes):,} bytes")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[Vision] ❌ Capture error: {e}")
|
msg = f"Capture error: {e}"
|
||||||
return False
|
print(f"[Vision] ❌ {msg}")
|
||||||
|
if player: player.write_log(f"ERR: {msg}")
|
||||||
|
return msg
|
||||||
|
|
||||||
_session.analyze(image_bytes, mime_type, user_text)
|
# Analyse
|
||||||
return True
|
analysis = _call_vision(image_bytes, mime, user_text)
|
||||||
|
print(f"[Vision] 💬 {analysis[:120]}")
|
||||||
|
|
||||||
|
if player:
|
||||||
|
player.write_log(f"Jarvis: {analysis}")
|
||||||
|
|
||||||
def warmup_session(player=None) -> None:
|
if speak and analysis:
|
||||||
try:
|
speak(analysis)
|
||||||
_ensure_session(player=player)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[Vision] ⚠️ Warmup failed: {e}")
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
return analysis
|
||||||
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.")
|
|
||||||
+32
-56
@@ -1,42 +1,17 @@
|
|||||||
#web_search.py
|
# web_search.py
|
||||||
|
# Gemini grounded-search replaced with DuckDuckGo + Ollama LLM summarization.
|
||||||
import json
|
import json
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
def _get_base_dir() -> Path:
|
def _get_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_DIR = _get_base_dir()
|
BASE_DIR = _get_base_dir()
|
||||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
|
||||||
|
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)["gemini_api_key"]
|
|
||||||
|
|
||||||
|
|
||||||
def _gemini_search(query: str) -> str:
|
|
||||||
from google import genai
|
|
||||||
|
|
||||||
client = genai.Client(api_key=_get_api_key())
|
|
||||||
response = client.models.generate_content(
|
|
||||||
model="gemini-2.5-flash",
|
|
||||||
contents=query,
|
|
||||||
config={"tools": [{"google_search": {}}]},
|
|
||||||
)
|
|
||||||
|
|
||||||
text = ""
|
|
||||||
for part in response.candidates[0].content.parts:
|
|
||||||
if hasattr(part, "text") and part.text:
|
|
||||||
text += part.text
|
|
||||||
|
|
||||||
text = text.strip()
|
|
||||||
if not text:
|
|
||||||
raise ValueError("Gemini returned an empty response.")
|
|
||||||
return text
|
|
||||||
|
|
||||||
|
|
||||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||||
@@ -59,7 +34,6 @@ def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
|||||||
def _format_ddg(query: str, results: list[dict]) -> str:
|
def _format_ddg(query: str, results: list[dict]) -> str:
|
||||||
if not results:
|
if not results:
|
||||||
return f"No results found for: {query}"
|
return f"No results found for: {query}"
|
||||||
|
|
||||||
lines = [f"Search results for: {query}\n"]
|
lines = [f"Search results for: {query}\n"]
|
||||||
for i, r in enumerate(results, 1):
|
for i, r in enumerate(results, 1):
|
||||||
if r.get("title"): lines.append(f"{i}. {r['title']}")
|
if r.get("title"): lines.append(f"{i}. {r['title']}")
|
||||||
@@ -68,17 +42,25 @@ def _format_ddg(query: str, results: list[dict]) -> str:
|
|||||||
lines.append("")
|
lines.append("")
|
||||||
return "\n".join(lines).strip()
|
return "\n".join(lines).strip()
|
||||||
|
|
||||||
def _compare(items: list[str], aspect: str) -> str:
|
|
||||||
query = (
|
|
||||||
f"Compare {', '.join(items)} in terms of {aspect}. "
|
|
||||||
"Give specific facts and data."
|
|
||||||
)
|
|
||||||
try:
|
|
||||||
return _gemini_search(query)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"[WebSearch] ⚠️ Gemini compare failed: {e} — falling back to DDG")
|
|
||||||
|
|
||||||
# DDG fallback: fetch results per item and merge
|
def _llm_summarize(query: str, raw_results: str) -> str:
|
||||||
|
try:
|
||||||
|
from core.llm_client import call_llm_text
|
||||||
|
system = (
|
||||||
|
"You are JARVIS. Summarize web search results clearly and concisely. "
|
||||||
|
"Answer the user's query directly. Be factual. Address user as 'sir'."
|
||||||
|
)
|
||||||
|
prompt = (
|
||||||
|
f"User question: {query}\n\n"
|
||||||
|
f"Web search results:\n{raw_results[:4000]}\n\n"
|
||||||
|
"Answer the question based on these results:"
|
||||||
|
)
|
||||||
|
return call_llm_text(prompt, system=system)
|
||||||
|
except Exception:
|
||||||
|
return raw_results
|
||||||
|
|
||||||
|
|
||||||
|
def _compare(items: list[str], aspect: str) -> str:
|
||||||
all_results: dict[str, list] = {}
|
all_results: dict[str, list] = {}
|
||||||
for item in items:
|
for item in items:
|
||||||
try:
|
try:
|
||||||
@@ -92,7 +74,9 @@ def _compare(items: list[str], aspect: str) -> str:
|
|||||||
for r in all_results.get(item, [])[:2]:
|
for r in all_results.get(item, [])[:2]:
|
||||||
if r.get("snippet"):
|
if r.get("snippet"):
|
||||||
lines.append(f" • {r['snippet']}")
|
lines.append(f" • {r['snippet']}")
|
||||||
return "\n".join(lines)
|
raw = "\n".join(lines)
|
||||||
|
return _llm_summarize(f"Compare {', '.join(items)} regarding {aspect}", raw)
|
||||||
|
|
||||||
|
|
||||||
def web_search(
|
def web_search(
|
||||||
parameters: dict,
|
parameters: dict,
|
||||||
@@ -120,22 +104,14 @@ def web_search(
|
|||||||
try:
|
try:
|
||||||
if mode == "compare" and items:
|
if mode == "compare" and items:
|
||||||
print(f"[WebSearch] 📊 Comparing: {items}")
|
print(f"[WebSearch] 📊 Comparing: {items}")
|
||||||
result = _compare(items, aspect)
|
return _compare(items, aspect)
|
||||||
print("[WebSearch] ✅ Compare done.")
|
|
||||||
return result
|
|
||||||
|
|
||||||
print("[WebSearch] 🌐 Trying Gemini...")
|
results = _ddg_search(query)
|
||||||
try:
|
raw = _format_ddg(query, results)
|
||||||
result = _gemini_search(query)
|
print(f"[WebSearch] ✅ DDG: {len(results)} result(s).")
|
||||||
print("[WebSearch] ✅ Gemini OK.")
|
# Let Ollama summarise the results for a cleaner spoken response
|
||||||
return result
|
return _llm_summarize(query, raw)
|
||||||
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:
|
except Exception as e:
|
||||||
print(f"[WebSearch] ❌ All backends failed: {e}")
|
print(f"[WebSearch] ❌ Failed: {e}")
|
||||||
return f"Search failed, sir: {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:
|
||||||
|
|||||||
+30
-78
@@ -1,8 +1,14 @@
|
|||||||
|
"""
|
||||||
|
MARK XL — Error Handler
|
||||||
|
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||||
|
"""
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
|
||||||
from enum import Enum
|
from enum import Enum
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.llm_client import call_llm_text
|
||||||
|
|
||||||
|
|
||||||
def get_base_dir() -> Path:
|
def get_base_dir() -> Path:
|
||||||
@@ -11,33 +17,26 @@ def get_base_dir() -> Path:
|
|||||||
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"
|
|
||||||
|
|
||||||
|
|
||||||
class ErrorDecision(Enum):
|
class ErrorDecision(Enum):
|
||||||
RETRY = "retry"
|
RETRY = "retry"
|
||||||
SKIP = "skip"
|
SKIP = "skip"
|
||||||
REPLAN = "replan"
|
REPLAN = "replan"
|
||||||
ABORT = "abort"
|
ABORT = "abort"
|
||||||
|
|
||||||
|
|
||||||
ERROR_ANALYST_PROMPT = """You are the error recovery module of MARK XXV AI assistant.
|
ERROR_ANALYST_PROMPT = """You are the error recovery module of MARK XL AI assistant.
|
||||||
|
|
||||||
A task step has failed. Analyze the error and decide what to do.
|
A task step has failed. Analyze the error and decide what to do.
|
||||||
|
|
||||||
DECISIONS:
|
DECISIONS:
|
||||||
- retry : Transient error (network timeout, temporary file lock, race condition).
|
- retry : Transient error (network timeout, temporary file lock, race condition).
|
||||||
The same step can succeed if tried again.
|
|
||||||
- skip : This step is not critical and the task can succeed without it.
|
- skip : This step is not critical and the task can succeed without it.
|
||||||
- replan : The approach was wrong. A different tool or method should be tried.
|
- replan : The approach was wrong. A different tool or method should be tried.
|
||||||
- abort : The task is fundamentally impossible or unsafe to continue.
|
- abort : The task is fundamentally impossible or unsafe to continue.
|
||||||
|
|
||||||
Also provide:
|
|
||||||
- A brief explanation of WHY it failed (1 sentence)
|
|
||||||
- A fix suggestion if decision is replan (what to try instead)
|
|
||||||
- Max retries: how many times to retry if decision is retry (1 or 2)
|
|
||||||
|
|
||||||
Return ONLY valid JSON:
|
Return ONLY valid JSON:
|
||||||
{
|
{
|
||||||
"decision": "retry|skip|replan|abort",
|
"decision": "retry|skip|replan|abort",
|
||||||
@@ -49,53 +48,22 @@ Return ONLY valid JSON:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)["gemini_api_key"]
|
|
||||||
|
|
||||||
|
|
||||||
def analyze_error(
|
def analyze_error(
|
||||||
step: dict,
|
step: dict,
|
||||||
error: str,
|
error: str,
|
||||||
attempt: int = 1,
|
attempt: int = 1,
|
||||||
max_attempts: int = 2
|
max_attempts: int = 2,
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""
|
|
||||||
Analyzes a failed step and returns a recovery decision.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
step : The step dict that failed
|
|
||||||
error : Error message/traceback
|
|
||||||
attempt : Current attempt number
|
|
||||||
max_attempts : How many times we've already tried
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
{
|
|
||||||
"decision": ErrorDecision,
|
|
||||||
"reason": str,
|
|
||||||
"fix_suggestion": str,
|
|
||||||
"max_retries": int,
|
|
||||||
"user_message": str
|
|
||||||
}
|
|
||||||
"""
|
|
||||||
import google.generativeai as genai
|
|
||||||
|
|
||||||
if attempt >= max_attempts:
|
if attempt >= max_attempts:
|
||||||
print(f"[ErrorHandler] ⚠️ Max attempts reached for step {step.get('step')} — forcing replan")
|
print(f"[ErrorHandler] ⚠️ Max attempts for step {step.get('step')} — forcing replan")
|
||||||
return {
|
return {
|
||||||
"decision": ErrorDecision.REPLAN,
|
"decision": ErrorDecision.REPLAN,
|
||||||
"reason": f"Failed {attempt} times: {error[:100]}",
|
"reason": f"Failed {attempt} times: {error[:100]}",
|
||||||
"fix_suggestion": "Try a completely different approach or tool",
|
"fix_suggestion": "Try a completely different approach or tool",
|
||||||
"max_retries": 0,
|
"max_retries": 0,
|
||||||
"user_message": "Trying a different approach, sir."
|
"user_message": "Trying a different approach, sir.",
|
||||||
}
|
}
|
||||||
|
|
||||||
genai.configure(api_key=_get_api_key())
|
|
||||||
model = genai.GenerativeModel(
|
|
||||||
model_name="gemini-2.5-flash-lite",
|
|
||||||
system_instruction=ERROR_ANALYST_PROMPT
|
|
||||||
)
|
|
||||||
|
|
||||||
prompt = f"""Failed step:
|
prompt = f"""Failed step:
|
||||||
Tool: {step.get('tool')}
|
Tool: {step.get('tool')}
|
||||||
Description: {step.get('description')}
|
Description: {step.get('description')}
|
||||||
@@ -108,11 +76,10 @@ Error:
|
|||||||
Attempt number: {attempt}"""
|
Attempt number: {attempt}"""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
text = call_llm_text(prompt, system=ERROR_ANALYST_PROMPT)
|
||||||
text = response.text.strip()
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
|
||||||
|
|
||||||
result = json.loads(text)
|
result = json.loads(text)
|
||||||
|
|
||||||
decision_str = result.get("decision", "replan").lower()
|
decision_str = result.get("decision", "replan").lower()
|
||||||
decision_map = {
|
decision_map = {
|
||||||
"retry": ErrorDecision.RETRY,
|
"retry": ErrorDecision.RETRY,
|
||||||
@@ -122,7 +89,6 @@ Attempt number: {attempt}"""
|
|||||||
}
|
}
|
||||||
result["decision"] = decision_map.get(decision_str, ErrorDecision.REPLAN)
|
result["decision"] = decision_map.get(decision_str, ErrorDecision.REPLAN)
|
||||||
|
|
||||||
|
|
||||||
if step.get("critical") and result["decision"] == ErrorDecision.SKIP:
|
if step.get("critical") and result["decision"] == ErrorDecision.SKIP:
|
||||||
result["decision"] = ErrorDecision.REPLAN
|
result["decision"] = ErrorDecision.REPLAN
|
||||||
result["user_message"] = "This step is critical — finding alternative approach, sir."
|
result["user_message"] = "This step is critical — finding alternative approach, sir."
|
||||||
@@ -137,22 +103,11 @@ Attempt number: {attempt}"""
|
|||||||
"reason": str(e),
|
"reason": str(e),
|
||||||
"fix_suggestion": "Try alternative approach",
|
"fix_suggestion": "Try alternative approach",
|
||||||
"max_retries": 1,
|
"max_retries": 1,
|
||||||
"user_message": "Encountered an issue, adjusting approach, sir."
|
"user_message": "Encountered an issue, adjusting approach, sir.",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def generate_fix(step: dict, error: str, fix_suggestion: str) -> dict:
|
def generate_fix(step: dict, error: str, fix_suggestion: str) -> dict:
|
||||||
"""
|
|
||||||
When decision is REPLAN and a fix suggestion exists,
|
|
||||||
generates a replacement step using generated_code as fallback.
|
|
||||||
|
|
||||||
Returns a modified step dict.
|
|
||||||
"""
|
|
||||||
import google.generativeai as genai
|
|
||||||
|
|
||||||
genai.configure(api_key=_get_api_key())
|
|
||||||
model = genai.GenerativeModel(model_name="gemini-2.0-flash")
|
|
||||||
|
|
||||||
prompt = f"""A task step failed. Generate a replacement step.
|
prompt = f"""A task step failed. Generate a replacement step.
|
||||||
|
|
||||||
Original step:
|
Original step:
|
||||||
@@ -167,10 +122,8 @@ Write a Python script that accomplishes the same goal differently.
|
|||||||
Return ONLY the Python code, no explanation."""
|
Return ONLY the Python code, no explanation."""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
code = call_llm_text(prompt)
|
||||||
code = response.text.strip()
|
|
||||||
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"step": step.get("step"),
|
"step": step.get("step"),
|
||||||
"tool": "code_helper",
|
"tool": "code_helper",
|
||||||
@@ -179,12 +132,11 @@ Return ONLY the Python code, no explanation."""
|
|||||||
"action": "run",
|
"action": "run",
|
||||||
"description": fix_suggestion,
|
"description": fix_suggestion,
|
||||||
"code": code,
|
"code": code,
|
||||||
"language": "python"
|
"language": "python",
|
||||||
},
|
},
|
||||||
"depends_on": step.get("depends_on", []),
|
"depends_on": step.get("depends_on", []),
|
||||||
"critical": step.get("critical", False)
|
"critical": step.get("critical", False),
|
||||||
}
|
}
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[ErrorHandler] ⚠️ Fix generation failed: {e}")
|
print(f"[ErrorHandler] ⚠️ Fix generation failed: {e}")
|
||||||
return {
|
return {
|
||||||
@@ -193,5 +145,5 @@ Return ONLY the Python code, no explanation."""
|
|||||||
"description": f"Fallback for: {step.get('description')}",
|
"description": f"Fallback for: {step.get('description')}",
|
||||||
"parameters": {"description": step.get("description", "")},
|
"parameters": {"description": step.get("description", "")},
|
||||||
"depends_on": step.get("depends_on", []),
|
"depends_on": step.get("depends_on", []),
|
||||||
"critical": step.get("critical", False)
|
"critical": step.get("critical", False),
|
||||||
}
|
}
|
||||||
+87
-89
@@ -1,3 +1,7 @@
|
|||||||
|
"""
|
||||||
|
MARK XL — Agent Executor
|
||||||
|
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||||
|
"""
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
@@ -10,6 +14,7 @@ from typing import Callable
|
|||||||
|
|
||||||
from agent.planner import create_plan, replan
|
from agent.planner import create_plan, replan
|
||||||
from agent.error_handler import analyze_error, generate_fix, ErrorDecision
|
from agent.error_handler import analyze_error, generate_fix, ErrorDecision
|
||||||
|
from core.llm_client import call_llm_text
|
||||||
|
|
||||||
|
|
||||||
def get_base_dir() -> Path:
|
def get_base_dir() -> Path:
|
||||||
@@ -18,17 +23,14 @@ def get_base_dir() -> Path:
|
|||||||
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"
|
|
||||||
|
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
# ---------------------------------------------------------------------------
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
# Code generation helper (replaces _run_generated_code with Gemini)
|
||||||
return json.load(f)["gemini_api_key"]
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
||||||
import google.generativeai as genai
|
|
||||||
|
|
||||||
if speak:
|
if speak:
|
||||||
speak("Writing custom code for this task, sir.")
|
speak("Writing custom code for this task, sir.")
|
||||||
|
|
||||||
@@ -40,34 +42,30 @@ def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
|||||||
if not desktop.exists():
|
if not desktop.exists():
|
||||||
try:
|
try:
|
||||||
import winreg
|
import winreg
|
||||||
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,
|
key = winreg.OpenKey(
|
||||||
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
|
winreg.HKEY_CURRENT_USER,
|
||||||
|
r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders",
|
||||||
|
)
|
||||||
desktop = Path(winreg.QueryValueEx(key, "Desktop")[0])
|
desktop = Path(winreg.QueryValueEx(key, "Desktop")[0])
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
genai.configure(api_key=_get_api_key())
|
system = (
|
||||||
model = genai.GenerativeModel(
|
"You are an expert Python developer. "
|
||||||
model_name="gemini-2.5-flash",
|
"Write clean, complete, working Python code. "
|
||||||
system_instruction=(
|
"Use standard library + common packages. "
|
||||||
"You are an expert Python developer. "
|
"Install missing packages with subprocess + pip if needed. "
|
||||||
"Write clean, complete, working Python code. "
|
"Return ONLY the Python code. No explanation, no markdown, no backticks.\n\n"
|
||||||
"Use standard library + common packages. "
|
f"SYSTEM PATHS:\n"
|
||||||
"Install missing packages with subprocess + pip if needed. "
|
f" Desktop = r'{desktop}'\n"
|
||||||
"Return ONLY the Python code. No explanation, no markdown, no backticks.\n\n"
|
f" Downloads = r'{downloads}'\n"
|
||||||
f"SYSTEM PATHS:\n"
|
f" Documents = r'{documents}'\n"
|
||||||
f" Desktop = r'{desktop}'\n"
|
f" Home = r'{home}'\n"
|
||||||
f" Downloads = r'{downloads}'\n"
|
|
||||||
f" Documents = r'{documents}'\n"
|
|
||||||
f" Home = r'{home}'\n"
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
|
prompt = f"Write Python code to accomplish this task:\n\n{description}"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(
|
code = call_llm_text(prompt, system=system)
|
||||||
f"Write Python code to accomplish this task:\n\n{description}"
|
|
||||||
)
|
|
||||||
code = response.text.strip()
|
|
||||||
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
code = re.sub(r"```(?:python)?", "", code).strip().rstrip("`").strip()
|
||||||
|
|
||||||
with tempfile.NamedTemporaryFile(
|
with tempfile.NamedTemporaryFile(
|
||||||
@@ -81,7 +79,7 @@ def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
|||||||
result = subprocess.run(
|
result = subprocess.run(
|
||||||
[sys.executable, tmp_path],
|
[sys.executable, tmp_path],
|
||||||
capture_output=True, text=True,
|
capture_output=True, text=True,
|
||||||
timeout=120, cwd=str(Path.home())
|
timeout=120, cwd=str(Path.home()),
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -107,37 +105,18 @@ def _run_generated_code(description: str, speak: Callable | None = None) -> str:
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
raise RuntimeError(f"Generated code failed: {e}")
|
raise RuntimeError(f"Generated code failed: {e}")
|
||||||
|
|
||||||
def _inject_context(params: dict, tool: str, step_results: dict, goal: str = "") -> dict:
|
|
||||||
if not step_results:
|
|
||||||
return params
|
|
||||||
|
|
||||||
params = dict(params)
|
# ---------------------------------------------------------------------------
|
||||||
|
# Context injection
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
if tool == "file_controller" and params.get("action") in ("write", "create_file"):
|
|
||||||
content = params.get("content", "")
|
|
||||||
if not content or len(content) < 50:
|
|
||||||
all_results = [
|
|
||||||
v for v in step_results.values()
|
|
||||||
if v and len(v) > 100 and v not in ("Done.", "Completed.")
|
|
||||||
]
|
|
||||||
if all_results:
|
|
||||||
combined = "\n\n---\n\n".join(all_results)
|
|
||||||
translated = _translate_to_goal_language(combined, goal)
|
|
||||||
params["content"] = translated
|
|
||||||
print(f"[Executor] 💉 Injected + translated content")
|
|
||||||
|
|
||||||
return params
|
|
||||||
def _detect_language(text: str) -> str:
|
def _detect_language(text: str) -> str:
|
||||||
import google.generativeai as genai
|
|
||||||
genai.configure(api_key=_get_api_key())
|
|
||||||
model = genai.GenerativeModel("gemini-2.5-flash-lite")
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(
|
return call_llm_text(
|
||||||
f"What language is this text written in? "
|
f"What language is this text written in? "
|
||||||
f"Reply with ONLY the language name in English (e.g. Turkish, English, French).\n\n"
|
f"Reply with ONLY the language name in English (e.g. Turkish, English, French).\n\n"
|
||||||
f"Text: {text[:200]}"
|
f"Text: {text[:200]}"
|
||||||
)
|
).strip()
|
||||||
return response.text.strip()
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return "English"
|
return "English"
|
||||||
|
|
||||||
@@ -146,13 +125,8 @@ def _translate_to_goal_language(content: str, goal: str) -> str:
|
|||||||
if not goal:
|
if not goal:
|
||||||
return content
|
return content
|
||||||
try:
|
try:
|
||||||
import google.generativeai as genai
|
|
||||||
genai.configure(api_key=_get_api_key())
|
|
||||||
model = genai.GenerativeModel("gemini-2.5-flash")
|
|
||||||
|
|
||||||
target_lang = _detect_language(goal)
|
target_lang = _detect_language(goal)
|
||||||
print(f"[Executor] 🌐 Translating to: {target_lang}")
|
print(f"[Executor] 🌐 Translating to: {target_lang}")
|
||||||
|
|
||||||
prompt = (
|
prompt = (
|
||||||
f"You are a professional translator. "
|
f"You are a professional translator. "
|
||||||
f"Translate the following text into {target_lang}.\n"
|
f"Translate the following text into {target_lang}.\n"
|
||||||
@@ -163,16 +137,38 @@ def _translate_to_goal_language(content: str, goal: str) -> str:
|
|||||||
f"- Output ONLY the translated text, nothing else\n\n"
|
f"- Output ONLY the translated text, nothing else\n\n"
|
||||||
f"Text to translate:\n{content[:4000]}"
|
f"Text to translate:\n{content[:4000]}"
|
||||||
)
|
)
|
||||||
response = model.generate_content(prompt)
|
translated = call_llm_text(prompt)
|
||||||
translated = response.text.strip()
|
|
||||||
print(f"[Executor] ✅ Translation done ({target_lang})")
|
print(f"[Executor] ✅ Translation done ({target_lang})")
|
||||||
return translated
|
return translated
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"[Executor] ⚠️ Translation failed: {e}")
|
print(f"[Executor] ⚠️ Translation failed: {e}")
|
||||||
return content
|
return content
|
||||||
|
|
||||||
def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
|
||||||
|
|
||||||
|
def _inject_context(params: dict, tool: str, step_results: dict, goal: str = "") -> dict:
|
||||||
|
if not step_results:
|
||||||
|
return params
|
||||||
|
params = dict(params)
|
||||||
|
if tool == "file_controller" and params.get("action") in ("write", "create_file"):
|
||||||
|
content = params.get("content", "")
|
||||||
|
if not content or len(content) < 50:
|
||||||
|
all_results = [
|
||||||
|
v for v in step_results.values()
|
||||||
|
if v and len(v) > 100 and v not in ("Done.", "Completed.")
|
||||||
|
]
|
||||||
|
if all_results:
|
||||||
|
combined = "\n\n---\n\n".join(all_results)
|
||||||
|
translated = _translate_to_goal_language(combined, goal)
|
||||||
|
params["content"] = translated
|
||||||
|
print("[Executor] 💉 Injected + translated content")
|
||||||
|
return params
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Tool routing
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
||||||
if tool == "open_app":
|
if tool == "open_app":
|
||||||
from actions.open_app import open_app
|
from actions.open_app import open_app
|
||||||
return open_app(parameters=parameters, player=None) or "Done."
|
return open_app(parameters=parameters, player=None) or "Done."
|
||||||
@@ -180,9 +176,11 @@ def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
|||||||
elif tool == "web_search":
|
elif tool == "web_search":
|
||||||
from actions.web_search import web_search
|
from actions.web_search import web_search
|
||||||
return web_search(parameters=parameters, player=None) or "Done."
|
return web_search(parameters=parameters, player=None) or "Done."
|
||||||
|
|
||||||
elif tool == "game_updater":
|
elif tool == "game_updater":
|
||||||
from actions.game_updater import game_updater
|
from actions.game_updater import game_updater
|
||||||
return game_updater(parameters=parameters, player=None, speak=speak) or "Done."
|
return game_updater(parameters=parameters, player=None, speak=speak) or "Done."
|
||||||
|
|
||||||
elif tool == "browser_control":
|
elif tool == "browser_control":
|
||||||
from actions.browser_control import browser_control
|
from actions.browser_control import browser_control
|
||||||
return browser_control(parameters=parameters, player=None) or "Done."
|
return browser_control(parameters=parameters, player=None) or "Done."
|
||||||
@@ -201,8 +199,8 @@ def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
|||||||
|
|
||||||
elif tool == "screen_process":
|
elif tool == "screen_process":
|
||||||
from actions.screen_processor import screen_process
|
from actions.screen_processor import screen_process
|
||||||
screen_process(parameters=parameters, player=None)
|
result = screen_process(parameters=parameters, player=None)
|
||||||
return "Screen captured and analyzed."
|
return result if isinstance(result, str) else "Screen captured and analyzed."
|
||||||
|
|
||||||
elif tool == "send_message":
|
elif tool == "send_message":
|
||||||
from actions.send_message import send_message
|
from actions.send_message import send_message
|
||||||
@@ -246,6 +244,11 @@ def _call_tool(tool: str, parameters: dict, speak: Callable | None) -> str:
|
|||||||
print(f"[Executor] ⚠️ Unknown tool '{tool}' — falling back to generated_code")
|
print(f"[Executor] ⚠️ Unknown tool '{tool}' — falling back to generated_code")
|
||||||
return _run_generated_code(f"Accomplish this task: {parameters}", speak=speak)
|
return _run_generated_code(f"Accomplish this task: {parameters}", speak=speak)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# AgentExecutor
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
class AgentExecutor:
|
class AgentExecutor:
|
||||||
|
|
||||||
MAX_REPLAN_ATTEMPTS = 2
|
MAX_REPLAN_ATTEMPTS = 2
|
||||||
@@ -259,13 +262,12 @@ class AgentExecutor:
|
|||||||
print(f"\n[Executor] 🎯 Goal: {goal}")
|
print(f"\n[Executor] 🎯 Goal: {goal}")
|
||||||
|
|
||||||
replan_attempts = 0
|
replan_attempts = 0
|
||||||
completed_steps = []
|
completed_steps: list = []
|
||||||
step_results = {}
|
step_results: dict = {}
|
||||||
plan = create_plan(goal)
|
plan = create_plan(goal)
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
steps = plan.get("steps", [])
|
steps = plan.get("steps", [])
|
||||||
|
|
||||||
if not steps:
|
if not steps:
|
||||||
msg = "I couldn't create a valid plan for this task, sir."
|
msg = "I couldn't create a valid plan for this task, sir."
|
||||||
if speak: speak(msg)
|
if speak: speak(msg)
|
||||||
@@ -284,8 +286,7 @@ class AgentExecutor:
|
|||||||
tool = step.get("tool", "generated_code")
|
tool = step.get("tool", "generated_code")
|
||||||
desc = step.get("description", "")
|
desc = step.get("description", "")
|
||||||
params = step.get("parameters", {})
|
params = step.get("parameters", {})
|
||||||
|
params = _inject_context(params, tool, step_results, goal=goal)
|
||||||
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}")
|
||||||
|
|
||||||
@@ -330,7 +331,7 @@ class AgentExecutor:
|
|||||||
if speak: speak(msg)
|
if speak: speak(msg)
|
||||||
return msg
|
return msg
|
||||||
|
|
||||||
else:
|
else: # REPLAN
|
||||||
fix_suggestion = recovery.get("fix_suggestion", "")
|
fix_suggestion = recovery.get("fix_suggestion", "")
|
||||||
if fix_suggestion and tool != "generated_code":
|
if fix_suggestion and tool != "generated_code":
|
||||||
try:
|
try:
|
||||||
@@ -339,7 +340,7 @@ class AgentExecutor:
|
|||||||
res = _call_tool(
|
res = _call_tool(
|
||||||
fixed_step["tool"],
|
fixed_step["tool"],
|
||||||
fixed_step["parameters"],
|
fixed_step["parameters"],
|
||||||
speak
|
speak,
|
||||||
)
|
)
|
||||||
step_results[step_num] = res
|
step_results[step_num] = res
|
||||||
completed_steps.append(step)
|
completed_steps.append(step)
|
||||||
@@ -370,27 +371,24 @@ class AgentExecutor:
|
|||||||
return 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]}."
|
||||||
|
steps_str = "\n".join(f"- {s.get('description', '')}" for s in completed_steps)
|
||||||
|
prompt = (
|
||||||
|
f'User goal: "{goal}"\n'
|
||||||
|
f"Completed steps:\n{steps_str}\n\n"
|
||||||
|
"Write a single natural sentence summarising what was accomplished. "
|
||||||
|
"Address the user as 'sir'. Be direct and positive."
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
import google.generativeai as genai
|
summary = call_llm_text(prompt)
|
||||||
genai.configure(api_key=_get_api_key())
|
if summary:
|
||||||
model = genai.GenerativeModel(model_name="gemini-2.5-flash-lite")
|
if speak: speak(summary)
|
||||||
steps_str = "\n".join(f"- {s.get('description', '')}" for s in completed_steps)
|
return summary
|
||||||
prompt = (
|
|
||||||
f'User goal: "{goal}"\n'
|
|
||||||
f"Completed steps:\n{steps_str}\n\n"
|
|
||||||
"Write a single natural sentence summarizing what was accomplished. "
|
|
||||||
"Address the user as 'sir'. Be direct and positive."
|
|
||||||
)
|
|
||||||
response = model.generate_content(prompt)
|
|
||||||
summary = response.text.strip()
|
|
||||||
if speak: speak(summary)
|
|
||||||
return summary
|
|
||||||
except Exception:
|
except Exception:
|
||||||
if speak: speak(fallback)
|
pass
|
||||||
return fallback
|
if speak: speak(fallback)
|
||||||
|
return fallback
|
||||||
+24
-85
@@ -1,8 +1,14 @@
|
|||||||
|
"""
|
||||||
|
MARK XL — Task Planner
|
||||||
|
Replaces google.generativeai with local Ollama via core.llm_client.
|
||||||
|
"""
|
||||||
import json
|
import json
|
||||||
import re
|
import re
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
from core.llm_client import call_llm_text
|
||||||
|
|
||||||
|
|
||||||
def get_base_dir() -> Path:
|
def get_base_dir() -> Path:
|
||||||
if getattr(sys, "frozen", False):
|
if getattr(sys, "frozen", False):
|
||||||
@@ -10,11 +16,10 @@ def get_base_dir() -> Path:
|
|||||||
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"
|
|
||||||
|
|
||||||
|
|
||||||
PLANNER_PROMPT = """You are the planning module of MARK XXV, a personal AI assistant.
|
PLANNER_PROMPT = """You are the planning module of MARK XL, a personal AI assistant.
|
||||||
Your job: break any user goal into a sequence of steps using ONLY the tools listed below.
|
Your job: break any user goal into a sequence of steps using ONLY the tools listed below.
|
||||||
|
|
||||||
ABSOLUTE RULES:
|
ABSOLUTE RULES:
|
||||||
@@ -110,45 +115,6 @@ code_helper
|
|||||||
dev_agent
|
dev_agent
|
||||||
description: string (required)
|
description: string (required)
|
||||||
language: string (optional)
|
language: string (optional)
|
||||||
EXAMPLES:
|
|
||||||
|
|
||||||
Goal: "research mechanical engineering and save it to a notepad file"
|
|
||||||
Steps:
|
|
||||||
|
|
||||||
web_search | query: "mechanical engineering overview definition history"
|
|
||||||
web_search | query: "mechanical engineering applications and future trends"
|
|
||||||
file_controller | action: write, path: desktop, name: mechanical_engineering.txt, content: "MECHANICAL ENGINEERING RESEARCH\n\nThis file will be filled with web research results."
|
|
||||||
|
|
||||||
Goal: "What is the price of Bitcoin"
|
|
||||||
Steps:
|
|
||||||
|
|
||||||
web_search | query: "Bitcoin price today USD"
|
|
||||||
|
|
||||||
Goal: "List the files on the desktop and find the largest 5 files"
|
|
||||||
Steps:
|
|
||||||
|
|
||||||
file_controller | action: list, path: desktop
|
|
||||||
file_controller | action: largest, path: desktop, count: 5
|
|
||||||
|
|
||||||
Goal: "Install PUBG from Steam"
|
|
||||||
Steps:
|
|
||||||
|
|
||||||
game_updater | action: install, platform: steam, game_name: "PUBG"
|
|
||||||
|
|
||||||
Goal: "Update all my Steam games"
|
|
||||||
Steps:
|
|
||||||
|
|
||||||
game_updater | action: update, platform: steam
|
|
||||||
|
|
||||||
Goal: "Send John a message on WhatsApp saying there is a meeting tomorrow"
|
|
||||||
Steps:
|
|
||||||
|
|
||||||
send_message | receiver: John, message_text: "There is a meeting tomorrow", platform: WhatsApp
|
|
||||||
|
|
||||||
Goal: "Open the clock and set a reminder for 30 minutes later"
|
|
||||||
Steps:
|
|
||||||
|
|
||||||
reminder | date: [today], time: [now+30min], message: "Reminder"
|
|
||||||
|
|
||||||
OUTPUT — return ONLY valid JSON, no markdown, no explanation, no code blocks:
|
OUTPUT — return ONLY valid JSON, no markdown, no explanation, no code blocks:
|
||||||
{
|
{
|
||||||
@@ -166,45 +132,28 @@ OUTPUT — return ONLY valid JSON, no markdown, no explanation, no code blocks:
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
def _get_api_key() -> str:
|
|
||||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
|
||||||
return json.load(f)["gemini_api_key"]
|
|
||||||
|
|
||||||
|
|
||||||
def create_plan(goal: str, context: str = "") -> dict:
|
def create_plan(goal: str, context: str = "") -> dict:
|
||||||
import google.generativeai as genai
|
|
||||||
|
|
||||||
genai.configure(api_key=_get_api_key())
|
|
||||||
model = genai.GenerativeModel(
|
|
||||||
model_name="gemini-2.5-flash-lite",
|
|
||||||
system_instruction=PLANNER_PROMPT
|
|
||||||
)
|
|
||||||
|
|
||||||
user_input = f"Goal: {goal}"
|
user_input = f"Goal: {goal}"
|
||||||
if context:
|
if context:
|
||||||
user_input += f"\n\nContext: {context}"
|
user_input += f"\n\nContext: {context}"
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(user_input)
|
text = call_llm_text(user_input, system=PLANNER_PROMPT)
|
||||||
text = response.text.strip()
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
|
||||||
|
|
||||||
plan = json.loads(text)
|
plan = json.loads(text)
|
||||||
|
|
||||||
if "steps" not in plan or not isinstance(plan["steps"], list):
|
if "steps" not in plan or not isinstance(plan["steps"], list):
|
||||||
raise ValueError("Invalid plan structure")
|
raise ValueError("Invalid plan structure")
|
||||||
|
|
||||||
for step in plan["steps"]:
|
for step in plan["steps"]:
|
||||||
if step.get("tool") in ("generated_code",):
|
if step.get("tool") == "generated_code":
|
||||||
print(f"[Planner] ⚠️ generated_code detected in step {step.get('step')} — replacing with web_search")
|
print(f"[Planner] ⚠️ generated_code in step {step.get('step')} — replacing with web_search")
|
||||||
desc = step.get("description", goal)
|
step["tool"] = "web_search"
|
||||||
step["tool"] = "web_search"
|
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
||||||
step["parameters"] = {"query": desc[:200]}
|
|
||||||
|
|
||||||
print(f"[Planner] ✅ Plan: {len(plan['steps'])} steps")
|
print(f"[Planner] ✅ Plan: {len(plan['steps'])} steps")
|
||||||
for s in plan["steps"]:
|
for s in plan["steps"]:
|
||||||
print(f" Step {s['step']}: [{s['tool']}] {s['description']}")
|
print(f" Step {s['step']}: [{s['tool']}] {s['description']}")
|
||||||
|
|
||||||
return plan
|
return plan
|
||||||
|
|
||||||
except json.JSONDecodeError as e:
|
except json.JSONDecodeError as e:
|
||||||
@@ -218,32 +167,23 @@ def create_plan(goal: str, context: str = "") -> dict:
|
|||||||
def _fallback_plan(goal: str) -> dict:
|
def _fallback_plan(goal: str) -> dict:
|
||||||
print("[Planner] 🔄 Fallback plan")
|
print("[Planner] 🔄 Fallback plan")
|
||||||
return {
|
return {
|
||||||
"goal": goal,
|
"goal": goal,
|
||||||
"steps": [
|
"steps": [
|
||||||
{
|
{
|
||||||
"step": 1,
|
"step": 1,
|
||||||
"tool": "web_search",
|
"tool": "web_search",
|
||||||
"description": f"Search for: {goal}",
|
"description": f"Search for: {goal}",
|
||||||
"parameters": {"query": goal},
|
"parameters": {"query": goal},
|
||||||
"critical": True
|
"critical": True,
|
||||||
}
|
}
|
||||||
]
|
],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def replan(goal: str, completed_steps: list, failed_step: dict, error: str) -> dict:
|
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(
|
completed_summary = "\n".join(
|
||||||
f" - Step {s['step']} ({s['tool']}): DONE" for s in completed_steps
|
f" - Step {s['step']} ({s['tool']}): DONE" for s in completed_steps
|
||||||
)
|
)
|
||||||
|
|
||||||
prompt = f"""Goal: {goal}
|
prompt = f"""Goal: {goal}
|
||||||
|
|
||||||
Already completed:
|
Already completed:
|
||||||
@@ -255,14 +195,13 @@ Error: {error}
|
|||||||
Create a REVISED plan for the remaining work only. Do not repeat completed steps."""
|
Create a REVISED plan for the remaining work only. Do not repeat completed steps."""
|
||||||
|
|
||||||
try:
|
try:
|
||||||
response = model.generate_content(prompt)
|
text = call_llm_text(prompt, system=PLANNER_PROMPT)
|
||||||
text = response.text.strip()
|
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
||||||
text = re.sub(r"```(?:json)?", "", text).strip().rstrip("`").strip()
|
plan = json.loads(text)
|
||||||
plan = json.loads(text)
|
|
||||||
|
|
||||||
for step in plan.get("steps", []):
|
for step in plan.get("steps", []):
|
||||||
if step.get("tool") == "generated_code":
|
if step.get("tool") == "generated_code":
|
||||||
step["tool"] = "web_search"
|
step["tool"] = "web_search"
|
||||||
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
step["parameters"] = {"query": step.get("description", goal)[:200]}
|
||||||
|
|
||||||
print(f"[Planner] 🔄 Revised plan: {len(plan['steps'])} steps")
|
print(f"[Planner] 🔄 Revised plan: {len(plan['steps'])} steps")
|
||||||
|
|||||||
+14
-5
@@ -1,16 +1,25 @@
|
|||||||
# config/__init__.py
|
# config/__init__.py
|
||||||
import json, os
|
import json
|
||||||
|
import platform
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
_CONFIG_PATH = Path(__file__).parent / "api_keys.json"
|
_CONFIG_PATH = Path(__file__).parent / "api_keys.json"
|
||||||
|
|
||||||
def get_config() -> dict:
|
def get_config() -> dict:
|
||||||
with open(_CONFIG_PATH, "r", encoding="utf-8") as f:
|
try:
|
||||||
return json.load(f)
|
with open(_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||||
|
return json.load(f)
|
||||||
|
except Exception:
|
||||||
|
return {}
|
||||||
|
|
||||||
def get_os() -> str:
|
def get_os() -> str:
|
||||||
"""Returns: 'windows' | 'mac' | 'linux'"""
|
"""Returns 'windows' | 'mac' | 'linux' — detected at runtime, not from config."""
|
||||||
return get_config().get("os_system", "windows").lower()
|
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_windows() -> bool: return get_os() == "windows"
|
||||||
def is_mac() -> bool: return get_os() == "mac"
|
def is_mac() -> bool: return get_os() == "mac"
|
||||||
|
|||||||
@@ -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)
|
||||||
+18
-15
@@ -2,37 +2,37 @@ import json
|
|||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
def get_base_dir() -> Path:
|
def get_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_DIR = get_base_dir()
|
BASE_DIR = get_base_dir()
|
||||||
CONFIG_DIR = BASE_DIR / "config"
|
CONFIG_DIR = BASE_DIR / "config"
|
||||||
CONFIG_FILE = CONFIG_DIR / "api_keys.json"
|
CONFIG_FILE = CONFIG_DIR / "api_keys.json"
|
||||||
|
|
||||||
|
|
||||||
def ensure_config_dir() -> None:
|
def ensure_config_dir() -> None:
|
||||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
|
||||||
def config_exists() -> bool:
|
def config_exists() -> bool:
|
||||||
return CONFIG_FILE.exists()
|
return CONFIG_FILE.exists()
|
||||||
|
|
||||||
def save_api_keys(gemini_api_key: str) -> None:
|
|
||||||
ensure_config_dir()
|
|
||||||
|
|
||||||
data: dict = {}
|
def save_config(cfg: dict) -> None:
|
||||||
|
ensure_config_dir()
|
||||||
|
existing: dict = {}
|
||||||
if CONFIG_FILE.exists():
|
if CONFIG_FILE.exists():
|
||||||
try:
|
try:
|
||||||
data = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
existing = json.loads(CONFIG_FILE.read_text(encoding="utf-8"))
|
||||||
except Exception:
|
except Exception:
|
||||||
data = {}
|
existing = {}
|
||||||
|
existing.update(cfg)
|
||||||
|
CONFIG_FILE.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||||
|
|
||||||
data["gemini_api_key"] = gemini_api_key.strip()
|
|
||||||
|
|
||||||
CONFIG_FILE.write_text(
|
|
||||||
json.dumps(data, indent=2),
|
|
||||||
encoding="utf-8"
|
|
||||||
)
|
|
||||||
|
|
||||||
def load_api_keys() -> dict:
|
def load_api_keys() -> dict:
|
||||||
if not CONFIG_FILE.exists():
|
if not CONFIG_FILE.exists():
|
||||||
@@ -43,9 +43,12 @@ def load_api_keys() -> dict:
|
|||||||
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:
|
def is_configured() -> bool:
|
||||||
key = get_gemini_key()
|
cfg = load_api_keys()
|
||||||
return bool(key and len(key) > 15)
|
return (
|
||||||
|
bool(cfg.get("os_system")) and
|
||||||
|
bool(cfg.get("llm_model")) and
|
||||||
|
bool(cfg.get("stt_engine")) and
|
||||||
|
bool(cfg.get("tts_engine"))
|
||||||
|
)
|
||||||
@@ -1,81 +1,159 @@
|
|||||||
# 🤖 MARK XXXIX (39)
|
# 🤖 MARK XL — Local AI Assistant
|
||||||
### The Ultimate Cross-Platform Personal AI Assistant — By FatihMakes
|
|
||||||
|
|
||||||
> 📺 **[Watch the full setup video on YouTube](https://youtu.be/ej1f5OE3SNQ?si=lCxDhJix9ungq1Ry)**
|
> **J.A.R.V.I.S** — Just A Rather Very Intelligent System
|
||||||
|
> Cross-platform voice AI assistant running entirely on local hardware. No cloud APIs required.
|
||||||
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 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.
|
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.
|
||||||
|
|
||||||
It's not just an assistant — it's an extension of your digital life.
|
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.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🚀 Capabilities
|
## Architecture
|
||||||
|
|
||||||
### Core Features
|
```
|
||||||
| Feature | Description |
|
Microphone → STT (Whisper / Vosk)
|
||||||
|---|---|
|
↓
|
||||||
| 🎙️ Real-time Voice | Ultra-low latency conversation in any language |
|
Ollama LLM (tool calling + streaming)
|
||||||
| 🖥️ System Control | Launch apps, manage files, execute terminal commands |
|
↓
|
||||||
| 🧩 Autonomous Tasks | High-level planning for complex, multi-step goals |
|
Tool Execution (OS, Browser, Files …)
|
||||||
| 👁️ Visual Awareness | Real-time screen processing and webcam vision |
|
↓
|
||||||
| 🧠 Persistent Memory | Deeply remembers your projects, preferences, and personal context |
|
TTS (EdgeTTS / Kokoro / ElevenLabs)
|
||||||
| ⌨️ Hybrid Input | Seamlessly switch between keyboard typing and voice commands |
|
↓
|
||||||
|
Speaker
|
||||||
|
```
|
||||||
|
|
||||||
|
### Core Components
|
||||||
|
|
||||||
|
| Layer | Technology | Notes |
|
||||||
|
|-------|-----------|-------|
|
||||||
|
| **STT** | faster-whisper / Vosk | Fully offline. Auto language detection or forced locale. |
|
||||||
|
| **LLM** | Ollama (any model) | qwen2.5, llama3.2, mistral, etc. Streaming + tool calling. |
|
||||||
|
| **TTS** | EdgeTTS / Kokoro / ElevenLabs | EdgeTTS = free + internet. Kokoro = fully offline. |
|
||||||
|
| **UI** | PyQt6 | HUD overlay with system monitor, log panel, file drop zone. |
|
||||||
|
| **Agent** | Custom task queue | Multi-step planner + executor + error recovery. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🆕 What's New in XXXIX
|
## Features
|
||||||
|
|
||||||
- 📂 **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.
|
- **Streaming responses** — TTS starts speaking on the first sentence, not after the full response
|
||||||
- 🎨 **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.
|
- **Tool calling** — 18 built-in tools: browser control, file management, weather, YouTube, messaging, screen analysis, code helper, game updater, flight finder, and more
|
||||||
- 🐧🍎 **Refined Cross-Platform Stability** — Major fixes for macOS and Linux compatibility. Core system actions are now more consistent across all three major operating systems.
|
- **Long-term memory** — Silently saves personal facts; recalled in every conversation
|
||||||
- ⚡ **Optimized Core Engine** — Significant performance boost in tool-calling logic and response generation, resulting in a 40% faster interaction speed.
|
- **Live configuration** — Change LLM model, STT engine, TTS voice without restarting (⚙ Configure button)
|
||||||
|
- **Ollama auto-start** — Automatically launches `ollama serve` if it's not running
|
||||||
|
- **Model warmup** — Pre-loads the LLM into memory during startup so the first message is as fast as subsequent ones
|
||||||
|
- **Multi-language STT** — Set `stt_language` to `auto` (Whisper detects) or a specific locale (`tr`, `de`, `fr`, …)
|
||||||
|
- **Cross-platform** — Windows, macOS, Linux (OS detected automatically at runtime)
|
||||||
|
- **File drop zone** — Drag and drop images, PDFs, Word docs, CSV, audio, video for AI processing
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚡ Quick Start
|
## Requirements
|
||||||
|
|
||||||
|
- Python 3.11 or 3.12
|
||||||
|
- [Ollama](https://ollama.com) installed and a model pulled (e.g. `ollama pull qwen2.5:7b`)
|
||||||
|
- A microphone
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
git clone https://github.com/FatihMakes/Mark-XXXIX.git
|
# 1. Install Ollama → https://ollama.com
|
||||||
cd Mark-XXXIX
|
# Then pull a model:
|
||||||
pip install -r requirements.txt
|
ollama pull qwen2.5:7b
|
||||||
playwright install
|
|
||||||
|
# 2. Clone / download the project and launch
|
||||||
|
cd Mark-XL
|
||||||
python main.py
|
python main.py
|
||||||
```
|
```
|
||||||
|
|
||||||
> ⚠️ **Installation Note:** To keep the repository lightweight, some OS-specific dependencies are not bundled in `requirements.txt`. If you run into a `ModuleNotFoundError`, simply install the missing package via `pip install <module_name>` for your specific system.
|
That's it. On first run MARK XL:
|
||||||
|
1. Auto-installs base packages (PyQt6, numpy …) and restarts once
|
||||||
|
2. Opens the **Initialisation** overlay — choose STT engine, LLM model, TTS engine
|
||||||
|
3. Click **INITIALISE SYSTEMS** — engine packages install in the background (progress shown in log)
|
||||||
|
4. JARVIS comes online
|
||||||
|
|
||||||
|
After setup, use the **⚙ CONFIGURE** button in the right panel to change any setting at any time without restarting.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 📋 Requirements
|
## Configuration (`config/api_keys.json`)
|
||||||
|
|
||||||
| Requirement | Details |
|
```json
|
||||||
|---|---|
|
{
|
||||||
| **OS** | Windows 10/11, macOS, or Linux |
|
"stt_engine": "whisper",
|
||||||
| **Python** | 3.11 or 3.12 |
|
"stt_model": "base",
|
||||||
| **Microphone** | Required for voice interaction |
|
"stt_language": "auto",
|
||||||
| **API Key** | Free Gemini API key |
|
"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` |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## ⚠️ License
|
## Built-in Tools
|
||||||
|
|
||||||
Personal and non-commercial use only.
|
| Tool | Description |
|
||||||
Licensed under **[Creative Commons BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/)**.
|
|------|-------------|
|
||||||
|
| `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 |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 👤 Connect with the Creator
|
## Keyboard Shortcuts
|
||||||
|
|
||||||
Engineered by a developer building a real-world JARVIS-style assistant.
|
| Key | Action |
|
||||||
⭐ **Star the repository to support the journey to Mark 100.**
|
|-----|--------|
|
||||||
|
| `F4` | Mute / unmute microphone |
|
||||||
|
| `F11` | Toggle fullscreen |
|
||||||
|
|
||||||
| Platform | Link |
|
---
|
||||||
|---|---|
|
|
||||||
| YouTube | [@FatihMakes](https://www.youtube.com/@FatihMakes) |
|
## TTS Engine Comparison
|
||||||
| Instagram | [@fatihmakes](https://www.instagram.com/fatihmakes) |
|
|
||||||
|
| 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
|
||||||
+44
-14
@@ -1,24 +1,54 @@
|
|||||||
sounddevice
|
# MARK XL — Python dependencies
|
||||||
google-genai
|
#
|
||||||
google-generativeai
|
# Normal users: just run python main.py
|
||||||
|
# All packages are installed automatically on first launch.
|
||||||
|
#
|
||||||
|
# Developers / manual setup:
|
||||||
|
# pip install -r requirements.txt
|
||||||
|
# Platform-specific packages install only on the matching OS.
|
||||||
|
|
||||||
|
# ── Core UI & system ──────────────────────────────────────────────────────
|
||||||
|
PyQt6
|
||||||
|
psutil
|
||||||
pillow
|
pillow
|
||||||
|
sounddevice
|
||||||
|
numpy
|
||||||
|
soundfile
|
||||||
requests
|
requests
|
||||||
|
|
||||||
|
# ── Web automation & search ───────────────────────────────────────────────
|
||||||
|
playwright
|
||||||
beautifulsoup4
|
beautifulsoup4
|
||||||
duckduckgo-search
|
duckduckgo-search
|
||||||
playwright
|
|
||||||
|
# ── OS control (cross-platform) ───────────────────────────────────────────
|
||||||
pyautogui
|
pyautogui
|
||||||
pyperclip
|
pyperclip
|
||||||
pygetwindow
|
pygetwindow
|
||||||
opencv-python
|
|
||||||
numpy
|
|
||||||
mss
|
|
||||||
Pillow
|
|
||||||
psutil
|
|
||||||
comtypes
|
|
||||||
pycaw
|
|
||||||
win10toast
|
|
||||||
send2trash
|
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
|
youtube-transcript-api
|
||||||
pywinauto
|
|
||||||
python-pptx
|
python-pptx
|
||||||
pyqt6
|
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