From 6f84ce6eaeb27279f1f476dba1a9fbc83c6318f0 Mon Sep 17 00:00:00 2001 From: admin Date: Wed, 25 Nov 2026 20:19:43 -0600 Subject: [PATCH] Upload files to "/" --- ai_command_access.py | 85 +++++++++++ ai_command_context.py | 273 +++++++++++++++++++++++++++++++++ ai_command_destinations.py | 67 +++++++++ ai_command_media.py | 124 +++++++++++++++ ai_command_media_extended.py | 282 +++++++++++++++++++++++++++++++++++ 5 files changed, 831 insertions(+) create mode 100644 ai_command_access.py create mode 100644 ai_command_context.py create mode 100644 ai_command_destinations.py create mode 100644 ai_command_media.py create mode 100644 ai_command_media_extended.py diff --git a/ai_command_access.py b/ai_command_access.py new file mode 100644 index 0000000..b0ea19a --- /dev/null +++ b/ai_command_access.py @@ -0,0 +1,85 @@ +"""Per-user access control for Kronic's AI Command panel. + +A user with chat_only access can converse with the model but cannot request +Balroc tool execution via the Kronic bridge. A user with tools access gets +whatever tools the separately configured Balroc harness permits. Do not treat +this as a per-tool allowlist inside Balroc. +""" +from __future__ import annotations +from media_accounts import AccountError, open_database, session_user, require_admin + + +def _ensure_schema(db): + db.execute('''CREATE TABLE IF NOT EXISTS ai_command_access ( + user_id INTEGER PRIMARY KEY REFERENCES users(id) ON DELETE CASCADE, + can_chat INTEGER NOT NULL DEFAULT 0 CHECK(can_chat IN (0,1)), + can_use_tools INTEGER NOT NULL DEFAULT 0 CHECK(can_use_tools IN (0,1)) + )''') + + +def access_for_user(user): + if bool(user['is_platform_admin']): + return {'can_chat': True, 'can_use_tools': True, 'is_platform_admin': True} + with open_database() as db: + _ensure_schema(db) + record = db.execute('SELECT can_chat,can_use_tools FROM ai_command_access WHERE user_id=?', (int(user['id']),)).fetchone() + from admin_policies import policies + rules=policies(int(user['id'])) + chat=bool(record and record['can_chat']) and all(r.get('ai_chat',True) for r in rules) + tools=chat and bool(record and record['can_use_tools']) and all(r.get('ai_tools',True) for r in rules) + return {'can_chat': chat, + 'can_use_tools': tools, + 'is_platform_admin': False} + + +def access_for_token(token): + user = session_user(token) + return access_for_user(user) + + +def require_ai_access(token): + result = access_for_token(token) + if not result['can_chat']: + raise AccountError(403, 'AI Command access has not been enabled for this account.') + return result + + +def admin_list_ai_access(token): + require_admin(token) + with open_database() as db: + _ensure_schema(db) + rows = db.execute('''SELECT u.id,u.username,u.status,u.is_platform_admin, + COALESCE(a.can_chat,0) AS can_chat, COALESCE(a.can_use_tools,0) AS can_use_tools + FROM users u LEFT JOIN ai_command_access a ON a.user_id=u.id + ORDER BY u.is_platform_admin DESC,u.username COLLATE NOCASE''').fetchall() + return {'users': [{'id': int(u['id']), 'username': u['username'], 'status': u['status'], + 'is_platform_admin': bool(u['is_platform_admin']), + 'can_chat': bool(u['is_platform_admin'] or u['can_chat']), + 'can_use_tools': bool(u['is_platform_admin'] or (u['can_chat'] and u['can_use_tools']))} + for u in rows]} + + +def admin_set_ai_access(token, data): + require_admin(token) + try: + user_id = int(data['user_id']) + except (KeyError, ValueError, TypeError): + raise AccountError(400, 'A valid user_id is required.') + chat = data.get('can_chat') + tools = data.get('can_use_tools') + if type(chat) is not bool or type(tools) is not bool: + raise AccountError(400, 'can_chat and can_use_tools must be booleans.') + if tools and not chat: + raise AccountError(400, 'Tool access requires chat access.') + with open_database() as db: + _ensure_schema(db) + user = db.execute('SELECT id,is_platform_admin FROM users WHERE id=?', (user_id,)).fetchone() + if not user: + raise AccountError(404, 'User not found.') + if user['is_platform_admin']: + raise AccountError(403, 'Platform administrator AI access cannot be revoked here.') + db.execute('''INSERT INTO ai_command_access(user_id,can_chat,can_use_tools) VALUES(?,?,?) + ON CONFLICT(user_id) DO UPDATE SET can_chat=excluded.can_chat, + can_use_tools=excluded.can_use_tools''', (user_id, int(chat), int(tools))) + db.commit() + return {'ok': True, 'user_id': user_id, 'can_chat': chat, 'can_use_tools': tools} diff --git a/ai_command_context.py b/ai_command_context.py new file mode 100644 index 0000000..c179a51 --- /dev/null +++ b/ai_command_context.py @@ -0,0 +1,273 @@ +"""Per-user, per-AI-window media follow-ups for Kronic. + +Only grounded search result IDs can be selected. No model-invented media links. +The existing resolver handles actual playback and room-sharing semantics. +""" +from __future__ import annotations + +import json +import os +import re +import sqlite3 +import threading +import time +from difflib import SequenceMatcher +from pathlib import Path + +from ai_command_media_extended import resolve as base_resolve +from media_accounts import enforce_media_library + +_DB_LOCK = threading.RLock() +_TTL = int(os.getenv('KRONIC_AI_CONTEXT_TTL_SECONDS', '7200')) + + +def _db_path(): + path = Path(os.getenv('KRONIC_AI_CONTEXT_DB', str(Path(__file__).resolve().parent / 'data' / 'ai_command_context.sqlite3'))) + path.parent.mkdir(parents=True, exist_ok=True) + return path + + +def _connect(): + db = sqlite3.connect(str(_db_path()), timeout=5) + db.execute('PRAGMA busy_timeout=5000') + db.execute('CREATE TABLE IF NOT EXISTS state (user_id INTEGER NOT NULL, window_id TEXT NOT NULL, updated REAL NOT NULL, context_json TEXT NOT NULL, PRIMARY KEY(user_id,window_id))') + return db + + +def _get(user_id, window_id): + with _DB_LOCK, _connect() as db: + row = db.execute('SELECT updated, context_json FROM state WHERE user_id=? AND window_id=?', (user_id, window_id)).fetchone() + if not row or time.time() - float(row[0]) > _TTL: + return {} + try: return json.loads(row[1]) + except (ValueError, TypeError): return {} + + +def _save(user_id, window_id, state): + with _DB_LOCK, _connect() as db: + db.execute('INSERT OR REPLACE INTO state VALUES (?,?,?,?)', (user_id, window_id, time.time(), json.dumps(state))) + + +def _reset(user_id, window_id): + with _DB_LOCK, _connect() as db: + db.execute('DELETE FROM state WHERE user_id=? AND window_id=?', (user_id, window_id)) + + +def _norm(value): + return ' '.join(re.findall(r'[a-z0-9]+', str(value or '').casefold())) + + +def _title_score(needle, title): + q,t = _norm(needle),_norm(title) + if not q or not t: return 0.0 + if q==t: return 1.0 + if q in t: return 0.96 if t.startswith(q) else 0.92 + qwords,twords = set(q.split()),set(t.split()) + coverage=len(qwords & twords)/max(1,len(qwords)) + return .72*coverage+.28*SequenceMatcher(None,q,t).ratio() + + +def _extract(msg): + m = re.match(r'^\s*(?:please\s+)?(play|watch|open|start|find|search|look up|show me)\b\s*(.*)$', msg, re.I) + return (m.group(1).lower(), m.group(2).strip()) if m else (None, '') + + +def _explicit_source(msg): + """Explicit source switch beats conversation context.""" + if re.search(r'\b(?:youtube|you[ -]?tube|tube)\b',msg,re.I):return 'youtube' + if re.search(r'\b(?:jellyfin)\b',msg,re.I):return 'jellyfin' + if re.search(r'\b(?:twitch)\b',msg,re.I):return 'twitch' + if re.search(r'\b(?:iptv|live tv)\b',msg,re.I):return 'iptv' + if re.search(r'\b(?:kronic\s+)?(?:movies?|films?)\b',msg,re.I):return 'movies' + if re.search(r'\b(?:tv\s+shows?|episodes?|series|season\s+\d+)\b',msg,re.I):return 'shows' + if re.search(r'\b(?:music|songs?|tracks?)\b',msg,re.I):return 'music' + return None + + +def _youtube_items(data): + return [i for i in ((data.get('items') if isinstance(data,dict) else []) or []) if isinstance(i,dict) and (i.get('id') or i.get('video_id'))] + + +def _minify(items): + result=[] + for i in items[:30]: + item={k:i[k] for k in ('id','video_id','title','artist','thumbnail','duration','is_live','channel','channel_name') if k in i and isinstance(i[k],(str,int,float,bool))} + if len(str(item.get('title','')))>350: item['title']=str(item['title'])[:350] + result.append(item) + return result + + +def _youtube_search_reply(query, youtube_search, *, play=False, artist_hint=''): + enforce_query = query if not artist_hint else f'{artist_hint} {query}' + items=_youtube_items(youtube_search(enforce_query,limit=24)) + results=[{**{k:i.get(k) for k in ('artist','thumbnail','duration','cached','is_live')},'title':str(i.get('title') or ''),'id':str(i.get('id') or i.get('video_id') or '')} for i in items] + state={'source':'youtube','destination':'kronic','search_query':enforce_query,'artist_hint':artist_hint, + 'results':_minify(items),'selected_id':None,'awaiting':'selection'} + if play: + choice, ambiguous = _choose_video(query,items) + if choice: + state['selected_id']=str(choice.get('id') or choice.get('video_id')) + state['awaiting']=None + return {'reply':f'Opening "{choice.get("title")}" in Kronic Tube.', + 'ui_action':_tube_action(choice,enforce_query),'results':results},state + return {'reply':f'Found {len(items)} YouTube results for "{enforce_query}". '+('Select a video to play.' if play else 'Choose a result.'), + 'ui_action':{'type':'tube_search','query':enforce_query},'results':results},state + + +def _choose_video(query,items): + ranked=sorted(((_title_score(query,i.get('title','')),i) for i in items),key=lambda x:x[0],reverse=True) + if not ranked:return None,False + top=ranked[0][0]; nextscore=ranked[1][0] if len(ranked)>1 else 0 + if top>=.77 and (top-nextscore>=.075 or top>=.995):return ranked[0][1],False + return None, bool(top>=.55 and top-nextscore<.075) + + +def _tube_action(item,query): + return {'type':'tube_play','query':query,'video_id':str(item.get('id') or item.get('video_id') or ''), + 'item':{k:item.get(k) for k in ('id','video_id','title','artist','thumbnail','duration','is_live') if k in item}} + + +def _select_from_state(rest,state,youtube_search): + """Select exact real results; re-query the SAME source when the search list is insufficient.""" + query=re.sub(r'^(?:the\s+)?(?:video\s+)?(?:one\s+)?(?:called|titled|named)\s+','',rest,flags=re.I).strip(' .?!"\'') + items=state.get('results') or [] + # 'play the second one' / 'play number 2' + m=re.match(r'^(?:the\s+)?(?:(first|second|third|fourth|fifth|sixth|seventh|eighth|ninth|tenth)|(?:number|result|option)\s*(\d+))(?:\s+one)?$',query,re.I) + if m: + index=(['first','second','third','fourth','fifth','sixth','seventh','eighth','ninth','tenth'].index(m.group(1).lower())+1) if m.group(1) else int(m.group(2)) + choice=items[index-1] if 1<=index<=len(items) else None + elif _norm(query) in ('it','that','that one','this','this one','the one'): + chosen_id=state.get('selected_id') + choice=next((x for x in items if str(x.get('id') or x.get('video_id'))==str(chosen_id)),None) + if not choice and len(items)==1: choice=items[0] + else: + choice,_=_choose_video(query,items) + if choice: + state['selected_id']=str(choice.get('id') or choice.get('video_id')) + state['awaiting']=None + return {'reply':f'Opening "{choice.get("title")}" in Kronic Tube.', 'ui_action':_tube_action(choice,state.get('search_query') or query), + 'results':[{'id':str(choice.get('id') or choice.get('video_id')),'title':str(choice.get('title') or '')}]},state + if not query or _norm(query) in ('it','that','that one','this one','the one'): + return {'reply':'Which YouTube result would you like? Say its title or result number.', 'ui_action':None},state + # Search again on YouTube, NOT in the Kronic music library. + new_query=query + hint=state.get('artist_hint') or '' + if hint and _norm(hint) not in _norm(query):new_query=f'{hint} {query}' + elif not hint: + # Preserve artist/topic from original search if the follow-up contains only the title. + orig=state.get('search_query') or '' + if orig and _norm(orig) not in _norm(query):new_query=f'{orig} {query}' + return _youtube_search_reply(new_query,youtube_search,play=True) + + + +def _local_followup(state, rest, uid): + """Follow up on cached local library matches without changing sources.""" + kind=state.get('source') + if kind not in ('movies','music','iptv','twitch'):return None + items=state.get('results') or [] + if not items:return None + enforce_media_library(uid,{'movies':'movies','music':'music','iptv':'iptv','twitch':'twitch'}[kind]) + q=rest.strip(' .?!') + m=re.match(r'^(?:the\s+)?(?:(first|second|third|fourth|fifth)|(?:number|result|option)\s*(\d+))(?:\s+one)?$',q,re.I) + if m: + index=(['first','second','third','fourth','fifth'].index(m.group(1).lower())+1) if m.group(1) else int(m.group(2)) + chosen=items[index-1] if 1<=index<=len(items) else None + elif re.match(r'^(?:the\s+)?(?:19|20)\d{2}\s+(?:version|one)$',q,re.I): + year=re.search(r'(?:19|20)\d{2}',q).group() + matches=[i for i in items if year in str(i.get('title') or '')] + chosen=matches[0] if len(matches)==1 else None + else: + chosen,_=_choose_video(q,items) + if not chosen:return None + if kind=='movies': + from admin_policies import enforce_source + from library_index import get_media_by_id,get_media_source + item=get_media_by_id(int(chosen['id'])) + enforce_source(uid,get_media_source(item['source_id']) if item and item.get('source_id') else None) + items=[i for i in items if (m:=get_media_by_id(int(i['id']))) and (src:=get_media_source(m.get('source_id'))) and __import__('admin_policies').source_allowed(uid,src)] + action={'type':'kronic_video_play','media_id':int(chosen['id']), 'title':str(chosen.get('title') or ''), + 'kind':'movies'} + if chosen.get('source_id'):action['source_id']=int(chosen['source_id']) + elif kind=='music': + action={'type':'music_play','track_id':int(chosen['id']),'query':str(chosen.get('title') or '')} + elif kind=='iptv': + action={'type':'iptv_play','channel_id':int(chosen['id']),'query':str(chosen.get('name') or '')} + else: + action={'type':'twitch_play','channel_id':str(chosen['id'])} + return {'reply':f'Opening {chosen.get("title") or chosen.get("name")} in Kronic {kind}.', 'ui_action':action,'results':items[:10]} + + +def resolve(message, user_id, can_use_tools, *, youtube_search, music_list_tracks, iptv_list_channels, window_id=''): + """Drop-in extension of the existing Kronic resolver; only adds active context.""" + msg=str(message or '').strip() + uid=int(user_id) + wid=str(window_id or '').strip() + if not re.fullmatch(r'[A-Za-z0-9_-]{1,128}',wid): + # Legacy caller without a trusted conversation identifier: keep old behaviour. + return base_resolve(message,user_id,can_use_tools,youtube_search=youtube_search, + music_list_tracks=music_list_tracks,iptv_list_channels=iptv_list_channels) + if re.fullmatch(r'(?:start over|new search|clear (?:search|context)|reset (?:search|context))\s*[.!]?',msg,re.I): + _reset(uid,wid) + return {'reply':'Media search context cleared. What would you like to find?','ui_action':None} + original_search=youtube_search + request_cache={} + def youtube_search(query,limit=24): + key=(query,limit) + if key not in request_cache:request_cache[key]=original_search(query,limit=limit) + return request_cache[key] + state=_get(uid,wid) + explicit=_explicit_source(msg) + verb,rest=_extract(msg) + if not can_use_tools and verb: + return {'reply':'AI media tools are not enabled for this account.','ui_action':None} + if explicit=='youtube' and verb: + enforce_media_library(uid,'tube') + # Defer to existing v7 handler to preserve search/play and library-navigation behaviour. + response=base_resolve(msg,uid,can_use_tools,youtube_search=youtube_search, + music_list_tracks=music_list_tracks,iptv_list_channels=iptv_list_channels) + if isinstance(response,dict): + from ai_command_media_extended import _explicit_youtube_request + parsed=_explicit_youtube_request(msg) + if parsed and parsed[0]: + query=parsed[0] + results=_youtube_items(youtube_search(query,limit=24)) + _save(uid,wid,{'source':'youtube','destination':'kronic','search_query':query, + 'artist_hint':'','results':_minify(results),'selected_id':None,'awaiting':'selection'}) + return response + if explicit and explicit!='youtube': + # A new explicitly named media source replaces old search context. + _reset(uid,wid) + state={} + if explicit=='jellyfin': + # Never reinterpret a Jellyfin-source request as Kronic Music. + # Let the existing Balroc bridge interpret the Jellyfin request. + return None + if state.get('source')=='youtube' and verb and rest: + enforce_media_library(uid,'tube') + if verb in ('play','watch','open','start'): + response,nextstate=_select_from_state(rest,state,youtube_search) + _save(uid,wid,nextstate) + return response + if verb in ('search','find','look up','show me'): + response,nextstate=_youtube_search_reply(rest,youtube_search) + _save(uid,wid,nextstate) + return response + if state and verb in ('play','watch','open','start') and rest and state.get('source')!='youtube': + hit=_local_followup(state,rest,uid) + if hit: + return hit + response=base_resolve(msg,uid,can_use_tools,youtube_search=youtube_search, + music_list_tracks=music_list_tracks,iptv_list_channels=iptv_list_channels) + if isinstance(response,dict): + action=response.get('ui_action') or {} + kind=str(action.get('type') or '') + newsource=('youtube' if kind.startswith('tube_') else + 'music' if kind.startswith('music_') else + 'movies' if kind.startswith('kronic_video_') and action.get('kind')=='movies' else + 'shows' if kind.startswith('kronic_video_') and action.get('kind')=='shows' else + 'iptv' if kind.startswith('iptv_') else + 'twitch' if kind.startswith('twitch_') else '') + if newsource and newsource!='youtube': + _save(uid,wid,{'source':newsource,'destination':'kronic','search_query':rest,'results':response.get('results') or [],'awaiting':'selection'}) + return response diff --git a/ai_command_destinations.py b/ai_command_destinations.py new file mode 100644 index 0000000..ac8206a --- /dev/null +++ b/ai_command_destinations.py @@ -0,0 +1,67 @@ +"""Resolve Kronic-vs-Jellyfin destination with live, allowlisted Jellyfin sessions. + +Never authorize a target from user-authored text; the target must be returned by +Balroc's live Jellyfin /clients endpoint and be server-side approved. +""" +from __future__ import annotations +import re + + +def _norm(text): + return ' '.join(re.findall(r'[a-z0-9]+', str(text or '').casefold())) + + +def _aliases(name): + n = _norm(name) + names = {n} + if n.startswith('kodi '): + rest = n[5:] + names.add(rest + ' kodi') + names.add('kodi ' + rest) + if rest in ('lwrliving', 'lower living', 'lowerliving'): + names.update(('lower living room kodi', 'lower living room cody', 'lower living kodi', 'downstairs kodi', 'kodi downstairs', 'lower living room tv')) + if rest == 'main': + names.update(('main living room kodi', 'main living room cody', 'main kodi', 'living room kodi')) + if rest == 'bedroom': + names.update(('bedroom kodi', 'bedroom cody', 'kodi bedroom')) + return names + + +def resolve(message, destination, clients): + """Return a safe route decision: {'mode': 'local'|'remote'|'error', ...}. + + Browser-selected destinations use device_id; natural-language matches exact + live, approved client names/aliases. Unknown targets never silently become + a music or local-media search. + """ + if not isinstance(message, str) or not message.strip(): + return {'mode':'error', 'reply':'Enter a media command.'} + destination = str(destination or 'kronic').strip() + available = [c for c in clients if isinstance(c, dict) and c.get('session_id') and c.get('device_id')] + if destination.lower() not in ('', 'kronic', 'local'): + found = [c for c in available if str(c['device_id']) == destination] + if len(found) != 1: + return {'mode':'error', 'reply':'That player is no longer active. Refresh the list of Jellyfin clients.'} + choice = found[0] + if not choice.get('approved') or not choice.get('controllable'): + return {'mode':'error', 'reply':'That Jellyfin client is not approved or cannot accept remote commands.'} + return {'mode':'remote', 'device':choice['device'], 'message':message.strip() + '\nTarget Jellyfin playback client: ' + str(choice['device']) + ' (device ID ' + str(choice['device_id']) + '). Use the device ID ' + str(choice['device_id']) + ' for the Jellyfin device argument.'} + # The explicit "on [device]" clause overrides Kronic's default. Match from + # the end so that titles containing normal room words are not misclassified. + cleaned = _norm(message) + tail = re.search(r'\b(?:on|to|using|in)\s+(?:the\s+)?(.+)$', cleaned) + if not tail: + return {'mode':'local', 'message':message} + target = tail.group(1).strip() + matches = [c for c in available if target in _aliases(c.get('device'))] + if len(matches) == 1: + choice = matches[0] + if not choice.get('approved') or not choice.get('controllable'): + return {'mode':'error', 'reply':'That Jellyfin player is active but not approved for remote control.'} + return {'mode':'remote', 'device':choice['device'], 'message':message.strip() + '\nTarget Jellyfin playback client: ' + str(choice['device']) + ' (device ID ' + str(choice['device_id']) + '). Use the device ID ' + str(choice['device_id']) + ' for the Jellyfin device argument.'} + if len(matches) > 1: + return {'mode':'error', 'reply':'Several Jellyfin clients match that name. Choose the exact device from the player selector.'} + # Explicit external-player wording cannot silently fall back to Kronic's music search. + if re.search(r'\b(kodi|cody|jellyfin|fire ?tv|firestick|android tv|web player|browser player)\b', target): + return {'mode':'error', 'reply':'I could not identify an approved active Jellyfin destination. Choose a client from the dropdown or check whether its app is connected.'} + return {'mode':'local', 'message':message} diff --git a/ai_command_media.py b/ai_command_media.py new file mode 100644 index 0000000..b04a239 --- /dev/null +++ b/ai_command_media.py @@ -0,0 +1,124 @@ +"""Authenticated Kronic AI media dispatch. Playback stays in Kronic's own player.""" +from __future__ import annotations +import re +from difflib import SequenceMatcher +from media_accounts import enforce_media_library + + +def _clean(value): + return re.sub(r'\s+', ' ', str(value or '')).strip(' .?!')[:200] + + +def _tube_intent(s): + """Return (query, should_play) for explicit YouTube/Tube video requests.""" + # Commands explicitly targeting Kodi/Jellyfin belong to the existing Balroc tools. + if re.search(r'\b(?:on|in|to)\s+(?:kodi|jellyfin)\b', s, flags=re.I): + return None + patterns = [ + (True, r'^(?:please\s+)?(?:play|watch|open|start)\s+(?:the\s+)?(?:youtube|you\s*tube|tube)\s+(?:video\s+)?(?:for|called|titled|named)?\s*(.+)$'), + (True, r'^(?:please\s+)?(?:play|watch|open|start)\s+(?:the\s+)?(?:video\s+)?(.+?)\s+(?:on|from|in|using)\s+(?:youtube|you\s*tube|tube)$'), + (True, r'^(?:please\s+)?(?:play|watch|open|start)\s+(?:the\s+)?(?:youtube\s+)?video\s+(?:called|named|titled|of)?\s*(.+)$'), + (False,r'^(?:please\s+)?(?:search|find|look up|show me)\s+(?:on\s+)?(?:youtube|you\s*tube|tube)\s+(?:for\s+)?(.+)$'), + (False,r'^(?:please\s+)?(?:search|find|look up|show me)\s+(.+?)\s+(?:on\s+)?(?:youtube|you\s*tube)$'), + # Explicit WAN Show / LTT requests may omit 'YouTube'; don't hijack Kodi/Jellyfin requests. + (True, r'^(?:please\s+)?(?:play|watch|open|start)\s+(?:(?!\s+(?:on|in)\s+kodi\b).)*(?:wan\s+show|linus\s+tech\s+tips).*$'), + ] + for play,pattern in patterns: + m=re.match(pattern,s,re.I) + if m: + return (_clean(m.group(1) if m.lastindex else re.sub(r'^(please\s+)?(play|watch|open|start)\s+', '', s,flags=re.I)),play) + return None + + +def _norm(s): + s=str(s or '').casefold() + s=re.sub(r'\b(\d+)(st|nd|rd|th)\b',r'\1',s) + s=re.sub(r'[^\w]+',' ',s) + return ' '.join(s.split()) + + +def _score(query,title): + q=_norm(query); t=_norm(title) + if not q or not t:return 0.0 + if q==t:return 1.0 + qt=set(q.split());tt=set(t.split()); intersection=qt&tt + overlap=len(intersection)/max(1,len(qt)) + precision=len(intersection)/max(1,len(tt)) + similarity=SequenceMatcher(None,q,t).ratio() + # Query can be a short description of a longer video, but require substantial overlap. + return max(similarity*0.85, (overlap*0.72 + precision*0.28)) + + +def _youtube_selection(query, items): + scored=[] + for i in items: + if not isinstance(i,dict) or not (i.get('id') or i.get('video_id')):continue + scored.append((_score(query,i.get('title')),i)) + scored.sort(key=lambda x:x[0],reverse=True) + if not scored:return None,[] + best=scored[0]; next_score=scored[1][0] if len(scored)>1 else 0 + # Avoid grabbing the first result without strong confidence or when near-tied. + if best[0] < 0.75 or (next_score >= 0.75 and best[0]-next_score < 0.09): + return None,scored + return best[1],scored + + +def _find_action(message): + s=_clean(message) + tube=_tube_intent(s) + if tube:return 'tube',tube[0],('play' if tube[1] else 'search') + patterns = [ + ('music',r'^(?:please\s+)?(?:search|find|look up|show me|play)\s+(?:some\s+)?(?:music|song|track|songs)\s+(?:for\s+|by\s+|called\s+)?(.+)$'), + ('music',r'^(?:please\s+)?play\s+(.+?)\s+(?:in|from|on)\s+(?:kronic\s+)?music$'), + ('iptv',r'^(?:please\s+)?(?:play|watch|open|find|search|show me)\s+(.+?)\s+(?:on\s+)?(?:iptv|live tv|live television)$'), + ('iptv',r'^(?:please\s+)?(?:play|watch|open|find|search|show me)\s+(?:the\s+)?(?:iptv|live tv)\s+(?:channel\s+)?(.+)$'), + ] + for kind,pat in patterns: + m=re.match(pat,s,re.I) + if m and _clean(m.group(1)): + verb=re.match(r'^\s*(\w+)',s,re.I).group(1).lower() + return kind,_clean(m.group(1)),verb + return None + + +def resolve(message,user_id,can_use_tools,*,youtube_search,music_list_tracks,iptv_list_channels): + intent=_find_action(message) + if not intent:return None + if not can_use_tools: + return {'reply':'This account has AI chat access but not AI media tools.','ui_action':None} + kind,query,verb=intent + enforce_media_library(int(user_id),{'tube':'tube','music':'music','iptv':'iptv'}[kind]) + if kind=='tube': + data=youtube_search(query,limit=24) + items=(data.get('items') if isinstance(data,dict) else []) or [] + results=[{**{k:i.get(k) for k in ('artist','thumbnail','duration','cached','is_live')},'title':str(i.get('title') or ''),'id':str(i.get('id') or i.get('video_id') or '')} for i in items if isinstance(i,dict)] + if verb=='play': + match,scored=_youtube_selection(query,items) + if match: + return {'reply':f'Opening "{match.get("title")}" in Kronic Tube.', + 'ui_action':{'type':'tube_play','query':query,'video_id':str(match.get('id') or match.get('video_id')), + 'item':{key:match.get(key) for key in ('id','title','artist','thumbnail','duration','is_live') if key in match}}, + 'results':results} + return {'reply':f'Could not identify one confident match for "{query}". Showing {len(items)} YouTube results so you can choose.', + 'ui_action':{'type':'tube_search','query':query},'results':results} + return {'reply':f'Found {len(items)} YouTube result(s) for "{query}". Opening Tube search.', + 'ui_action':{'type':'tube_search','query':query},'results':results} + if kind=='music': + tracks=list(music_list_tracks(limit=100,search=query) or []) + play=verb=='play';item=tracks[0] if tracks else None + return {'reply':(f'Opening {item.get("title") or query} from Kronic Music.' if play and item else + f'Found {len(tracks)} music track(s) matching "{query}".' if tracks else f'No matching music tracks found for "{query}".'), + 'ui_action':{'type':'music_play' if play and item else 'music_search','query':query, + **({'track_id':int(item['id'])} if play and item else {})}, + 'results':[{'id':i.get('id'),'title':i.get('title'),'artist':i.get('artist'),'thumbnail':i.get('cover_url')} for i in tracks]} + channels=list(iptv_list_channels(int(user_id),selected_only=True) or []) + hits=[x for x in channels if query.casefold() in str(x.get('name') or '').casefold()] + hits.sort(key=lambda x:(str(x.get('name') or '').casefold()!=query.casefold(),len(str(x.get('name') or '')))) + is_play=verb in ('play','watch','open') + one=hits[0] if hits else None + if is_play and len(hits)>1 and str(hits[0].get('name','')).casefold()!=query.casefold():is_play=False + return {'reply':(f'Opening {one.get("name")} in Kronic IPTV.' if is_play and one else + f'Found {len(hits)} IPTV channel(s) matching "{query}".' if hits else f'No accessible IPTV channel matches "{query}".'), + 'ui_action':{'type':'iptv_play' if is_play and one else 'iptv_search','query':query, + **({'channel_id':int(one['id'])} if is_play and one else {})}, + 'results':[{'id':c.get('id'),'name':c.get('name'),'thumbnail':c.get('tvg_logo'),'subtitle':c.get('group_name')} for c in hits]} diff --git a/ai_command_media_extended.py b/ai_command_media_extended.py new file mode 100644 index 0000000..ecb69db --- /dev/null +++ b/ai_command_media_extended.py @@ -0,0 +1,282 @@ +"""Kronic-local AI intent routing; never sends room playback to Jellyfin by default. + +Uses the existing authenticated Kronic media libraries and returns only UI actions. +The browser invokes Kronic's native player functions; room_sync.js owns sharing. +""" +from __future__ import annotations +import re +from difflib import SequenceMatcher +from ai_command_media import resolve as original_resolve, _clean, _score +from media_accounts import enforce_media_library +from library_index import search_media, get_media_sources +from twitch_jobs import list_channels as twitch_list_channels + + +def norm(s): + return re.sub(r'[^a-z0-9]+', ' ', str(s or '').lower()).strip() + + +def media_title(item): + return str(item.get('effective_title') or item.get('title') or '') + + +def series_title(item): + return str(item.get('effective_series_title') or item.get('series_title') or media_title(item)) + + +def match(query, label): + q, t = norm(query), norm(label) + if not q or not t: return 0 + if q == t: return 1 + if q in t: return 0.9 if t.startswith(q) else 0.8 + qparts = set(q.split()); tparts = set(t.split()) + return max(0.7*len(qparts & tparts)/max(1,len(qparts)) + 0.3*SequenceMatcher(None,q,t).ratio(), SequenceMatcher(None,q,t).ratio()*0.8) + + +def choose(query, items, title_getter, min_score=0.68): + ordered = sorted(items,key=lambda i:match(query,title_getter(i)),reverse=True) + if not ordered: return None,[] + score = match(query,title_getter(ordered[0])) + second = match(query,title_getter(ordered[1])) if len(ordered)>1 else 0 + if scoremusic fallback for this request. + tube = _youtube_only(message, user_id, can_use_tools, youtube_search) + if tube is not None: + return tube + found=intended(message) + if found and not can_use_tools: + return {'reply':'AI media tools are not enabled for this account.','ui_action':None} + if not found: + return original_resolve(message,user_id,can_use_tools,youtube_search=youtube_search,music_list_tracks=music_list_tracks,iptv_list_channels=iptv_list_channels) + kind,query,play,*numbers=found + if kind=='tv_unparsed': + return {'reply':'That sounds like a TV episode, but I could not reliably read the season and episode. Try “Rick and Morty season 4 episode 3”.', 'ui_action':None, 'results':[]} + if kind=='music': + enforce_media_library(int(user_id),'music') + # Search title and artist independently; Kronic's SQLite search is a phrase match. + query=norm(query) + candidates=list(music_list_tracks(limit=250,search=query) or []) + if not candidates: + parts=query.split(); subqueries=[ ' '.join(parts[-2:]),parts[-1], ' '.join(parts[:2]) ] if len(parts)>1 else [query] + indexed={} + for term in subqueries: + for row in (music_list_tracks(limit=250,search=term) or []):indexed[str(row['id'])]=row + candidates=list(indexed.values()) + chosen,ordered=choose(query,candidates,lambda r:' '.join([str(r.get('artist') or ''),str(r.get('title') or '')]),0.55) + if not chosen and candidates: + chosen,ordered=choose(query,candidates,lambda r:str(r.get('title') or ''),0.60) + results=[{'title':r.get('title'),'artist':r.get('artist'),'id':r.get('id'),'thumbnail':r.get('cover_url')} for r in ordered] + if play and chosen: + return {'reply':f'Opening {chosen.get("title")} by {chosen.get("artist") or "Unknown Artist"} in Kronic Music.', 'ui_action':{'type':'music_play','track_id':int(chosen['id']),'query':str(chosen.get('title') or query)},'results':results} + return {'reply':f'{len(candidates)} matching Kronic music tracks. '+('Select a result to play.' if play else 'Opening Music search.'), 'ui_action':{'type':'music_search','query':query},'results':results} + if kind=='twitch': + enforce_media_library(int(user_id),'twitch') + channels=twitch_list_channels(int(user_id)) or [] + chosen,ordered=choose(query,channels,lambda x:str(x.get('channel_name') or x.get('title') or x.get('name') or ''),0.63) + results=[{'id':r.get('id'),'name':r.get('channel_name') or r.get('title'),'subtitle':r.get('title'),'thumbnail':r.get('thumbnail_url') or r.get('profile_image_url')} for r in ordered if match(query,r.get('channel_name') or r.get('title'))>=0.45] + if chosen and play: + return {'reply':f'Opening {chosen.get("channel_name") or chosen.get("title")} in Kronic Twitch.', 'ui_action':{'type':'twitch_play','channel_id':str(chosen.get('id'))},'results':results} + return {'reply':f'{len(results)} matching saved Twitch channels.','ui_action':{'type':'twitch_search','query':query},'results':results} + sources={int(s['id']):s for s in get_media_sources(enabled_only=True)} + wants_tv=kind in ('series','episode') + search_name=query + requested_year=None + if kind in ('movie','auto'): + year_match=re.search(r'(?:\s|\()((?:19|20)\d{2})\)?$', search_name) + if year_match: + requested_year=int(year_match.group(1)) + search_name=search_name[:year_match.start()].strip() + query=search_name + if kind=='auto': + # If exactly matching a show's title, prefer that over unrelated movies. + wants_tv=False + allowed=[] + for item in search_media(search_name,limit=350): + src=sources.get(int(item.get('source_id') or 0)) + if not src:continue + type_key='tv' if src.get('library_type')=='shows' else 'movies' + try: + from admin_policies import enforce_source + enforce_source(int(user_id),src) + except Exception:continue + allowed.append((item,src)) + if kind=='auto': + show_exact=any(norm(series_title(i))==norm(query) for i,s in allowed if s.get('library_type')=='shows') + wants_tv=show_exact + candidates=[i for i,s in allowed if (s.get('library_type')=='shows')==wants_tv] + if requested_year and not wants_tv: + candidates=[i for i in candidates if int(i.get('effective_year') or i.get('year') or 0)==requested_year] + if kind=='episode' or (wants_tv and len(numbers)>0 and numbers[0] is not None): + season=int(numbers[0]); episode=int(numbers[1]) if len(numbers)>1 and numbers[1] is not None else None + filtered=[i for i in candidates if norm(series_title(i))==norm(query) and int(i.get('effective_season') or i.get('season') or -1)==season] + if episode is not None: + filtered=[i for i in filtered if int(i.get('effective_episode') or i.get('episode') or -1)==episode] + candidates=filtered + def library_context(item): + source=sources.get(int(item.get('source_id') or 0),{}) + return {'source_id':int(item['source_id']),'source_name':str(source.get('name') or ''), 'kind':'shows' if source.get('library_type')=='shows' else 'movies'} + if wants_tv: + # Jellyfin remains available for episodes not present in Kronic's + # indexed local library. We don't misroute such requests to Music. + if not candidates: + return None + chosen,ordered=choose(query,candidates,series_title,0.65) + if kind=='episode' and len(candidates)==1:chosen=candidates[0] + if kind=='series': + # Don't auto-play an arbitrary episode for a series-level request. + playable=False + else: playable=play + if chosen and playable: + title=f'{series_title(chosen)} S{chosen.get("effective_season") or chosen.get("season")}E{chosen.get("effective_episode") or chosen.get("episode")}' + return {'reply':f'Opening {title} in Kronic TV.', 'ui_action':{'type':'kronic_video_play','media_id':int(chosen['id']),'title':title,**library_context(chosen)},'results':[]} + source_ids={int(i.get('source_id') or 0) for i in candidates} + context=library_context(candidates[0]) if candidates and len(source_ids)==1 else {'kind':'shows'} + if candidates and len(source_ids)==1: context['show_name']=series_title(candidates[0]) + if candidates and len(source_ids)==1 and numbers and numbers[0] is not None: context['season']=int(numbers[0]) + return {'reply':f'Found {len(candidates)} matching Kronic episodes.' if candidates else f'No matching TV episodes in Kronic for {query}.', 'ui_action':{'type':'kronic_video_browse','query':query,**context},'results':[{'id':i.get('id'),'title':f'{series_title(i)} · S{i.get("effective_season")}E{i.get("effective_episode")} · {i.get("effective_episode_title") or media_title(i)}','source_id':i.get('source_id')} for i in ordered]} + if kind=='auto' and not candidates: + # Natural track names work without 'on Kronic Music'. + # Probe music, but only accept an actual selected track. A search with + # zero or ambiguous results is NOT evidence that the user meant Music. + try: + music_result=resolve('play music '+query,user_id,can_use_tools,youtube_search=youtube_search,music_list_tracks=music_list_tracks,iptv_list_channels=iptv_list_channels) + except PermissionError: + music_result={} + if (music_result.get('ui_action') or {}).get('type')=='music_play':return music_result + # Natural channel names work without 'on IPTV'. + try: + enforce_media_library(int(user_id),'iptv') + channels=list(iptv_list_channels(int(user_id),selected_only=True) or []) + exact=[c for c in channels if norm(c.get('name'))==norm(query)] + if len(exact)==1: + return {'reply':f'Opening {exact[0].get("name")} in Kronic IPTV.', + 'ui_action':{'type':'iptv_play','channel_id':int(exact[0]['id']),'query':query},'results':[]} + except Exception:pass + # Unknown bare title: let Balroc/Jellyfin reason about it. Never + # open the Kronic Music panel as a last resort. + return None + chosen,ordered=choose(query,candidates,media_title,0.68) + if play and chosen: + return {'reply':f'Opening {media_title(chosen)} in Kronic Movies.','ui_action':{'type':'kronic_video_play','media_id':int(chosen['id']),'title':media_title(chosen),**library_context(chosen)},'results':[]} + source_ids={int(i.get('source_id') or 0) for i in candidates} + context=library_context(candidates[0]) if candidates and len(source_ids)==1 else {'kind':'movies'} + return {'reply':f'Found {len(candidates)} matching Kronic movies. '+('Opening the matching movie library.' if candidates and len(source_ids)==1 else 'Select a library or title.'), 'ui_action':{'type':'kronic_video_browse','query':query,**context},'results':[{'id':i.get('id'),'title':media_title(i),'source_id':i.get('source_id')} for i in ordered]}