"""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]}