Upload files to "/"
This commit is contained in:
@@ -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]}
|
||||
Reference in New Issue
Block a user