Add files via upload
This commit is contained in:
1 parent
234dd79273
commit
d929ef03cf
30 files changed
+3802
-2702
No files matched your search
@@ -13,10 +13,10 @@ from pathlib import Path
|
||||
# ── Blocked categories (never monitor regardless of what user says) ────────────
|
||||
|
||||
_BLOCKED = {
|
||||
# Marka / varlık adları — her dilde aynı yazılır
|
||||
# Brand / asset names — spelled the same in every language
|
||||
"bitcoin", "ethereum", "dogecoin", "solana", "binance",
|
||||
"nft", "blockchain", "defi", "altcoin", "memecoin", "coin", "token",
|
||||
# "kripto" kökünün farklı dillerdeki yazılışları
|
||||
# spellings of the "crypto" root across different languages
|
||||
"crypto", "kripto", "cripto", "krypto", "крипто", "仮想通貨", "暗号資産",
|
||||
"cryptocurrency",
|
||||
}
|
||||
|
||||
+104
-32
@@ -369,12 +369,12 @@ _WIN_EXE_HINTS: dict[str, str] = {"chrome": "chrome", "edge": "msedge"}
|
||||
|
||||
def _open_native(url: str, browser_name: Optional[str]) -> str:
|
||||
"""
|
||||
Kullanıcının GERÇEK tarayıcısını normal şekilde açar — kendi profili,
|
||||
giriş yapılmış hesapları ve eklentileriyle. Otomasyon bağlanmaz, bu yüzden
|
||||
about:blank sekmesi veya boş profil ASLA görünmez.
|
||||
url boş ise tarayıcı URL'siz başlatılır (kendi açılış sayfası /
|
||||
oturum geri yükleme ile) — tıpkı kullanıcının kendisi açmış gibi.
|
||||
Windows / macOS / Linux üçünde de çalışır.
|
||||
Opens the user's REAL browser normally — with their own profile,
|
||||
logged-in accounts and extensions. No automation attaches, so an
|
||||
about:blank tab or a blank profile NEVER shows up.
|
||||
If url is empty the browser starts with no URL (its own start page /
|
||||
session restore) — exactly as if the user had opened it themselves.
|
||||
Works on all three of Windows / macOS / Linux.
|
||||
"""
|
||||
url = _normalize_url(url) if url and url.strip() else ""
|
||||
if url == "about:blank":
|
||||
@@ -384,7 +384,7 @@ def _open_native(url: str, browser_name: Optional[str]) -> str:
|
||||
if browser_name:
|
||||
name = _ALIASES.get(browser_name.lower().strip(), browser_name.lower().strip())
|
||||
elif not url:
|
||||
# URL yok → sadece pencere açılacak; varsayılan tarayıcının exe'si gerekir
|
||||
# No URL → only a window will open; needs the default browser's exe
|
||||
name = _detect_default_browser()
|
||||
|
||||
# Specific browser → launch its own executable, exactly like the user would.
|
||||
@@ -443,8 +443,8 @@ def _open_native(url: str, browser_name: Optional[str]) -> str:
|
||||
|
||||
class _BrowserSession:
|
||||
"""
|
||||
Bir tarayıcı örneği için tam oturum.
|
||||
Tüm tarayıcılar launch_persistent_context ile gerçek profil üzerinde açılır.
|
||||
A full session for one browser instance.
|
||||
All browsers open on the real profile via launch_persistent_context.
|
||||
"""
|
||||
|
||||
def __init__(self, browser_name: str):
|
||||
@@ -505,9 +505,9 @@ class _BrowserSession:
|
||||
|
||||
async def _adopt_page(self) -> Page:
|
||||
"""
|
||||
launch_persistent_context zaten bir başlangıç sekmesi açar.
|
||||
Yeni bir boş sekme (about:blank) açmak yerine o sekmeyi devralır —
|
||||
böylece kullanıcı fazladan boş sekme görmez.
|
||||
launch_persistent_context already opens a starting tab.
|
||||
Instead of opening a new blank tab (about:blank), it adopts that tab —
|
||||
so the user never sees an extra blank tab.
|
||||
"""
|
||||
await asyncio.sleep(0.3)
|
||||
pages = self._context.pages
|
||||
@@ -515,8 +515,8 @@ class _BrowserSession:
|
||||
|
||||
async def _launch(self):
|
||||
"""
|
||||
Tarayıcıyı gerçek kullanıcı profiliyle başlatır.
|
||||
Context zaten açıksa hiçbir şey yapmaz.
|
||||
Launches the browser with the real user profile.
|
||||
Does nothing if the context is already open.
|
||||
"""
|
||||
if self._context is not None:
|
||||
return
|
||||
@@ -607,10 +607,10 @@ class _BrowserSession:
|
||||
except Exception as e:
|
||||
print(f"[Browser] ⚠️ Real profile failed for {label}: {e}")
|
||||
|
||||
# Gerçek profil açılamadı (tarayıcı zaten açık / kilitli profil / yeni
|
||||
# Chrome sürümleri otomasyonla gerçek profili engelliyor). Kalıcı
|
||||
# JARVIS otomasyon profiline geçilir — buraya bir kez giriş yapılan
|
||||
# hesaplar sonraki oturumlarda da açık kalır.
|
||||
# The real profile could not be opened (browser already open / locked
|
||||
# profile / newer Chrome versions block the real profile under
|
||||
# automation). Fall back to a persistent JARVIS automation profile —
|
||||
# accounts logged in here once stay logged in on later sessions too.
|
||||
jarvis_profile = str(Path.home() / ".jarvis_profiles" / self.browser_name)
|
||||
Path(jarvis_profile).mkdir(parents=True, exist_ok=True)
|
||||
print(f"[Browser] Retrying with JARVIS profile: {jarvis_profile}")
|
||||
@@ -840,7 +840,7 @@ class _BrowserSession:
|
||||
return f"{self.browser_name} closed."
|
||||
|
||||
class _SessionRegistry:
|
||||
"""Tüm aktif tarayıcı oturumlarını yönetir."""
|
||||
"""Manages all active browser sessions."""
|
||||
|
||||
def __init__(self):
|
||||
self._sessions: dict[str, _BrowserSession] = {}
|
||||
@@ -849,7 +849,7 @@ class _SessionRegistry:
|
||||
self._last_native_url: str = ""
|
||||
|
||||
def has(self, browser_name: str | None = None) -> bool:
|
||||
"""Bu tarayıcı için (veya hiç) aktif bir otomasyon oturumu var mı?"""
|
||||
"""Is there an active automation session for this browser (or any)?"""
|
||||
with self._lock:
|
||||
if not browser_name:
|
||||
return bool(self._sessions)
|
||||
@@ -860,7 +860,7 @@ class _SessionRegistry:
|
||||
self._last_native_url = url
|
||||
|
||||
def pop_native_url(self) -> str:
|
||||
"""Son native açılan URL'yi bir kez döndürür (tekrarı önlemek için tüketilir)."""
|
||||
"""Returns the last natively-opened URL once (consumed to avoid repeats)."""
|
||||
url, self._last_native_url = self._last_native_url, ""
|
||||
return url
|
||||
|
||||
@@ -956,12 +956,12 @@ def browser_control(
|
||||
_log(player, result)
|
||||
return result
|
||||
|
||||
# ── Gezinme HER ZAMAN native ─────────────────────────────────────────────
|
||||
# go_to / search / new_tab siteyi kullanıcının kendi tarayıcısında açar —
|
||||
# kendi profili, giriş yapılmış hesapları ve açılış sayfasıyla; tıpkı
|
||||
# kullanıcının kendisi açmış gibi. about:blank'li kontrollü pencere burada
|
||||
# asla açılmaz. Tek istisna: hâlihazırda süren bir otomasyon akışı varsa
|
||||
# gezinme o pencerede devam eder (çok adımlı görevler bölünmesin diye).
|
||||
# ── Navigation is ALWAYS native ──────────────────────────────────────────
|
||||
# go_to / search / new_tab open the site in the user's own browser —
|
||||
# their own profile, logged-in accounts and start page; exactly as if the
|
||||
# user had opened it themselves. A controlled window with about:blank never
|
||||
# opens here. The only exception: if an automation flow is already running,
|
||||
# navigation continues in that window (so multi-step tasks aren't split).
|
||||
if action in ("go_to", "search", "new_tab"):
|
||||
if _registry.has(browser):
|
||||
sess = _registry.get(browser)
|
||||
@@ -993,10 +993,10 @@ def browser_control(
|
||||
_log(player, result)
|
||||
return result
|
||||
|
||||
# ── Etkileşimli aksiyonlar (tıklama/yazma/okuma…) ────────────────────────
|
||||
# Bunlar fiziksel olarak kontrol edilebilir bir tarayıcı gerektirir;
|
||||
# yalnızca burada otomasyon penceresi açılır ve açılır açılmaz kullanıcının
|
||||
# son gezindiği sayfaya gider — boş sayfada beklemez.
|
||||
# ── Interactive actions (click/type/read…) ───────────────────────────────
|
||||
# These require a physically controllable browser; the automation window
|
||||
# only opens here, and as soon as it opens it goes to the user's last
|
||||
# navigated page — it doesn't sit on a blank page.
|
||||
try:
|
||||
sess = _registry.get(browser)
|
||||
except Exception as e:
|
||||
@@ -1057,4 +1057,76 @@ def _log(player, text: str):
|
||||
short = str(text)[:80]
|
||||
print(f"[Browser] {short}")
|
||||
if player:
|
||||
player.write_log(f"[browser] {short[:60]}")
|
||||
player.write_log(f"[browser] {short[:60]}")
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "browser_control",
|
||||
"description": "Controls any web browser. Use for: opening websites, searching the web, clicking elements, filling forms, scrolling, screenshots, navigation, any web-based task. Simple open/search requests launch the user's own browser normally (their real profile and logged-in accounts); interactive actions (click, type, fill_form...) attach an automation browser. Always pass the 'browser' parameter when the user specifies a browser (e.g. 'open in Edge', 'use Firefox', 'open Chrome'). Multiple browsers can run simultaneously.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "go_to | search | click | type | scroll | fill_form | smart_click | smart_type | get_text | get_url | press | new_tab | close_tab | screenshot | back | forward | reload | switch | list_browsers | close | close_all"
|
||||
},
|
||||
"browser": {
|
||||
"type": "STRING",
|
||||
"description": "Target browser: chrome | edge | firefox | opera | operagx | brave | vivaldi | safari. Omit to use the currently active browser."
|
||||
},
|
||||
"url": {
|
||||
"type": "STRING",
|
||||
"description": "URL for go_to / new_tab action"
|
||||
},
|
||||
"query": {
|
||||
"type": "STRING",
|
||||
"description": "Search query for search action"
|
||||
},
|
||||
"engine": {
|
||||
"type": "STRING",
|
||||
"description": "Search engine: google | bing | duckduckgo | yandex (default: google)"
|
||||
},
|
||||
"selector": {
|
||||
"type": "STRING",
|
||||
"description": "CSS selector for click/type"
|
||||
},
|
||||
"text": {
|
||||
"type": "STRING",
|
||||
"description": "Text to click or type"
|
||||
},
|
||||
"description": {
|
||||
"type": "STRING",
|
||||
"description": "Element description for smart_click/smart_type"
|
||||
},
|
||||
"direction": {
|
||||
"type": "STRING",
|
||||
"description": "up | down for scroll"
|
||||
},
|
||||
"amount": {
|
||||
"type": "INTEGER",
|
||||
"description": "Scroll amount in pixels (default: 500)"
|
||||
},
|
||||
"key": {
|
||||
"type": "STRING",
|
||||
"description": "Key name for press action (e.g. Enter, Escape, F5)"
|
||||
},
|
||||
"path": {
|
||||
"type": "STRING",
|
||||
"description": "Save path for screenshot"
|
||||
},
|
||||
"incognito": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Open in private/incognito mode"
|
||||
},
|
||||
"clear_first": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Clear field before typing (default: true)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"handler": browser_control,
|
||||
}
|
||||
+54
-6
@@ -115,10 +115,10 @@ _VALID_INTENTS = {"write", "edit", "explain", "run", "build", "screen_debug", "o
|
||||
|
||||
def _detect_intent(description: str, file_path: str, code: str) -> str:
|
||||
"""
|
||||
Dil bağımsız niyet tespiti — sabit anahtar kelime listesi YOK.
|
||||
Kullanıcı hangi dilde konuşursa konuşsun, açıklama Gemini'ye
|
||||
sınıflandırtılır. API'ye ulaşılamazsa dile bakmayan yapısal
|
||||
ipuçlarına (dosya diskte var mı, kod verilmiş mi) düşülür.
|
||||
Language-independent intent detection — NO fixed keyword list.
|
||||
Whatever language the user speaks, the description is classified by
|
||||
Gemini. If the API is unreachable, it falls back to language-agnostic
|
||||
structural hints (does the file exist on disk, was code provided).
|
||||
"""
|
||||
desc = (description or "").strip()
|
||||
file_exists = bool(file_path) and Path(file_path).exists()
|
||||
@@ -152,7 +152,7 @@ def _detect_intent(description: str, file_path: str, code: str) -> str:
|
||||
except Exception as e:
|
||||
print(f"[Code] Intent classification failed ({e}) — structural fallback")
|
||||
|
||||
# Yapısal geri dönüş — hiçbir dile bağlı değil
|
||||
# Structural fallback — not tied to any language
|
||||
if file_exists:
|
||||
return "edit" if desc else "explain"
|
||||
if code:
|
||||
@@ -581,4 +581,52 @@ def code_helper(
|
||||
return _screen_debug_action(description, file_path, player, speak)
|
||||
|
||||
else:
|
||||
return f"Unknown action: '{action}'. Use write, edit, explain, run, build, optimize, or screen_debug."
|
||||
return f"Unknown action: '{action}'. Use write, edit, explain, run, build, optimize, or screen_debug."
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "code_helper",
|
||||
"description": "Writes, edits, explains, runs, or builds code files.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "write | edit | explain | run | build | auto (default: auto)"
|
||||
},
|
||||
"description": {
|
||||
"type": "STRING",
|
||||
"description": "What the code should do or what change to make"
|
||||
},
|
||||
"language": {
|
||||
"type": "STRING",
|
||||
"description": "Programming language (default: python)"
|
||||
},
|
||||
"output_path": {
|
||||
"type": "STRING",
|
||||
"description": "Where to save the file"
|
||||
},
|
||||
"file_path": {
|
||||
"type": "STRING",
|
||||
"description": "Path to existing file for edit/explain/run/build"
|
||||
},
|
||||
"code": {
|
||||
"type": "STRING",
|
||||
"description": "Raw code string for explain"
|
||||
},
|
||||
"args": {
|
||||
"type": "STRING",
|
||||
"description": "CLI arguments for run/build"
|
||||
},
|
||||
"timeout": {
|
||||
"type": "INTEGER",
|
||||
"description": "Execution timeout in seconds (default: 30)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"handler": code_helper,
|
||||
}
|
||||
@@ -511,4 +511,80 @@ def computer_control(
|
||||
|
||||
except Exception as e:
|
||||
print(f"[ComputerControl] ❌ {action}: {e}")
|
||||
return f"computer_control '{action}' failed: {e}"
|
||||
return f"computer_control '{action}' failed: {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "computer_control",
|
||||
"description": "Direct computer control: type, click, hotkeys, scroll, move mouse, screenshots, find elements on screen.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "type | smart_type | click | double_click | right_click | hotkey | press | scroll | move | copy | paste | screenshot | wait | clear_field | focus_window | screen_find | screen_click | random_data | user_data"
|
||||
},
|
||||
"text": {
|
||||
"type": "STRING",
|
||||
"description": "Text to type or paste"
|
||||
},
|
||||
"x": {
|
||||
"type": "INTEGER",
|
||||
"description": "X coordinate"
|
||||
},
|
||||
"y": {
|
||||
"type": "INTEGER",
|
||||
"description": "Y coordinate"
|
||||
},
|
||||
"keys": {
|
||||
"type": "STRING",
|
||||
"description": "Key combination e.g. 'ctrl+c'"
|
||||
},
|
||||
"key": {
|
||||
"type": "STRING",
|
||||
"description": "Single key e.g. 'enter'"
|
||||
},
|
||||
"direction": {
|
||||
"type": "STRING",
|
||||
"description": "up | down | left | right"
|
||||
},
|
||||
"amount": {
|
||||
"type": "INTEGER",
|
||||
"description": "Scroll amount (default: 3)"
|
||||
},
|
||||
"seconds": {
|
||||
"type": "NUMBER",
|
||||
"description": "Seconds to wait"
|
||||
},
|
||||
"title": {
|
||||
"type": "STRING",
|
||||
"description": "Window title for focus_window"
|
||||
},
|
||||
"description": {
|
||||
"type": "STRING",
|
||||
"description": "Element description for screen_find/screen_click"
|
||||
},
|
||||
"type": {
|
||||
"type": "STRING",
|
||||
"description": "Data type for random_data"
|
||||
},
|
||||
"field": {
|
||||
"type": "STRING",
|
||||
"description": "Field for user_data: name|email|city"
|
||||
},
|
||||
"clear_first": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Clear field before typing (default: true)"
|
||||
},
|
||||
"path": {
|
||||
"type": "STRING",
|
||||
"description": "Save path for screenshot"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"handler": computer_control,
|
||||
}
|
||||
@@ -905,4 +905,58 @@ def computer_settings(
|
||||
push_undo("dark mode toggled",
|
||||
lambda: (dark_mode(), "Theme switched back.")[1])
|
||||
|
||||
return f"Done: {action}."
|
||||
return f"Done: {action}."
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "computer_settings",
|
||||
"description": "Controls the computer: volume, brightness, window management, keyboard shortcuts, typing text on screen, closing apps, fullscreen, dark mode, WiFi, restart, shutdown, scrolling, tab management, zoom, screenshots, lock screen, refresh/reload page. Use for ANY single computer control command. restart, shutdown and toggle_wifi put a confirmation on the user's screen and do NOT happen until they press it — never claim they are done. Volume, brightness and dark mode can be reversed with the `undo` tool.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
# The exact vocabulary, spelled out.
|
||||
#
|
||||
# This used to say only "The action to perform", so the model
|
||||
# usually filled `description` instead — and computer_settings then
|
||||
# made a SECOND Gemini call, inside the tool, purely to translate
|
||||
# that sentence into one of these names. Every "turn the volume
|
||||
# down" cost two model round trips.
|
||||
#
|
||||
# Naming the actions here costs ~600 characters once per session and
|
||||
# removes a whole round trip from every computer command.
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": (
|
||||
"The exact action. Prefer this over `description` — pick one of: "
|
||||
"volume_up | volume_down | volume_set | mute | "
|
||||
"brightness_up | brightness_down | sleep_display | "
|
||||
"pause_video | close_app | close_window | full_screen | "
|
||||
"minimize | maximize | snap_left | snap_right | "
|
||||
"switch_window | show_desktop | task_manager | focus_search | "
|
||||
"refresh_page | close_tab | new_tab | next_tab | prev_tab | "
|
||||
"go_back | go_forward | zoom_in | zoom_out | zoom_reset | "
|
||||
"find_on_page | scroll_up | scroll_down | scroll_top | "
|
||||
"scroll_bottom | page_up | page_down | copy | paste | cut | "
|
||||
"undo | redo | select_all | save | enter | escape | press_key | "
|
||||
"type_text | screenshot | lock_screen | open_settings | "
|
||||
"file_explorer | open_run | dark_mode | toggle_wifi | "
|
||||
"restart | shutdown"
|
||||
)
|
||||
},
|
||||
"description": {
|
||||
"type": "STRING",
|
||||
"description": (
|
||||
"Fallback only, when no action name above fits. "
|
||||
"Resolved locally — no extra model call."
|
||||
)
|
||||
},
|
||||
"value": {
|
||||
"type": "STRING",
|
||||
"description": "Optional value: volume level 0-100, text to type, key name, etc."
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
},
|
||||
"handler": computer_settings,
|
||||
}
|
||||
+37
-1
@@ -477,4 +477,40 @@ def desktop_control(
|
||||
|
||||
except Exception as e:
|
||||
print(f"[Desktop] Error: {e}")
|
||||
return f"Desktop control error: {e}"
|
||||
return f"Desktop control error: {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "desktop_control",
|
||||
"description": "Controls the desktop: wallpaper, organize, clean, list, stats.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "wallpaper | wallpaper_url | organize | clean | list | stats | task"
|
||||
},
|
||||
"path": {
|
||||
"type": "STRING",
|
||||
"description": "Image path for wallpaper"
|
||||
},
|
||||
"url": {
|
||||
"type": "STRING",
|
||||
"description": "Image URL for wallpaper_url"
|
||||
},
|
||||
"mode": {
|
||||
"type": "STRING",
|
||||
"description": "by_type or by_date for organize"
|
||||
},
|
||||
"task": {
|
||||
"type": "STRING",
|
||||
"description": "Natural language desktop task"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"handler": desktop_control,
|
||||
}
|
||||
+34
-2
@@ -324,7 +324,7 @@ def _run_project(run_command: str, project_dir: Path, timeout: int = 30) -> str:
|
||||
return f"Run error: {e}"
|
||||
|
||||
def _try_auto_install(error_output: str, project_dir: Path) -> bool:
|
||||
"""ModuleNotFoundError varsa eksik paketi otomatik kurmaya çalışır."""
|
||||
"""If there is a ModuleNotFoundError, tries to auto-install the missing package."""
|
||||
pattern = re.compile(
|
||||
r"No module named ['\"]([a-zA-Z0-9_\-\.]+)['\"]", re.IGNORECASE
|
||||
)
|
||||
@@ -599,4 +599,36 @@ def dev_agent(
|
||||
timeout = timeout,
|
||||
speak = speak,
|
||||
player = player,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "dev_agent",
|
||||
"description": "Builds complete multi-file projects from scratch: plans, writes files, installs deps, opens VSCode, runs and fixes errors.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"description": {
|
||||
"type": "STRING",
|
||||
"description": "What the project should do"
|
||||
},
|
||||
"language": {
|
||||
"type": "STRING",
|
||||
"description": "Programming language (default: python)"
|
||||
},
|
||||
"project_name": {
|
||||
"type": "STRING",
|
||||
"description": "Optional project folder name"
|
||||
},
|
||||
"timeout": {
|
||||
"type": "INTEGER",
|
||||
"description": "Run timeout in seconds (default: 30)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"description"
|
||||
]
|
||||
},
|
||||
"handler": dev_agent,
|
||||
}
|
||||
+54
-19
@@ -95,7 +95,7 @@ _SAFE_ROOTS: list[Path] = [
|
||||
]
|
||||
|
||||
def _is_safe_path(target: Path) -> bool:
|
||||
"""Verilen path _SAFE_ROOTS içinde mi? Değilse işlemi reddet."""
|
||||
"""Is the given path inside _SAFE_ROOTS? If not, reject the operation."""
|
||||
try:
|
||||
resolved = target.resolve()
|
||||
return any(
|
||||
@@ -158,22 +158,9 @@ def _resolve_path(raw: str) -> Path:
|
||||
"videos": _get_videos(),
|
||||
"home": Path.home(),
|
||||
}
|
||||
raw = raw.strip().strip('"').strip("'")
|
||||
lower = raw.lower()
|
||||
lower = raw.strip().lower()
|
||||
if lower in shortcuts:
|
||||
return shortcuts[lower]
|
||||
|
||||
# "desktop/notes/a.md" and "desktop\notes\a.md" — a shortcut followed by a
|
||||
# sub-path. Without this branch the whole string falls through to the
|
||||
# relative-path return below and is resolved against the process CWD instead
|
||||
# of the real Desktop: an "Access denied" when the project lives outside the
|
||||
# home directory, or — worse — a silent write into a stray "desktop" folder
|
||||
# inside the project when it lives inside it.
|
||||
head, sep, rest = raw.replace("\\", "/").partition("/")
|
||||
if sep and head.lower() in shortcuts:
|
||||
rest = rest.strip("/")
|
||||
return shortcuts[head.lower()] / rest if rest else shortcuts[head.lower()]
|
||||
|
||||
return Path(raw).expanduser()
|
||||
|
||||
def _format_size(b: int) -> str:
|
||||
@@ -275,7 +262,7 @@ def delete_file(path: str, name: str = "") -> str:
|
||||
if not target.exists():
|
||||
return f"Not found: {target.name}"
|
||||
|
||||
# Güvenli dizin kontrolü — kritik kullanıcı klasörlerini koru
|
||||
# Safe-directory check — protect critical user folders
|
||||
protected = {
|
||||
_get_desktop(), _get_downloads(), _get_documents(),
|
||||
_get_pictures(), _get_music(), _get_videos(), Path.home()
|
||||
@@ -461,7 +448,7 @@ def find_files(name: str = "", extension: str = "",
|
||||
|
||||
results = []
|
||||
dir_count = 0
|
||||
max_dirs = 500 # performans + güvenlik limiti
|
||||
max_dirs = 500 # performance + safety limit
|
||||
|
||||
for item in search_path.rglob("*"):
|
||||
if item.is_dir():
|
||||
@@ -556,7 +543,7 @@ def organize_desktop() -> str:
|
||||
|
||||
try:
|
||||
for item in desktop.iterdir():
|
||||
# Klasörlere, gizli dosyalara ve organize klasörlerine dokunma
|
||||
# Leave folders, hidden files and organize-folders untouched
|
||||
if item.is_dir() or item.name.startswith("."):
|
||||
continue
|
||||
if item.name in {k for k in type_map}:
|
||||
@@ -718,4 +705,52 @@ def file_controller(
|
||||
return f"Unknown action: '{action}'"
|
||||
|
||||
except Exception as e:
|
||||
return f"File controller error ({action}): {e}"
|
||||
return f"File controller error ({action}): {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "file_controller",
|
||||
"description": "Manages files and folders: list, create, delete, move, copy, rename, read, write, find, disk usage.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "list | create_file | create_folder | delete | move | copy | rename | read | write | find | largest | disk_usage | organize_desktop | info"
|
||||
},
|
||||
"path": {
|
||||
"type": "STRING",
|
||||
"description": "File/folder path or shortcut: desktop, downloads, documents, home"
|
||||
},
|
||||
"destination": {
|
||||
"type": "STRING",
|
||||
"description": "Destination path for move/copy"
|
||||
},
|
||||
"new_name": {
|
||||
"type": "STRING",
|
||||
"description": "New name for rename"
|
||||
},
|
||||
"content": {
|
||||
"type": "STRING",
|
||||
"description": "Content for create_file/write"
|
||||
},
|
||||
"name": {
|
||||
"type": "STRING",
|
||||
"description": "File name to search for"
|
||||
},
|
||||
"extension": {
|
||||
"type": "STRING",
|
||||
"description": "File extension to search (e.g. .pdf)"
|
||||
},
|
||||
"count": {
|
||||
"type": "INTEGER",
|
||||
"description": "Number of results for largest"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"action"
|
||||
]
|
||||
},
|
||||
"handler": file_controller,
|
||||
}
|
||||
@@ -833,4 +833,86 @@ def file_processor(parameters: dict, player=None, speak=None) -> str:
|
||||
except Exception as e:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return f"Processing failed: {e}"
|
||||
return f"Processing failed: {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "file_processor",
|
||||
"description": "Processes any file that the user has uploaded or dropped onto the interface. Use this when the user refers to an uploaded file and wants an action on it. Supports: images (describe/ocr/resize/compress/convert), PDFs (summarize/extract_text/to_word), Word docs & text files (summarize/fix/reformat/translate), CSV/Excel (analyze/stats/filter/sort/convert), JSON/XML (validate/format/analyze), code files (explain/review/fix/optimize/run/document/test), audio (transcribe/trim/convert/info), video (trim/extract_audio/extract_frame/compress/transcribe/info), archives (list/extract), presentations (summarize/extract_text). ALWAYS call this tool when a file has been uploaded and the user gives a command about it. If the user's command is ambiguous, pick the most logical action for that file type.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"file_path": {
|
||||
"type": "STRING",
|
||||
"description": "Full path to the uploaded file. Leave empty to use the currently uploaded file."
|
||||
},
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "What to do with the file. Examples by type:\nimage: describe | ocr | resize | compress | convert | info\npdf: summarize | extract_text | to_word | info\ndocx/txt: summarize | fix | reformat | translate_hint | word_count | to_bullet\ncsv/excel: analyze | stats | filter | sort | convert | info\njson: validate | format | analyze | to_csv\ncode: explain | review | fix | optimize | run | document | test\naudio: transcribe | trim | convert | info\nvideo: trim | extract_audio | extract_frame | compress | transcribe | info | convert\narchive: list | extract\npptx: summarize | extract_text | analyze"
|
||||
},
|
||||
"instruction": {
|
||||
"type": "STRING",
|
||||
"description": "Free-form instruction if action doesn't cover it. E.g. 'translate this to Turkish', 'find all email addresses'"
|
||||
},
|
||||
"format": {
|
||||
"type": "STRING",
|
||||
"description": "Target format for conversion. E.g. 'mp3', 'pdf', 'csv', 'png'"
|
||||
},
|
||||
"width": {
|
||||
"type": "INTEGER",
|
||||
"description": "Target width for image resize"
|
||||
},
|
||||
"height": {
|
||||
"type": "INTEGER",
|
||||
"description": "Target height for image resize"
|
||||
},
|
||||
"scale": {
|
||||
"type": "NUMBER",
|
||||
"description": "Scale factor for image resize (e.g. 0.5)"
|
||||
},
|
||||
"quality": {
|
||||
"type": "INTEGER",
|
||||
"description": "Quality 1-100 for image/video compress"
|
||||
},
|
||||
"start": {
|
||||
"type": "STRING",
|
||||
"description": "Start time for trim: seconds or HH:MM:SS"
|
||||
},
|
||||
"end": {
|
||||
"type": "STRING",
|
||||
"description": "End time for trim: seconds or HH:MM:SS"
|
||||
},
|
||||
"timestamp": {
|
||||
"type": "STRING",
|
||||
"description": "Timestamp for video frame extraction HH:MM:SS"
|
||||
},
|
||||
"column": {
|
||||
"type": "STRING",
|
||||
"description": "Column name for CSV filter/sort"
|
||||
},
|
||||
"value": {
|
||||
"type": "STRING",
|
||||
"description": "Filter value for CSV filter"
|
||||
},
|
||||
"condition": {
|
||||
"type": "STRING",
|
||||
"description": "Filter condition: equals|contains|gt|lt"
|
||||
},
|
||||
"ascending": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Sort order for CSV sort (default: true)"
|
||||
},
|
||||
"save": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Save result to file (default: true)"
|
||||
},
|
||||
"destination": {
|
||||
"type": "STRING",
|
||||
"description": "Output folder for archive extract"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
},
|
||||
"handler": file_processor,
|
||||
}
|
||||
@@ -27,14 +27,13 @@ _MONTH_MAP: dict[str, int] = {
|
||||
"january": 1, "february": 2, "march": 3, "april": 4,
|
||||
"may": 5, "june": 6, "july": 7, "august": 8,
|
||||
"september": 9, "october": 10, "november": 11, "december": 12,
|
||||
"ocak": 1, "şubat": 2, "mart": 3, "nisan": 4,
|
||||
"mayıs": 5, "haziran": 6, "temmuz": 7, "ağustos": 8,
|
||||
"eylül": 9, "ekim": 10, "kasım": 11, "aralık": 12,
|
||||
}
|
||||
|
||||
# English fast-path only — Gemini (below) normalizes date expressions in ANY
|
||||
# language to YYYY-MM-DD, so no other language needs to be hardcoded here.
|
||||
_RELATIVE_MAP_KEYS = {
|
||||
"today", "bugün",
|
||||
"tomorrow", "yarın",
|
||||
"today",
|
||||
"tomorrow",
|
||||
}
|
||||
|
||||
|
||||
@@ -53,9 +52,8 @@ def _parse_date(raw: str) -> str:
|
||||
pass
|
||||
|
||||
relative = {
|
||||
"today": today, "bugün": today,
|
||||
"today": today,
|
||||
"tomorrow": today + timedelta(days=1),
|
||||
"yarın": today + timedelta(days=1),
|
||||
}
|
||||
for key, val in relative.items():
|
||||
if key in lower:
|
||||
@@ -361,4 +359,50 @@ def flight_finder(parameters: dict, player=None, speak=None) -> str:
|
||||
|
||||
except Exception as e:
|
||||
print(f"[FlightFinder] ❌ {e}")
|
||||
return f"Flight search failed, sir: {e}"
|
||||
return f"Flight search failed, sir: {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "flight_finder",
|
||||
"description": "Searches Google Flights and speaks the best options.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"origin": {
|
||||
"type": "STRING",
|
||||
"description": "Departure city or airport code"
|
||||
},
|
||||
"destination": {
|
||||
"type": "STRING",
|
||||
"description": "Arrival city or airport code"
|
||||
},
|
||||
"date": {
|
||||
"type": "STRING",
|
||||
"description": "Departure date (any format)"
|
||||
},
|
||||
"return_date": {
|
||||
"type": "STRING",
|
||||
"description": "Return date for round trips"
|
||||
},
|
||||
"passengers": {
|
||||
"type": "INTEGER",
|
||||
"description": "Number of passengers (default: 1)"
|
||||
},
|
||||
"cabin": {
|
||||
"type": "STRING",
|
||||
"description": "economy | premium | business | first"
|
||||
},
|
||||
"save": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Save results to Notepad"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"origin",
|
||||
"destination",
|
||||
"date"
|
||||
]
|
||||
},
|
||||
"handler": flight_finder,
|
||||
}
|
||||
+66
-19
@@ -202,7 +202,7 @@ def _click_first_profile_by_screenshot() -> bool:
|
||||
time.sleep(1.5)
|
||||
win = _get_steam_window_rect()
|
||||
if not win:
|
||||
print("[GameUpdater] ⚠️ Steam penceresi bulunamadı")
|
||||
print("[GameUpdater] ⚠️ Steam window not found")
|
||||
return False
|
||||
|
||||
wx, wy, ww, wh = win
|
||||
@@ -220,7 +220,7 @@ def _click_first_profile_by_screenshot() -> bool:
|
||||
colorful = (max_c > 60) & ((max_c - min_c) > 40)
|
||||
|
||||
if not colorful.any():
|
||||
print("[GameUpdater] ⚠️ Avatar rengi bulunamadı — tahminle tıklanıyor")
|
||||
print("[GameUpdater] ⚠️ Avatar colour not found — clicking by guess")
|
||||
pyautogui.click(wx + ww // 2 - ww // 6, wy + wh // 2)
|
||||
return True
|
||||
|
||||
@@ -235,20 +235,20 @@ def _click_first_profile_by_screenshot() -> bool:
|
||||
|
||||
abs_x = wx + search_x1 + int(block_cols.mean())
|
||||
abs_y = wy + search_y1 + int(rows.mean())
|
||||
print(f"[GameUpdater] 🎯 Profil avatarı ({abs_x}, {abs_y}) — tıklanıyor")
|
||||
print(f"[GameUpdater] 🎯 Profile avatar ({abs_x}, {abs_y}) — clicking")
|
||||
pyautogui.click(abs_x, abs_y)
|
||||
return True
|
||||
|
||||
except ImportError as e:
|
||||
print(f"[GameUpdater] ⚠️ Eksik kütüphane: {e}")
|
||||
print(f"[GameUpdater] ⚠️ Missing library: {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[GameUpdater] ⚠️ Profil tespiti başarısız: {e}")
|
||||
print(f"[GameUpdater] ⚠️ Profile detection failed: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _handle_steam_profile_selection() -> bool:
|
||||
print("[GameUpdater] 🔍 Profil seçim dialogu kontrol ediliyor...")
|
||||
print("[GameUpdater] 🔍 Checking profile-selection dialog...")
|
||||
win = _get_steam_window_rect()
|
||||
if not win:
|
||||
return False
|
||||
@@ -266,14 +266,14 @@ def _handle_steam_profile_selection() -> bool:
|
||||
(top_region[:,:,2] > 200)
|
||||
))
|
||||
if not is_small and white_pixels <= 100:
|
||||
print("[GameUpdater] ℹ️ Profil dialogu yok — Steam zaten giriş yapmış")
|
||||
print("[GameUpdater] ℹ️ No profile dialog — Steam is already logged in")
|
||||
return False
|
||||
except ImportError:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print("[GameUpdater] 👤 Profil seçimi tespit edildi — ilk profile tıklanıyor")
|
||||
print("[GameUpdater] 👤 Profile selection detected — clicking the first profile")
|
||||
return _click_first_profile_by_screenshot()
|
||||
|
||||
def _find_best_drive() -> dict | None:
|
||||
@@ -298,7 +298,7 @@ def _select_drive_in_dialog(dialog, drive_letter: str) -> bool:
|
||||
for ctrl in dialog.descendants(control_type=control_type):
|
||||
if target in ctrl.window_text().upper():
|
||||
ctrl.click_input()
|
||||
print(f"[GameUpdater] ✅ Sürücü seçildi ({control_type}): {ctrl.window_text()}")
|
||||
print(f"[GameUpdater] ✅ Drive selected ({control_type}): {ctrl.window_text()}")
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
@@ -390,12 +390,17 @@ def _handle_install_dialog(game_name: str) -> str:
|
||||
|
||||
drive_letter = best_drive["letter"]
|
||||
drive_label = f"{drive_letter}:"
|
||||
print(f"[GameUpdater] 🏆 Hedef sürücü: {drive_label} ({best_drive['free_gb']:.1f} GB boş)")
|
||||
print(f"[GameUpdater] 🏆 Target drive: {drive_label} ({best_drive['free_gb']:.1f} GB free)")
|
||||
|
||||
try:
|
||||
from pywinauto import Application, findwindows
|
||||
dialog = None
|
||||
|
||||
# NOTE: this drives Steam's native installer dialog by matching its
|
||||
# on-screen button/title text, which is localized. We match English and
|
||||
# Turkish labels (install/yükle, next/ileri, ok/tamam). On a Steam client
|
||||
# set to another language the match simply fails and the automation
|
||||
# reports it — it never crashes, and manual install still works.
|
||||
for _ in range(40):
|
||||
time.sleep(0.5)
|
||||
try:
|
||||
@@ -423,7 +428,7 @@ def _handle_install_dialog(game_name: str) -> str:
|
||||
break
|
||||
|
||||
if not dialog:
|
||||
raise RuntimeError("Dialog bulunamadı")
|
||||
raise RuntimeError("Dialog not found")
|
||||
|
||||
dialog.set_focus()
|
||||
time.sleep(0.4)
|
||||
@@ -440,7 +445,7 @@ def _handle_install_dialog(game_name: str) -> str:
|
||||
except ImportError:
|
||||
return _handle_install_dialog_pyautogui(game_name, best_drive)
|
||||
except Exception as e:
|
||||
print(f"[GameUpdater] ⚠️ pywinauto başarısız: {e}")
|
||||
print(f"[GameUpdater] ⚠️ pywinauto failed: {e}")
|
||||
return _handle_install_dialog_pyautogui(game_name, best_drive)
|
||||
|
||||
def _ensure_steam_running(steam_path: Path) -> bool:
|
||||
@@ -449,10 +454,10 @@ def _ensure_steam_running(steam_path: Path) -> bool:
|
||||
|
||||
exe = _steam_exe(steam_path)
|
||||
if not exe.exists():
|
||||
print(f"[GameUpdater] ❌ Steam bulunamadı: {exe}")
|
||||
print(f"[GameUpdater] ❌ Steam not found: {exe}")
|
||||
return False
|
||||
|
||||
print("[GameUpdater] 🚀 Steam başlatılıyor...")
|
||||
print("[GameUpdater] 🚀 Starting Steam...")
|
||||
if is_mac():
|
||||
subprocess.Popen(["open", "-a", "Steam"])
|
||||
else:
|
||||
@@ -461,14 +466,14 @@ def _ensure_steam_running(steam_path: Path) -> bool:
|
||||
for _ in range(20):
|
||||
time.sleep(1)
|
||||
if _is_steam_running():
|
||||
print("[GameUpdater] ✅ Steam çalışıyor")
|
||||
print("[GameUpdater] ✅ Steam is running")
|
||||
time.sleep(4)
|
||||
if is_windows():
|
||||
_handle_steam_profile_selection()
|
||||
time.sleep(2)
|
||||
return True
|
||||
|
||||
print("[GameUpdater] ⚠️ Steam başlatılamadı")
|
||||
print("[GameUpdater] ⚠️ Could not start Steam")
|
||||
return False
|
||||
|
||||
def _search_steam_appid(game_name: str) -> tuple[str | None, str | None]:
|
||||
@@ -488,7 +493,7 @@ def _search_steam_appid(game_name: str) -> tuple[str | None, str | None]:
|
||||
|
||||
for key, (app_id, canonical) in _KNOWN_APPIDS.items():
|
||||
if name_lower in key or key in name_lower:
|
||||
print(f"[GameUpdater] 📖 Kısmi eşleşme: {canonical} ({app_id})")
|
||||
print(f"[GameUpdater] 📖 Partial match: {canonical} ({app_id})")
|
||||
return app_id, canonical
|
||||
|
||||
try:
|
||||
@@ -503,7 +508,7 @@ def _search_steam_appid(game_name: str) -> tuple[str | None, str | None]:
|
||||
print(f"[GameUpdater] 🌐 Store API: {best['name']} ({best['id']})")
|
||||
return str(best["id"]), best["name"]
|
||||
except Exception as e:
|
||||
print(f"[GameUpdater] ⚠️ AppID arama başarısız: {e}")
|
||||
print(f"[GameUpdater] ⚠️ AppID lookup failed: {e}")
|
||||
|
||||
return None, None
|
||||
|
||||
@@ -1051,4 +1056,46 @@ if __name__ == "__main__":
|
||||
if "--scheduled" in sys.argv:
|
||||
print(f"[GameUpdater] 🕐 Scheduled run at {datetime.now().strftime('%H:%M')}")
|
||||
result = game_updater({"action": "update", "platform": "both"})
|
||||
print(f"[GameUpdater] ✅ {result}")
|
||||
print(f"[GameUpdater] ✅ {result}")
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "game_updater",
|
||||
"description": "THE ONLY tool for ANY Steam or Epic Games request. Use for: installing, downloading, updating games, listing installed games, checking download status, scheduling updates. ALWAYS call directly for any Steam/Epic/game request. NEVER use browser_control or web_search for Steam/Epic.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "update | install | list | download_status | schedule | cancel_schedule | schedule_status (default: update)"
|
||||
},
|
||||
"platform": {
|
||||
"type": "STRING",
|
||||
"description": "steam | epic | both (default: both)"
|
||||
},
|
||||
"game_name": {
|
||||
"type": "STRING",
|
||||
"description": "Game name (partial match supported)"
|
||||
},
|
||||
"app_id": {
|
||||
"type": "STRING",
|
||||
"description": "Steam AppID for install (optional)"
|
||||
},
|
||||
"hour": {
|
||||
"type": "INTEGER",
|
||||
"description": "Hour for scheduled update 0-23 (default: 3)"
|
||||
},
|
||||
"minute": {
|
||||
"type": "INTEGER",
|
||||
"description": "Minute for scheduled update 0-59 (default: 0)"
|
||||
},
|
||||
"shutdown_when_done": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Shut down PC when download finishes"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
},
|
||||
"handler": game_updater,
|
||||
}
|
||||
+21
-1
@@ -270,4 +270,24 @@ def open_app(
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"[open_app] Error: {e}")
|
||||
return f"Failed to open {app_name}: {e}"
|
||||
return f"Failed to open {app_name}: {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "open_app",
|
||||
"description": "Opens any application on the computer. Use this whenever the user asks to open, launch, or start any app, website, or program. Always call this tool — never just say you opened it.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"app_name": {
|
||||
"type": "STRING",
|
||||
"description": "Exact name of the application (e.g. 'WhatsApp', 'Chrome', 'Spotify')"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"app_name"
|
||||
]
|
||||
},
|
||||
"handler": open_app,
|
||||
}
|
||||
+31
-1
@@ -334,4 +334,34 @@ def reminder(
|
||||
player.write_log(f"[Reminder] ✅ {date_str} {time_str} — {safe_msg[:40]}")
|
||||
|
||||
friendly_time = target_dt.strftime("%B %d at %I:%M %p")
|
||||
return f"Reminder set for {friendly_time}."
|
||||
return f"Reminder set for {friendly_time}."
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "reminder",
|
||||
"description": "Sets a timed reminder using Task Scheduler.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"date": {
|
||||
"type": "STRING",
|
||||
"description": "Date in YYYY-MM-DD format"
|
||||
},
|
||||
"time": {
|
||||
"type": "STRING",
|
||||
"description": "Time in HH:MM format (24h)"
|
||||
},
|
||||
"message": {
|
||||
"type": "STRING",
|
||||
"description": "Reminder message text"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"date",
|
||||
"time",
|
||||
"message"
|
||||
]
|
||||
},
|
||||
"handler": reminder,
|
||||
}
|
||||
+183
-464
@@ -1,464 +1,183 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import base64
|
||||
import io
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
import sounddevice as sd
|
||||
|
||||
try:
|
||||
import cv2
|
||||
_CV2 = True
|
||||
except ImportError:
|
||||
_CV2 = False
|
||||
|
||||
try:
|
||||
import mss
|
||||
import mss.tools
|
||||
_MSS = True
|
||||
except ImportError:
|
||||
_MSS = False
|
||||
|
||||
try:
|
||||
import PIL.Image
|
||||
_PIL = True
|
||||
except ImportError:
|
||||
_PIL = False
|
||||
|
||||
from google import genai
|
||||
from google.genai import types as gtypes
|
||||
|
||||
def _base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
_BASE = _base_dir()
|
||||
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
||||
|
||||
|
||||
def _load_config() -> dict:
|
||||
try:
|
||||
return json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_config_key(key: str, value) -> None:
|
||||
try:
|
||||
cfg = _load_config()
|
||||
cfg[key] = value
|
||||
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
key = _load_config().get("gemini_api_key", "")
|
||||
if not key:
|
||||
raise RuntimeError("gemini_api_key not found in config.")
|
||||
return key
|
||||
|
||||
|
||||
def _get_os() -> str:
|
||||
return _load_config().get("os_system", "windows").lower()
|
||||
|
||||
_LIVE_MODEL = "models/gemini-2.5-flash-native-audio-preview-12-2025"
|
||||
_CHANNELS = 1
|
||||
_RECEIVE_SAMPLE_RATE = 24_000
|
||||
_CHUNK_SIZE = 1_024
|
||||
|
||||
_IMG_MAX_W = 1280
|
||||
_IMG_MAX_H = 720
|
||||
_JPEG_Q = 82
|
||||
|
||||
_SYSTEM_PROMPT = (
|
||||
"You are JARVIS, Tony Stark's AI assistant. "
|
||||
"You are given an image from either the user's screen or their webcam. "
|
||||
"Analyze what you see with detail and intelligence. "
|
||||
"Describe objects, text, people, components, and their context clearly. "
|
||||
"For technical questions (circuits, code, hardware) give specific, expert answers. "
|
||||
"Be concise — 2-4 sentences — unless the question demands more detail. "
|
||||
"Speak directly to the user ('I can see...', 'You have...'). "
|
||||
"Address the user as 'sir' depending on the language they used."
|
||||
)
|
||||
|
||||
|
||||
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
||||
if not _PIL:
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
|
||||
try:
|
||||
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
|
||||
def _capture_screen() -> tuple[bytes, str]:
|
||||
|
||||
if not _MSS:
|
||||
raise RuntimeError("mss is not installed. Run: pip install mss")
|
||||
|
||||
with mss.mss() as sct:
|
||||
monitors = sct.monitors # [0] = all combined, [1..n] = real screens
|
||||
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
||||
shot = sct.grab(target)
|
||||
png = mss.tools.to_png(shot.rgb, shot.size)
|
||||
|
||||
return _compress(png, "PNG")
|
||||
|
||||
|
||||
def _cv2_backend() -> int:
|
||||
"""Return the best OpenCV camera backend for the current OS."""
|
||||
if not _CV2:
|
||||
return 0
|
||||
os_name = _get_os()
|
||||
if os_name == "windows":
|
||||
return cv2.CAP_DSHOW
|
||||
if os_name == "mac":
|
||||
return cv2.CAP_AVFOUNDATION
|
||||
return cv2.CAP_ANY
|
||||
|
||||
|
||||
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
||||
|
||||
if not _CV2:
|
||||
return False
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
if not cap.isOpened():
|
||||
cap.release()
|
||||
return False
|
||||
for _ in range(warmup):
|
||||
cap.read()
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
if not ret or frame is None:
|
||||
return False
|
||||
return bool(np.mean(frame) > 8)
|
||||
|
||||
|
||||
def _detect_camera_index() -> int:
|
||||
|
||||
backend = _cv2_backend()
|
||||
print("[Vision] 🔍 Auto-detecting camera...")
|
||||
for idx in range(6):
|
||||
if _probe_camera(idx, backend):
|
||||
print(f"[Vision] ✅ Camera found at index {idx}")
|
||||
_save_config_key("camera_index", idx)
|
||||
return idx
|
||||
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
||||
|
||||
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
||||
_save_config_key("camera_index", 0)
|
||||
return 0
|
||||
|
||||
|
||||
def _get_camera_index() -> int:
|
||||
cfg = _load_config()
|
||||
if "camera_index" in cfg:
|
||||
return int(cfg["camera_index"])
|
||||
return _detect_camera_index()
|
||||
|
||||
|
||||
def _capture_camera() -> tuple[bytes, str]:
|
||||
if not _CV2:
|
||||
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
||||
|
||||
index = _get_camera_index()
|
||||
backend = _cv2_backend()
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
|
||||
if not cap.isOpened():
|
||||
raise RuntimeError(f"Camera index {index} could not be opened.")
|
||||
|
||||
for _ in range(10):
|
||||
cap.read()
|
||||
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
|
||||
if not ret or frame is None:
|
||||
raise RuntimeError("Camera returned no frame.")
|
||||
|
||||
if _PIL:
|
||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
img = PIL.Image.fromarray(rgb)
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
|
||||
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
||||
return buf.tobytes(), "image/jpeg"
|
||||
|
||||
class _VisionSession:
|
||||
def __init__(self):
|
||||
self._loop: Optional[asyncio.AbstractEventLoop] = None
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
self._session = None
|
||||
self._out_queue: Optional[asyncio.Queue] = None
|
||||
self._audio_in: Optional[asyncio.Queue] = None
|
||||
self._ready_evt: threading.Event = threading.Event()
|
||||
self._player = None
|
||||
self._lock: threading.Lock = threading.Lock()
|
||||
|
||||
def start(self, player=None, timeout: float = 25.0) -> None:
|
||||
with self._lock:
|
||||
if self._thread and self._thread.is_alive():
|
||||
if player is not None:
|
||||
self._player = player
|
||||
return
|
||||
self._player = player
|
||||
self._thread = threading.Thread(
|
||||
target=self._run_event_loop,
|
||||
daemon=True,
|
||||
name="VisionSessionThread",
|
||||
)
|
||||
self._thread.start()
|
||||
|
||||
if not self._ready_evt.wait(timeout=timeout):
|
||||
raise RuntimeError(f"Vision session did not connect within {timeout}s.")
|
||||
print("[Vision] ✅ Session ready")
|
||||
|
||||
def analyze(self, image_bytes: bytes, mime_type: str, user_text: str) -> None:
|
||||
if not self._loop or not self._out_queue:
|
||||
print("[Vision] ⚠️ Session not started — dropping request")
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(
|
||||
self._out_queue.put((image_bytes, mime_type, user_text)),
|
||||
self._loop,
|
||||
)
|
||||
|
||||
def is_ready(self) -> bool:
|
||||
return self._session is not None
|
||||
|
||||
def _run_event_loop(self) -> None:
|
||||
self._loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(self._loop)
|
||||
self._loop.run_until_complete(self._session_loop())
|
||||
|
||||
async def _session_loop(self) -> None:
|
||||
self._out_queue = asyncio.Queue(maxsize=30)
|
||||
self._audio_in = asyncio.Queue()
|
||||
|
||||
client = genai.Client(
|
||||
api_key=_get_api_key(),
|
||||
http_options={"api_version": "v1beta"},
|
||||
)
|
||||
config = gtypes.LiveConnectConfig(
|
||||
response_modalities=["AUDIO"],
|
||||
output_audio_transcription={},
|
||||
system_instruction=_SYSTEM_PROMPT,
|
||||
speech_config=gtypes.SpeechConfig(
|
||||
voice_config=gtypes.VoiceConfig(
|
||||
prebuilt_voice_config=gtypes.PrebuiltVoiceConfig(
|
||||
voice_name="Charon"
|
||||
)
|
||||
)
|
||||
),
|
||||
)
|
||||
|
||||
backoff = 2.0
|
||||
while True:
|
||||
try:
|
||||
print("[Vision] 🔌 Connecting...")
|
||||
async with client.aio.live.connect(
|
||||
model=_LIVE_MODEL, config=config
|
||||
) as session:
|
||||
self._session = session
|
||||
self._ready_evt.set()
|
||||
backoff = 2.0
|
||||
print("[Vision] ✅ Connected")
|
||||
|
||||
async with asyncio.TaskGroup() as tg:
|
||||
tg.create_task(self._send_loop())
|
||||
tg.create_task(self._recv_loop())
|
||||
tg.create_task(self._play_loop())
|
||||
|
||||
except* Exception as eg:
|
||||
for exc in eg.exceptions:
|
||||
print(f"[Vision] ⚠️ Session error: {exc}")
|
||||
finally:
|
||||
self._session = None
|
||||
self._ready_evt.clear()
|
||||
|
||||
print(f"[Vision] 🔄 Reconnecting in {backoff:.0f}s...")
|
||||
await asyncio.sleep(backoff)
|
||||
backoff = min(backoff * 1.5, 30.0)
|
||||
self._ready_evt.set()
|
||||
|
||||
async def _send_loop(self) -> None:
|
||||
while True:
|
||||
image_bytes, mime_type, user_text = await self._out_queue.get()
|
||||
if not self._session:
|
||||
print("[Vision] ⚠️ No session — dropping image")
|
||||
continue
|
||||
try:
|
||||
b64 = base64.b64encode(image_bytes).decode("ascii")
|
||||
await self._session.send_client_content(
|
||||
turns={
|
||||
"parts": [
|
||||
{"inline_data": {"mime_type": mime_type, "data": b64}},
|
||||
{"text": user_text},
|
||||
]
|
||||
},
|
||||
turn_complete=True,
|
||||
)
|
||||
print(f"[Vision] 📤 Sent {len(image_bytes):,} bytes — '{user_text[:60]}'")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Send error: {e}")
|
||||
raise # propagate to TaskGroup → triggers session reconnect
|
||||
|
||||
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 = []
|
||||
# Auto-close camera ~2s after JARVIS finishes speaking
|
||||
if self._player and hasattr(self._player, "stop_camera_stream"):
|
||||
async def _deferred_close():
|
||||
await asyncio.sleep(2.0)
|
||||
try:
|
||||
self._player.stop_camera_stream()
|
||||
except Exception:
|
||||
pass
|
||||
asyncio.create_task(_deferred_close())
|
||||
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Recv error: {e}")
|
||||
raise
|
||||
|
||||
async def _play_loop(self) -> None:
|
||||
stream = sd.RawOutputStream(
|
||||
samplerate=_RECEIVE_SAMPLE_RATE,
|
||||
channels=_CHANNELS,
|
||||
dtype="int16",
|
||||
blocksize=_CHUNK_SIZE,
|
||||
)
|
||||
stream.start()
|
||||
try:
|
||||
while True:
|
||||
chunk = await self._audio_in.get()
|
||||
await asyncio.to_thread(stream.write, chunk)
|
||||
except Exception as e:
|
||||
print(f"[Vision] ❌ Play error: {e}")
|
||||
raise
|
||||
finally:
|
||||
stream.stop()
|
||||
stream.close()
|
||||
|
||||
_session = _VisionSession()
|
||||
_session_lock = threading.Lock()
|
||||
_session_up = False
|
||||
|
||||
|
||||
def _ensure_session(player=None) -> None:
|
||||
global _session_up
|
||||
with _session_lock:
|
||||
if not _session_up:
|
||||
_session.start(player=player)
|
||||
_session_up = True
|
||||
elif player is not None:
|
||||
_session._player = player
|
||||
|
||||
|
||||
def screen_process(
|
||||
parameters: dict,
|
||||
response=None,
|
||||
player=None,
|
||||
session_memory=None,
|
||||
) -> bool:
|
||||
|
||||
params = parameters or {}
|
||||
user_text = (params.get("text") or params.get("user_text") or "").strip()
|
||||
angle = params.get("angle", "screen").lower().strip()
|
||||
|
||||
if not user_text:
|
||||
print("[Vision] ⚠️ No question provided — aborting")
|
||||
return False
|
||||
|
||||
print(f"[Vision] ▶ angle={angle!r} question='{user_text[:80]}'")
|
||||
|
||||
try:
|
||||
_ensure_session(player=player)
|
||||
except Exception as e:
|
||||
print(f"[Vision] ❌ Could not start session: {e}")
|
||||
return False
|
||||
|
||||
try:
|
||||
if angle == "camera":
|
||||
image_bytes, mime_type = _capture_camera()
|
||||
print(f"[Vision] 📷 Camera: {len(image_bytes):,} bytes")
|
||||
if player and hasattr(player, "start_camera_stream"):
|
||||
try:
|
||||
player.start_camera_stream()
|
||||
except Exception as _e:
|
||||
print(f"[Vision] ⚠️ Camera stream failed: {_e}")
|
||||
elif player and hasattr(player, "show_camera_frame"):
|
||||
try:
|
||||
player.show_camera_frame(image_bytes)
|
||||
except Exception as _e:
|
||||
print(f"[Vision] ⚠️ Camera preview failed: {_e}")
|
||||
else:
|
||||
image_bytes, mime_type = _capture_screen()
|
||||
print(f"[Vision] 🖥️ Screen: {len(image_bytes):,} bytes")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ❌ Capture error: {e}")
|
||||
return False
|
||||
|
||||
_session.analyze(image_bytes, mime_type, user_text)
|
||||
return True
|
||||
|
||||
|
||||
def warmup_session(player=None) -> None:
|
||||
try:
|
||||
_ensure_session(player=player)
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Warmup failed: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("[TEST] screen_processor.py")
|
||||
print("=" * 52)
|
||||
mode = input("angle — screen / camera (default: screen): ").strip().lower() or "screen"
|
||||
q = input("Question (Enter = default): ").strip() or "What do you see? Be brief."
|
||||
|
||||
t0 = time.perf_counter()
|
||||
warmup_session()
|
||||
print(f"Session ready in {time.perf_counter()-t0:.2f}s\n")
|
||||
|
||||
t1 = time.perf_counter()
|
||||
ok = screen_process({"angle": mode, "text": q})
|
||||
print(f"Queued in {time.perf_counter()-t1:.3f}s — waiting for audio...")
|
||||
time.sleep(10)
|
||||
print("Done." if ok else "Failed.")
|
||||
"""
|
||||
Screen & webcam capture for JARVIS vision.
|
||||
|
||||
Provides the two capture entry points main.py uses — `_capture_screen()` and
|
||||
`_capture_camera()` — plus their helpers (compression, camera auto-detection,
|
||||
config access). main.py grabs a frame here on demand, then injects it into the
|
||||
main Gemini Live session; there is no separate vision session here.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
try:
|
||||
import cv2
|
||||
_CV2 = True
|
||||
except ImportError:
|
||||
_CV2 = False
|
||||
|
||||
try:
|
||||
import mss
|
||||
import mss.tools
|
||||
_MSS = True
|
||||
except ImportError:
|
||||
_MSS = False
|
||||
|
||||
try:
|
||||
import PIL.Image
|
||||
_PIL = True
|
||||
except ImportError:
|
||||
_PIL = False
|
||||
|
||||
|
||||
def _base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
return Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
_BASE = _base_dir()
|
||||
_CONFIG_PATH = _BASE / "config" / "api_keys.json"
|
||||
|
||||
|
||||
def _load_config() -> dict:
|
||||
try:
|
||||
return json.loads(_CONFIG_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _save_config_key(key: str, value) -> None:
|
||||
try:
|
||||
cfg = _load_config()
|
||||
cfg[key] = value
|
||||
_CONFIG_PATH.write_text(json.dumps(cfg, indent=4), encoding="utf-8")
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Could not save config key '{key}': {e}")
|
||||
|
||||
|
||||
def _get_os() -> str:
|
||||
return _load_config().get("os_system", "windows").lower()
|
||||
|
||||
|
||||
_IMG_MAX_W = 1280
|
||||
_IMG_MAX_H = 720
|
||||
_JPEG_Q = 82
|
||||
|
||||
|
||||
def _compress(img_bytes: bytes, source_format: str = "PNG") -> tuple[bytes, str]:
|
||||
if not _PIL:
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
|
||||
try:
|
||||
img = PIL.Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q, optimize=False)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
except Exception as e:
|
||||
print(f"[Vision] ⚠️ Image compress failed: {e}")
|
||||
return img_bytes, f"image/{source_format.lower()}"
|
||||
|
||||
|
||||
def _capture_screen() -> tuple[bytes, str]:
|
||||
|
||||
if not _MSS:
|
||||
raise RuntimeError("mss is not installed. Run: pip install mss")
|
||||
|
||||
with mss.mss() as sct:
|
||||
monitors = sct.monitors # [0] = all combined, [1..n] = real screens
|
||||
target = monitors[1] if len(monitors) > 1 else monitors[0]
|
||||
shot = sct.grab(target)
|
||||
png = mss.tools.to_png(shot.rgb, shot.size)
|
||||
|
||||
return _compress(png, "PNG")
|
||||
|
||||
|
||||
def _cv2_backend() -> int:
|
||||
"""Return the best OpenCV camera backend for the current OS."""
|
||||
if not _CV2:
|
||||
return 0
|
||||
os_name = _get_os()
|
||||
if os_name == "windows":
|
||||
return cv2.CAP_DSHOW
|
||||
if os_name == "mac":
|
||||
return cv2.CAP_AVFOUNDATION
|
||||
return cv2.CAP_ANY
|
||||
|
||||
|
||||
def _probe_camera(index: int, backend: int, warmup: int = 5) -> bool:
|
||||
|
||||
if not _CV2:
|
||||
return False
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
if not cap.isOpened():
|
||||
cap.release()
|
||||
return False
|
||||
for _ in range(warmup):
|
||||
cap.read()
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
if not ret or frame is None:
|
||||
return False
|
||||
return bool(np.mean(frame) > 8)
|
||||
|
||||
|
||||
def _detect_camera_index() -> int:
|
||||
|
||||
backend = _cv2_backend()
|
||||
print("[Vision] 🔍 Auto-detecting camera...")
|
||||
for idx in range(6):
|
||||
if _probe_camera(idx, backend):
|
||||
print(f"[Vision] ✅ Camera found at index {idx}")
|
||||
_save_config_key("camera_index", idx)
|
||||
return idx
|
||||
print(f"[Vision] ⚠️ Camera index {idx}: no usable frame")
|
||||
|
||||
print("[Vision] ⚠️ No camera found — defaulting to index 0")
|
||||
_save_config_key("camera_index", 0)
|
||||
return 0
|
||||
|
||||
|
||||
def _get_camera_index() -> int:
|
||||
cfg = _load_config()
|
||||
if "camera_index" in cfg:
|
||||
return int(cfg["camera_index"])
|
||||
return _detect_camera_index()
|
||||
|
||||
|
||||
def _capture_camera() -> tuple[bytes, str]:
|
||||
if not _CV2:
|
||||
raise RuntimeError("OpenCV (cv2) is not installed. Run: pip install opencv-python")
|
||||
|
||||
index = _get_camera_index()
|
||||
backend = _cv2_backend()
|
||||
cap = cv2.VideoCapture(index, backend)
|
||||
|
||||
if not cap.isOpened():
|
||||
raise RuntimeError(f"Camera index {index} could not be opened.")
|
||||
|
||||
for _ in range(10):
|
||||
cap.read()
|
||||
|
||||
ret, frame = cap.read()
|
||||
cap.release()
|
||||
|
||||
if not ret or frame is None:
|
||||
raise RuntimeError("Camera returned no frame.")
|
||||
|
||||
if _PIL:
|
||||
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
img = PIL.Image.fromarray(rgb)
|
||||
img.thumbnail((_IMG_MAX_W, _IMG_MAX_H), PIL.Image.BILINEAR)
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="JPEG", quality=_JPEG_Q)
|
||||
return buf.getvalue(), "image/jpeg"
|
||||
|
||||
_, buf = cv2.imencode(".jpg", frame, [cv2.IMWRITE_JPEG_QUALITY, _JPEG_Q])
|
||||
return buf.tobytes(), "image/jpeg"
|
||||
+31
-1
@@ -263,4 +263,34 @@ def send_message(
|
||||
if player:
|
||||
player.write_log(f"[msg] {result}")
|
||||
|
||||
return result
|
||||
return result
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "send_message",
|
||||
"description": "Sends a text message via WhatsApp, Telegram, or other messaging platform.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"receiver": {
|
||||
"type": "STRING",
|
||||
"description": "Recipient contact name"
|
||||
},
|
||||
"message_text": {
|
||||
"type": "STRING",
|
||||
"description": "The message to send"
|
||||
},
|
||||
"platform": {
|
||||
"type": "STRING",
|
||||
"description": "Platform: WhatsApp, Telegram, etc."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"receiver",
|
||||
"message_text",
|
||||
"platform"
|
||||
]
|
||||
},
|
||||
"handler": send_message,
|
||||
}
|
||||
@@ -48,4 +48,24 @@ def _log(message: str, player=None) -> None:
|
||||
try:
|
||||
player.write_log(f"JARVIS: {message}")
|
||||
except Exception:
|
||||
pass
|
||||
pass
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "weather_report",
|
||||
"description": "Gives the weather report to user",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"city": {
|
||||
"type": "STRING",
|
||||
"description": "City name"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"city"
|
||||
]
|
||||
},
|
||||
"handler": weather_action,
|
||||
}
|
||||
+96
-131
@@ -1,68 +1,8 @@
|
||||
#web_search.py
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# ── Gemini grounding quota circuit breaker ────────────────────────────────────
|
||||
# The google_search grounding tool has its own small quota, separate from plain
|
||||
# generation. Once it is spent every call returns 429 — so retrying it at the
|
||||
# top of every search only adds a dead round-trip before the DDG fallback runs.
|
||||
# After a quota error, skip Gemini entirely for a cooldown period.
|
||||
_QUOTA_COOLDOWN_SEC = 900 # 15 minutes
|
||||
_quota_blocked_until = 0.0
|
||||
_quota_lock = threading.Lock()
|
||||
|
||||
|
||||
def _gemini_available() -> bool:
|
||||
with _quota_lock:
|
||||
return time.monotonic() >= _quota_blocked_until
|
||||
|
||||
|
||||
def _note_gemini_error(exc: Exception) -> None:
|
||||
"""Trip the breaker when the error is a quota / rate-limit rejection."""
|
||||
global _quota_blocked_until
|
||||
msg = str(exc)
|
||||
if "429" in msg or "RESOURCE_EXHAUSTED" in msg:
|
||||
with _quota_lock:
|
||||
already = time.monotonic() < _quota_blocked_until
|
||||
_quota_blocked_until = time.monotonic() + _QUOTA_COOLDOWN_SEC
|
||||
if not already:
|
||||
print(
|
||||
"[WebSearch] Gemini grounding quota exhausted — skipping it for "
|
||||
f"{_QUOTA_COOLDOWN_SEC // 60} min and serving results from DDG."
|
||||
)
|
||||
|
||||
|
||||
class _QuotaCooldown(RuntimeError):
|
||||
"""Raised instead of calling Gemini while the quota breaker is open."""
|
||||
|
||||
|
||||
def _log_gemini_failure(context: str, exc: Exception) -> None:
|
||||
"""Log a Gemini failure — silently when it is just the expected cooldown."""
|
||||
if isinstance(exc, _QuotaCooldown):
|
||||
return # announced once when the breaker tripped; not a warning
|
||||
print(f"[WebSearch] \u26a0\ufe0f {context} failed ({exc}) — using DDG instead")
|
||||
|
||||
|
||||
def _run_bounded(fn, timeout: float, label: str = "task"):
|
||||
"""Run fn() in a daemon thread; return its result, or None if it overruns."""
|
||||
box = [None]
|
||||
|
||||
def _run():
|
||||
try:
|
||||
box[0] = fn()
|
||||
except Exception as e:
|
||||
_log_gemini_failure(label, e)
|
||||
|
||||
t = threading.Thread(target=_run, daemon=True)
|
||||
t.start()
|
||||
t.join(timeout)
|
||||
if t.is_alive():
|
||||
print(f"[WebSearch] {label} exceeded {timeout:.0f}s — moving on")
|
||||
return box[0]
|
||||
|
||||
def _get_base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
@@ -79,21 +19,14 @@ def _get_api_key() -> str:
|
||||
|
||||
|
||||
def _gemini_search(query: str) -> str:
|
||||
if not _gemini_available():
|
||||
raise _QuotaCooldown("Gemini grounding is in quota cooldown")
|
||||
|
||||
from google import genai
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
try:
|
||||
response = client.models.generate_content(
|
||||
model="gemini-flash-latest",
|
||||
contents=query,
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
)
|
||||
except Exception as e:
|
||||
_note_gemini_error(e)
|
||||
raise
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
response = client.models.generate_content(
|
||||
model="gemini-flash-latest",
|
||||
contents=query,
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
)
|
||||
|
||||
text = ""
|
||||
for part in response.candidates[0].content.parts:
|
||||
@@ -106,45 +39,30 @@ def _gemini_search(query: str) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def _get_ddgs():
|
||||
"""
|
||||
Returns the DDGS class. The package was renamed duckduckgo-search -> ddgs;
|
||||
the legacy package's endpoints are now rejected by DuckDuckGo (news() gets a
|
||||
403 Ratelimit, text() silently returns zero results), so warn loudly if we
|
||||
end up on it instead of failing in silence.
|
||||
"""
|
||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
return DDGS
|
||||
except ImportError:
|
||||
from duckduckgo_search import DDGS
|
||||
print(
|
||||
"[WebSearch] ⚠️ Using the deprecated 'duckduckgo-search' package — "
|
||||
"DuckDuckGo blocks its endpoints, so every search will come back "
|
||||
"empty. Fix with: pip install -U ddgs"
|
||||
)
|
||||
return DDGS
|
||||
|
||||
|
||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||
DDGS = _get_ddgs()
|
||||
results = []
|
||||
try:
|
||||
with DDGS() as ddgs:
|
||||
for r in ddgs.text(query, max_results=max_results):
|
||||
results.append({
|
||||
"title": r.get("title", ""),
|
||||
"snippet": r.get("body", ""),
|
||||
"url": r.get("href", ""),
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG text() failed: {e}")
|
||||
with DDGS() as ddgs:
|
||||
for r in ddgs.text(query, max_results=max_results):
|
||||
results.append({
|
||||
"title": r.get("title", ""),
|
||||
"snippet": r.get("body", ""),
|
||||
"url": r.get("href", ""),
|
||||
})
|
||||
return results
|
||||
|
||||
|
||||
def _ddg_news(query: str, max_results: int = 8) -> list[dict]:
|
||||
"""DDG news search — returns actual articles, not website homepages."""
|
||||
DDGS = _get_ddgs()
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
except ImportError:
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
results = []
|
||||
try:
|
||||
with DDGS() as ddgs:
|
||||
@@ -157,9 +75,6 @@ def _ddg_news(query: str, max_results: int = 8) -> list[dict]:
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG news() failed ({e}) — falling back to text search")
|
||||
# Also covers the legacy-package case, where news() returns an empty list
|
||||
# instead of raising.
|
||||
if not results:
|
||||
results = _ddg_search(query, max_results=max_results)
|
||||
return results
|
||||
|
||||
@@ -242,43 +157,58 @@ def _search(query: str) -> str:
|
||||
try:
|
||||
return _gemini_search(query)
|
||||
except Exception as e:
|
||||
_log_gemini_failure("Gemini search", e)
|
||||
print(f"[WebSearch] ⚠️ Gemini failed ({e}) — trying DDG...")
|
||||
results = _ddg_search(query)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
|
||||
def _news(query: str) -> str:
|
||||
"""
|
||||
DDG first, Gemini as backup.
|
||||
|
||||
The old version raced both backends in parallel and kept the first answer.
|
||||
That burned one google_search grounding call on *every* news request —
|
||||
including the startup briefing — even when DDG had already won the race.
|
||||
Grounding has a small quota, so it ran dry after a handful of launches and
|
||||
then 429'd for everything else (research/compare), which are the modes that
|
||||
actually need a synthesised answer.
|
||||
|
||||
DDG news returns in well under a second and gives raw headlines, which is
|
||||
exactly what the briefing wants, so it goes first and Gemini is only touched
|
||||
when DDG comes back empty.
|
||||
Runs Gemini grounded search AND DDG news in parallel.
|
||||
Returns whichever delivers a valid result first; cancels the other.
|
||||
"""
|
||||
import threading
|
||||
|
||||
gemini_query = f"latest news today: {query}" if query else "top world news today"
|
||||
ddg_query = query if query else "world news today"
|
||||
|
||||
def _ddg_attempt() -> str:
|
||||
return _format_news(ddg_query, _ddg_news(ddg_query, max_results=8))
|
||||
result_box = [None] # first valid result lands here
|
||||
lock = threading.Lock()
|
||||
done_evt = threading.Event()
|
||||
failures = [0]
|
||||
|
||||
text = _run_bounded(_ddg_attempt, timeout=5.0, label="DDG news")
|
||||
if text and len(text) > 60 and not text.startswith("No news found"):
|
||||
return text
|
||||
def _store(r: str) -> None:
|
||||
if r and len(r) > 60:
|
||||
with lock:
|
||||
if result_box[0] is None:
|
||||
result_box[0] = r
|
||||
done_evt.set()
|
||||
else:
|
||||
with lock:
|
||||
failures[0] += 1
|
||||
if failures[0] >= 2: # both failed — unblock caller
|
||||
done_evt.set()
|
||||
|
||||
text = _run_bounded(
|
||||
lambda: _gemini_search(gemini_query), timeout=6.0, label="Gemini news"
|
||||
)
|
||||
if text and len(text) > 60:
|
||||
return text
|
||||
def _try_gemini():
|
||||
try:
|
||||
_store(_gemini_search(gemini_query))
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini news failed ({e})")
|
||||
_store("")
|
||||
|
||||
return f"No news found for: {query}"
|
||||
def _try_ddg():
|
||||
try:
|
||||
results = _ddg_news(ddg_query, max_results=8)
|
||||
_store(_format_news(ddg_query, results))
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG news failed ({e})")
|
||||
_store("")
|
||||
|
||||
threading.Thread(target=_try_gemini, daemon=True).start()
|
||||
threading.Thread(target=_try_ddg, daemon=True).start()
|
||||
|
||||
done_evt.wait(timeout=10.0)
|
||||
return result_box[0] or f"No news found for: {query}"
|
||||
|
||||
|
||||
def _research(query: str) -> str:
|
||||
@@ -293,7 +223,7 @@ def _research(query: str) -> str:
|
||||
try:
|
||||
return _gemini_search(research_query)
|
||||
except Exception as e:
|
||||
_log_gemini_failure("Gemini research", e)
|
||||
print(f"[WebSearch] ⚠️ Research Gemini failed ({e}) — DDG fallback...")
|
||||
results = _ddg_search(query, max_results=10)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
@@ -304,7 +234,7 @@ def _price(query: str) -> str:
|
||||
try:
|
||||
return _gemini_search(price_query)
|
||||
except Exception as e:
|
||||
_log_gemini_failure("Gemini price", e)
|
||||
print(f"[WebSearch] ⚠️ Price Gemini failed ({e}) — DDG fallback...")
|
||||
results = _ddg_search(f"{query} price buy", max_results=6)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
@@ -317,7 +247,7 @@ def _compare(items: list[str], aspect: str) -> str:
|
||||
try:
|
||||
return _gemini_search(query)
|
||||
except Exception as e:
|
||||
_log_gemini_failure("Gemini compare", e)
|
||||
print(f"[WebSearch] ⚠️ Gemini compare failed: {e} — falling back to DDG")
|
||||
|
||||
all_results: dict[str, list] = {}
|
||||
for item in items:
|
||||
@@ -376,3 +306,38 @@ def web_search(
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ❌ All backends failed: {e}")
|
||||
return f"Search failed: {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "web_search",
|
||||
"description": "Searches the web. Use for ANY question about current facts, events, prices, or topics — always prefer this over guessing. Modes: 'search' (default), 'news' (latest headlines on a topic), 'research' (deep comprehensive answer), 'price' (product cost lookup), 'compare' (side-by-side comparison of items).",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "STRING",
|
||||
"description": "Search query or topic"
|
||||
},
|
||||
"mode": {
|
||||
"type": "STRING",
|
||||
"description": "search | news | research | price | compare"
|
||||
},
|
||||
"items": {
|
||||
"type": "ARRAY",
|
||||
"items": {
|
||||
"type": "STRING"
|
||||
},
|
||||
"description": "Items to compare (compare mode)"
|
||||
},
|
||||
"aspect": {
|
||||
"type": "STRING",
|
||||
"description": "Comparison aspect: price | specs | reviews | features"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"query"
|
||||
]
|
||||
},
|
||||
"handler": web_search,
|
||||
}
|
||||
@@ -434,4 +434,38 @@ def youtube_video(
|
||||
return handler(params, player, speak) or "Done."
|
||||
except Exception as e:
|
||||
print(f"[YouTube] ❌ Error in {action}: {e}")
|
||||
return f"YouTube {action} failed, sir: {e}"
|
||||
return f"YouTube {action} failed, sir: {e}"
|
||||
|
||||
|
||||
# ── Tool declaration (auto-discovered by core/action_loader.py) ──────────────
|
||||
TOOL = {
|
||||
"name": "youtube_video",
|
||||
"description": "Controls YouTube. Use for: playing videos, summarizing a video's content, getting video info, or showing trending videos.",
|
||||
"parameters": {
|
||||
"type": "OBJECT",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "STRING",
|
||||
"description": "play | summarize | get_info | trending (default: play)"
|
||||
},
|
||||
"query": {
|
||||
"type": "STRING",
|
||||
"description": "Search query for play action"
|
||||
},
|
||||
"save": {
|
||||
"type": "BOOLEAN",
|
||||
"description": "Save summary to Notepad (summarize only)"
|
||||
},
|
||||
"region": {
|
||||
"type": "STRING",
|
||||
"description": "Country code for trending e.g. TR, US"
|
||||
},
|
||||
"url": {
|
||||
"type": "STRING",
|
||||
"description": "Video URL for get_info action"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
},
|
||||
"handler": youtube_video,
|
||||
}
|
||||
Reference in new issue
Block a user