Spaces:
Configuration error
Configuration error
Delete chatbot_py.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487"""core/chatbot.py===============Main conversational AI engine for CineAI.
Model: microsoft/Phi-3-mini-4k-instruct (3.8B params, ~4GB RAM in float16) - Fastest free instruct model that fits in 16GB RAM alongside Whisper/BLIP - Excellent at following instructions, summarization, Q&A - Supports 4k context โ enough for full movie transcripts - Fallback: TinyLlama-1.1B-Chat (~2GB RAM) if memory is constrained
Pipeline: 1. Receive user question 2. Retrieve semantically relevant memory chunks (FAISS) 3. Search web if needed (intent detection) 4. Build structured prompt with: system role + video context + web context + history + question 5. Stream tokens from LLM 6. Translate answer to Hindi if requested 7. Store Q&A pair in memory
Streaming: uses HuggingFace TextIteratorStreamer for real-time token output."""
from __future__ import annotations
import gcimport osimport reimport threadingimport timefrom typing import Generator, Optional, List, Dict, Iterator
import psutilimport torchfrom loguru import loggerfrom transformers import ( AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer, BitsAndBytesConfig, pipeline,)
from core.memory import MemoryStorefrom core.web_search import WebSearcherfrom core.translator import Translator
# โโ Model config โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
PRIMARY_MODEL = "microsoft/Phi-3-mini-4k-instruct"FALLBACK_MODEL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"CACHE_DIR = os.path.expanduser("~/.cache/cineai/llm")
_llm_model = None_llm_tokenizer = None_llm_lock = threading.Lock()_loaded_llm_name: str = ""
def _free_ram_gb() -> float: return psutil.virtual_memory().available / 1e9
def _load_llm(model_name: str): global _llm_model, _llm_tokenizer, _loaded_llm_name logger.info(f"Loading LLM: {model_name} โฆ")
_llm_tokenizer = AutoTokenizer.from_pretrained( model_name, cache_dir=CACHE_DIR, trust_remote_code=True, )
use_cuda = torch.cuda.is_available() if use_cuda: bnb_cfg = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_compute_dtype=torch.float16, bnb_4bit_quant_type="nf4", bnb_4bit_use_double_quant=True, ) _llm_model = AutoModelForCausalLM.from_pretrained( model_name, quantization_config=bnb_cfg, device_map="auto", trust_remote_code=True, cache_dir=CACHE_DIR, ) else: # CPU: use float32 โ no bitsandbytes on CPU _llm_model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype=torch.float32, device_map="cpu", trust_remote_code=True, cache_dir=CACHE_DIR, )
_llm_model.eval() _loaded_llm_name = model_name logger.info(f"LLM '{model_name}' loaded โ")
def get_llm(): global _llm_model, _llm_tokenizer with _llm_lock: if _llm_model is None: model_name = PRIMARY_MODEL if _free_ram_gb() >= 7 else FALLBACK_MODEL _load_llm(model_name) return _llm_model, _llm_tokenizer, _loaded_llm_name
def unload_llm(): global _llm_model, _llm_tokenizer, _loaded_llm_name with _llm_lock: if _llm_model is not None: del _llm_model del _llm_tokenizer _llm_model = None _llm_tokenizer = None _loaded_llm_name = "" gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() logger.info("LLM unloaded")
# โโ Intent detection โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
WEB_SEARCH_TRIGGERS = [ "imdb", "rating", "review", "actor", "actress", "director", "cast", "release", "award", "box office", "budget", "oscar", "who plays", "real name", "based on", "true story", "sequel", "prequel", "box office", "trivia", "behind the scenes", "hidden meaning", "ending explained", "what does it mean",]
HINDI_TRIGGERS = [ "hindi", "เคนเคฟเคเคฆเฅ", "translate", "anuvad", "anuwad", "bolo", "hindi mein", "in hindi",]
SUMMARY_TRIGGERS = [ "summarize", "summary", "summarise", "what happened", "recap", "brief", "overview",]
def _needs_web_search(text: str) -> bool: t = text.lower() return any(kw in t for kw in WEB_SEARCH_TRIGGERS)
def _wants_hindi(text: str) -> bool: t = text.lower() return any(kw in t for kw in HINDI_TRIGGERS)
def _is_summary_request(text: str) -> bool: t = text.lower() return any(kw in t for kw in SUMMARY_TRIGGERS)
def _extract_time_range(text: str) -> Optional[tuple]: """Try to extract minute range like 'last 10 minutes' or 'from 20 to 30 minutes'.""" m = re.search(r'last\s+(\d+)\s+minute', text, re.I) if m: return ("last", int(m.group(1))) m = re.search(r'from\s+(\d+)\s+to\s+(\d+)\s+minute', text, re.I) if m: return ("range", int(m.group(1)), int(m.group(2))) return None
# โโ System prompt โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
SYSTEM_PROMPT = """You are CineAI, an expert movie and video companion AI assistant.You help users deeply understand any movie or video they upload.
Your personality:- Intelligent, insightful, like a knowledgeable friend watching together- Explain scenes clearly, including emotions, symbolism, and subtext- Remember everything from the video: characters, plot, dialogue, timeline- Give confident, detailed answers โ never refuse to discuss movie content- If asked in Hindi or for Hindi output, respond in Hindi- Keep responses concise but complete (2-4 paragraphs max unless summarizing)
You have access to:1. VIDEO CONTEXT: Transcribed dialogue and scene descriptions from the uploaded video2. WEB CONTEXT: Real-time internet information about the movie/show3. CONVERSATION HISTORY: Previous questions and answers in this session
Always prioritize VIDEO CONTEXT for specific scene questions.Use WEB CONTEXT for cast, ratings, background information, and hidden meanings."""
# โโ Main chatbot โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
class CineAIChatbot:
MAX_NEW_TOKENS = 512 TEMPERATURE = 0.7 TOP_P = 0.9 REPETITION_PENALTY = 1.15
def __init__(self): self.searcher = WebSearcher() self.translator = Translator()
# โโ Main streaming response โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ def stream_response( self, user_message: str, memory: MemoryStore, video_title: str = "", video_duration_sec: float = 0.0, translate_to_hindi: bool = False, ) -> Generator[str, None, None]: """ Yields response tokens one by one (streaming). Falls back to full response if streaming fails. """ try: yield from self._stream_impl( user_message, memory, video_title, video_duration_sec, translate_to_hindi ) except Exception as e: logger.error(f"Stream error: {e}") yield f"\nโ ๏ธ Error generating response: {str(e)}"
def _stream_impl( self, user_message: str, memory: MemoryStore, video_title: str, video_duration_sec: float, translate_to_hindi: bool, ) -> Generator[str, None, None]: model, tokenizer, _ = get_llm()
# โโ 1. Build context โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ video_context = memory.build_context_for_query(user_message, video_duration_sec)
# โโ 2. Time-range handling โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ time_range = _extract_time_range(user_message) if time_range: if time_range[0] == "last": chunks = memory.get_last_n_minutes(time_range[1], video_duration_sec) video_context = "\n".join(c.content for c in chunks) or video_context elif time_range[0] == "range": start_sec = time_range[1] * 60 end_sec = time_range[2] * 60 chunks = memory.get_timeline_range(start_sec, end_sec) video_context = "\n".join(c.content for c in chunks) or video_context
# โโ 3. Web search (if needed) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ web_context = "" if _needs_web_search(user_message) or not video_context.strip(): yield "๐ *Searching the webโฆ*\n\n" web_context = self.searcher.search_for_query(user_message, video_title)
# โโ 4. Conversation history โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ history = memory.get_conversation_history(last_n=4) history_text = "\n".join( f"{h['role'].upper()}: {h['content']}" for h in history )
# โโ 5. Build prompt โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ want_hindi = translate_to_hindi or _wants_hindi(user_message) lang_instruction = "\nIMPORTANT: Respond ENTIRELY in Hindi (Devanagari script)." if want_hindi else ""
prompt = _build_prompt( system=SYSTEM_PROMPT + lang_instruction, video_title=video_title, video_context=video_context, web_context=web_context, history=history_text, question=user_message, model_name=_loaded_llm_name, tokenizer=tokenizer, )
# โโ 6. Stream generation โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ inputs = tokenizer( prompt, return_tensors="pt", truncation=True, max_length=3800, ) input_ids = inputs["input_ids"].to(next(model.parameters()).device)
streamer = TextIteratorStreamer( tokenizer, skip_prompt=True, skip_special_tokens=True, timeout=60.0, )
gen_kwargs = dict( input_ids=input_ids, streamer=streamer, max_new_tokens=self.MAX_NEW_TOKENS, do_sample=True, temperature=self.TEMPERATURE, top_p=self.TOP_P, repetition_penalty=self.REPETITION_PENALTY, pad_token_id=tokenizer.eos_token_id, )
gen_thread = threading.Thread(target=model.generate, kwargs=gen_kwargs, daemon=True) gen_thread.start()
full_response = "" for token in streamer: full_response += token yield token
gen_thread.join(timeout=120)
# โโ 7. Post-process translation โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ if want_hindi and not _looks_hindi(full_response): yield "\n\n---\n๐ฎ๐ณ *Hindi translation:*\n" hindi = self.translator.translate_to_hindi(full_response) yield hindi full_response = full_response + "\n\n" + hindi
# โโ 8. Store in memory โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ memory.add_conversation("user", user_message) memory.add_conversation("assistant", full_response[:500]) memory.add( content=f"Q: {user_message}\nA: {full_response[:300]}", timestamp_sec=0.0, memory_type="qa", )
# โโ Non-streaming (for TTS) โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ def get_response( self, user_message: str, memory: MemoryStore, video_title: str = "", video_duration_sec: float = 0.0, translate_to_hindi: bool = False, ) -> str: """Collect full streaming response into a single string.""" parts = [] for token in self.stream_response( user_message, memory, video_title, video_duration_sec, translate_to_hindi ): if not token.startswith("๐"): # skip UI status messages parts.append(token) return "".join(parts).strip()
# โโ Scene summarizer โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ def summarize_scene( self, scene_text: str, timestamp_label: str = "", memory: Optional[MemoryStore] = None, ) -> str: """Generate a scene summary and store it in memory.""" model, tokenizer, name = get_llm()
prompt = _summarize_prompt(scene_text, timestamp_label, tokenizer, name) inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048) input_ids = inputs["input_ids"].to(next(model.parameters()).device)
with torch.no_grad(): ids = model.generate( input_ids, max_new_tokens=200, do_sample=False, temperature=1.0, pad_token_id=tokenizer.eos_token_id, ) summary = tokenizer.decode(ids[0][input_ids.shape[1]:], skip_special_tokens=True).strip()
if memory and summary: memory.add( content=summary, timestamp_sec=0.0, memory_type="scene", metadata={"is_summary": True, "label": timestamp_label}, ) return summary
# โโ Whole-movie summary โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ def generate_full_summary(self, memory: MemoryStore, video_title: str = "") -> str: """Generate a structured full movie/video summary from all stored memories.""" scenes = memory.get_recent_scenes(n=20) if not scenes: return "No video content processed yet. Please upload and process a video first."
scene_text = "\n".join( f"[{_fmt_time(c.timestamp_sec)}] {c.content}" for c in reversed(scenes) )[:3000]
fake_memory = type('obj', (object,), { 'build_context_for_query': lambda *a, **kw: scene_text, 'get_last_n_minutes': lambda *a: scenes, 'get_timeline_range': lambda *a: scenes, 'get_conversation_history': lambda *a: [], })()
return self.get_response( "Give me a comprehensive structured summary of this entire video/movie. " "Include: main plot, key characters, major events in order, emotional arc, and ending.", memory=memory, video_title=video_title, )
# โโ Prompt builders โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _build_prompt( system: str, video_title: str, video_context: str, web_context: str, history: str, question: str, model_name: str, tokenizer,) -> str: """ Build the correct prompt format for each model family. Phi-3 uses <|system|>โฆ<|user|>โฆ<|assistant|> format. TinyLlama uses ChatML: <|im_start|>systemโฆ<|im_end|>. """ context_block = "" if video_title: context_block += f"VIDEO TITLE: {video_title}\n\n" if video_context and video_context.strip() != "No prior video context available.": context_block += f"VIDEO CONTEXT:\n{video_context}\n\n" if web_context: context_block += f"WEB INFORMATION:\n{web_context}\n\n" if history: context_block += f"RECENT CONVERSATION:\n{history}\n\n"
full_system = system if context_block: full_system += "\n\n" + context_block
if "phi-3" in model_name.lower() or "phi3" in model_name.lower(): return ( f"<|system|>\n{full_system}<|end|>\n" f"<|user|>\n{question}<|end|>\n" f"<|assistant|>\n" ) elif "tinyllama" in model_name.lower(): return ( f"<|im_start|>system\n{full_system}<|im_end|>\n" f"<|im_start|>user\n{question}<|im_end|>\n" f"<|im_start|>assistant\n" ) else: # Generic instruct format return f"### System:\n{full_system}\n\n### User:\n{question}\n\n### Assistant:\n"
def _summarize_prompt(text: str, label: str, tokenizer, model_name: str) -> str: instruction = ( f"Summarize the following {'scene at ' + label if label else 'content'} " f"in 3-5 sentences. Capture key events, characters, emotions, and important dialogue.\n\n" f"CONTENT:\n{text}\n\nSUMMARY:" ) if "phi-3" in model_name.lower(): return f"<|system|>\nYou are a movie analyst.<|end|>\n<|user|>\n{instruction}<|end|>\n<|assistant|>\n" return f"### Instruction:\n{instruction}\n### Response:\n"
# โโ Helpers โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
def _looks_hindi(text: str) -> bool: """Detect if text already contains Devanagari script.""" return bool(re.search(r'[\u0900-\u097F]', text))
def _fmt_time(sec: float) -> str: sec = int(sec) h, rem = divmod(sec, 3600) m, s = divmod(rem, 60) return f"{h:02d}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"chatbot_py.pyDeleted-487