Files
Kronic-Krusaders/ai_command_media_extended.py
T
2026-11-25 20:19:43 -06:00

283 lines
17 KiB
Python

"""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 score<min_score or (score-second<0.07 and score<0.99):return None,ordered
return ordered[0],ordered
def intended(message):
s=_clean(message)
# Explicit external destination remains handled by Balroc/Jellyfin.
if re.search(r'\b(?:on|in|to|using)\s+(?:kodi(?:[- ]\w+)?|jellyfin)\b',s,re.I):return None
verb=re.match(r'^(?:please\s+)?(play|watch|open|start|find|search|show me|look up)\b\s*(.*)$',s,re.I)
if not verb:return None
action,rest=verb.group(1).lower(),verb.group(2).strip()
play=action in ('play','watch','open','start')
rest=re.sub(r'\s+(?:on|in|using|from)\s+(?:kronic|kronickrusaders|this (?:room|chat))\s*$', '',rest,flags=re.I)
rest=re.sub(r'^(?:the\s+)?','',rest,flags=re.I)
# Normalize natural movie prefixes before classification.
rest=re.sub(r'^(?:(?:the|a)\s+)?(?:movie|film)\s+(?:(?:called|named)\s+)?', 'movie ', rest, flags=re.I)
# Must check Twitch before generic television/program routes.
tw=re.match(r'^(?:twitch\s+)?(?:channel|stream)\s+(.+?)(?:\s+on\s+twitch)?$',rest,re.I)
tw2=re.match(r'^(.+?)\s+(?:on|from)\s+twitch$',rest,re.I)
if rest.lower().startswith('twitch ') or tw2 or tw and 'twitch' in s.lower():
return ('twitch', (tw2.group(1) if tw2 else re.sub(r'^twitch\s+(?:channel\s+|stream\s+)?','',rest,flags=re.I)).strip(),play)
if re.search(r'\b(?:youtube|you tube|tube)\b',s,re.I):return None # existing YouTube logic
# Explicit labels or natural media types.
music=re.match(r'^(?:(?:some\s+)?(?:music|song|track|songs)\s+(?:called\s+|by\s+|for\s+)?)(.+)$',rest,re.I)
music2=re.match(r'^(.+?)\s+(?:song|track|music)$',rest,re.I)
if music or music2:
return ('music',(music or music2).group(1).strip(),play)
if re.search(r'\b(?:iptv|live tv|live television)\b',rest,re.I):return None # existing IPTV resolver
tv=re.match(r'^(?:(?:tv\s+)?(?:show|series|episode)\s+)?(.+?)\s+(?:season\s*|s\s*)(\d+)\s*[,;:\-]?\s*(?:(?:episode|ep|e)\s*(\d+))?$',rest,re.I)
tv2=re.match(r'^(?:(?:tv\s+)?(?:show|series|episode)\s+)(.+)$',rest,re.I)
if tv:
return ('episode' if tv.group(3) else 'series',tv.group(1).strip(),play,int(tv.group(2)),int(tv.group(3)) if tv.group(3) else None)
if tv2:return ('series',tv2.group(1).strip(),play,None,None)
movie=re.match(r'^(?:(?:movie|film)\s+)(.+)$',rest,re.I)
if movie:return ('movie',movie.group(1).strip(),play)
# Bare 'play [title]' should default to Kronic, not Jellyfin/Kodi.
# An episode-like command must never silently turn into a music search.
# Return a typed intent even for unfamiliar episode phrasing, so the caller
# can ask for clarification without navigating away from TV.
if re.search(r'\b(?:season\s*\d+|episode\s*\d+|s\d+\s*e\d+)\b', rest, re.I):
return ('tv_unparsed', rest, play)
if play and rest:return ('auto',rest,True)
return None
def _explicit_youtube_request(message):
"""Resolve explicitly named YouTube requests before any generic media fallback.
Returns (search_query, should_play), or None. Never treats YouTube as music.
"""
s = _clean(message)
if not re.search(r'\b(?:youtube|you[ -]?tube)\b', s, re.I):
return None
command = re.match(r'^\s*(?:please\s+)?(play|watch|open|start|find|search|look up|show me)\b\s*(.*)$', s, re.I)
if not command:
return None
action, rest = command.group(1).lower(), command.group(2).strip()
should_play = action in ('play', 'watch', 'open', 'start')
# "Play VIDEO on YouTube" / "Find VIDEO in YouTube".
suffix = re.search(r'\s+(?:on|in|from|using)\s+(?:the\s+)?(?:youtube|you[ -]?tube)(?:\s+(?:app|window|player))?\s*$', rest, re.I)
if suffix:
rest = rest[:suffix.start()].strip()
else:
# "Search YouTube for VIDEO" / "Play YouTube video VIDEO".
prefix = re.match(r'^(?:on\s+)?(?:the\s+)?(?:youtube|you[ -]?tube)\b(?:\s+(?:videos?|for|about|called|named|titled))?\s*', rest, re.I)
if prefix:
rest = rest[prefix.end():].strip()
else:
# A YouTube mention in an unrecognized structure must not
# reach movie/music/Jellyfin fallback.
return ('', should_play)
rest = re.sub(r'^(?:the\s+)?(?:video\s+)?(?:for|called|named|titled)\s+', '', rest, flags=re.I).strip(' \"\'')
return rest[:200], should_play
def _youtube_only(message, user_id, can_use_tools, youtube_search):
parsed = _explicit_youtube_request(message)
if parsed is None:
return None
if not can_use_tools:
return {'reply': 'AI media tools are not enabled for this account.', 'ui_action': None}
query, should_play = parsed
if not query:
return {'reply': 'Tell me which video to find on YouTube.', 'ui_action': None}
enforce_media_library(int(user_id), 'tube')
# Use Kronic's existing YouTube resolver and player action format.
data = youtube_search(query, limit=24)
items = (data.get('items') if isinstance(data, dict) else []) or []
items = [i for i in items if isinstance(i, dict)]
from ai_command_media import _youtube_selection
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 not items:
return {'reply': f'No YouTube results found for "{query}".', 'ui_action': {'type': 'tube_search', 'query': query}, 'results': []}
if should_play:
chosen, _ = _youtube_selection(query, items)
if chosen:
return {
'reply': f'Opening "{chosen.get("title")}" in Kronic Tube.',
'ui_action': {
'type': 'tube_play', 'query': query,
'video_id': str(chosen.get('id') or chosen.get('video_id') or ''),
'item': {k: chosen.get(k) for k in ('id', 'title', 'artist', 'thumbnail', 'duration', 'is_live') if k in chosen},
},
'results': results,
}
return {
'reply': f'YouTube returned {len(items)} results for "{query}" but none was a clear single match. Showing the Tube results.',
'ui_action': {'type': 'tube_search', 'query': query}, 'results': results,
}
return {
'reply': f'Found {len(items)} YouTube results for "{query}". Choose a result.',
'ui_action': {'type': 'tube_search', 'query': query}, 'results': results,
}
def resolve(message,user_id,can_use_tools,*,youtube_search,music_list_tracks,iptv_list_channels):
# Highest-priority explicit media destination: YouTube. Never fall
# through to the generic auto/movie->music 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]}