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