suraj-ml-projects commited on
Commit
7c52b1b
·
verified ·
1 Parent(s): d75f53d

Delete chatbot_py.py

Browse files
Files changed (1) hide show
  1. chatbot_py.py +0 -487
chatbot_py.py DELETED
@@ -1,487 +0,0 @@
1
- """
2
- core/chatbot.py
3
- ===============
4
- Main conversational AI engine for CineAI.
5
-
6
- Model: microsoft/Phi-3-mini-4k-instruct (3.8B params, ~4GB RAM in float16)
7
- - Fastest free instruct model that fits in 16GB RAM alongside Whisper/BLIP
8
- - Excellent at following instructions, summarization, Q&A
9
- - Supports 4k context — enough for full movie transcripts
10
- - Fallback: TinyLlama-1.1B-Chat (~2GB RAM) if memory is constrained
11
-
12
- Pipeline:
13
- 1. Receive user question
14
- 2. Retrieve semantically relevant memory chunks (FAISS)
15
- 3. Search web if needed (intent detection)
16
- 4. Build structured prompt with: system role + video context + web context + history + question
17
- 5. Stream tokens from LLM
18
- 6. Translate answer to Hindi if requested
19
- 7. Store Q&A pair in memory
20
-
21
- Streaming: uses HuggingFace TextIteratorStreamer for real-time token output.
22
- """
23
-
24
- from __future__ import annotations
25
-
26
- import gc
27
- import os
28
- import re
29
- import threading
30
- import time
31
- from typing import Generator, Optional, List, Dict, Iterator
32
-
33
- import psutil
34
- import torch
35
- from loguru import logger
36
- from transformers import (
37
- AutoTokenizer,
38
- AutoModelForCausalLM,
39
- TextIteratorStreamer,
40
- BitsAndBytesConfig,
41
- pipeline,
42
- )
43
-
44
- from core.memory import MemoryStore
45
- from core.web_search import WebSearcher
46
- from core.translator import Translator
47
-
48
-
49
- # ── Model config ───────────────────────────────────────────────────────────────
50
-
51
- PRIMARY_MODEL = "microsoft/Phi-3-mini-4k-instruct"
52
- FALLBACK_MODEL = "TinyLlama/TinyLlama-1.1B-Chat-v1.0"
53
- CACHE_DIR = os.path.expanduser("~/.cache/cineai/llm")
54
-
55
- _llm_model = None
56
- _llm_tokenizer = None
57
- _llm_lock = threading.Lock()
58
- _loaded_llm_name: str = ""
59
-
60
-
61
- def _free_ram_gb() -> float:
62
- return psutil.virtual_memory().available / 1e9
63
-
64
-
65
- def _load_llm(model_name: str):
66
- global _llm_model, _llm_tokenizer, _loaded_llm_name
67
- logger.info(f"Loading LLM: {model_name} …")
68
-
69
- _llm_tokenizer = AutoTokenizer.from_pretrained(
70
- model_name,
71
- cache_dir=CACHE_DIR,
72
- trust_remote_code=True,
73
- )
74
-
75
- use_cuda = torch.cuda.is_available()
76
- if use_cuda:
77
- bnb_cfg = BitsAndBytesConfig(
78
- load_in_4bit=True,
79
- bnb_4bit_compute_dtype=torch.float16,
80
- bnb_4bit_quant_type="nf4",
81
- bnb_4bit_use_double_quant=True,
82
- )
83
- _llm_model = AutoModelForCausalLM.from_pretrained(
84
- model_name,
85
- quantization_config=bnb_cfg,
86
- device_map="auto",
87
- trust_remote_code=True,
88
- cache_dir=CACHE_DIR,
89
- )
90
- else:
91
- # CPU: use float32 — no bitsandbytes on CPU
92
- _llm_model = AutoModelForCausalLM.from_pretrained(
93
- model_name,
94
- torch_dtype=torch.float32,
95
- device_map="cpu",
96
- trust_remote_code=True,
97
- cache_dir=CACHE_DIR,
98
- )
99
-
100
- _llm_model.eval()
101
- _loaded_llm_name = model_name
102
- logger.info(f"LLM '{model_name}' loaded ✓")
103
-
104
-
105
- def get_llm():
106
- global _llm_model, _llm_tokenizer
107
- with _llm_lock:
108
- if _llm_model is None:
109
- model_name = PRIMARY_MODEL if _free_ram_gb() >= 7 else FALLBACK_MODEL
110
- _load_llm(model_name)
111
- return _llm_model, _llm_tokenizer, _loaded_llm_name
112
-
113
-
114
- def unload_llm():
115
- global _llm_model, _llm_tokenizer, _loaded_llm_name
116
- with _llm_lock:
117
- if _llm_model is not None:
118
- del _llm_model
119
- del _llm_tokenizer
120
- _llm_model = None
121
- _llm_tokenizer = None
122
- _loaded_llm_name = ""
123
- gc.collect()
124
- if torch.cuda.is_available():
125
- torch.cuda.empty_cache()
126
- logger.info("LLM unloaded")
127
-
128
-
129
- # ── Intent detection ───────────────────────────────────────────────────────────
130
-
131
- WEB_SEARCH_TRIGGERS = [
132
- "imdb", "rating", "review", "actor", "actress", "director", "cast",
133
- "release", "award", "box office", "budget", "oscar", "who plays",
134
- "real name", "based on", "true story", "sequel", "prequel",
135
- "box office", "trivia", "behind the scenes", "hidden meaning",
136
- "ending explained", "what does it mean",
137
- ]
138
-
139
- HINDI_TRIGGERS = [
140
- "hindi", "हिंदी", "translate", "anuvad", "anuwad", "bolo",
141
- "hindi mein", "in hindi",
142
- ]
143
-
144
- SUMMARY_TRIGGERS = [
145
- "summarize", "summary", "summarise", "what happened",
146
- "recap", "brief", "overview",
147
- ]
148
-
149
-
150
- def _needs_web_search(text: str) -> bool:
151
- t = text.lower()
152
- return any(kw in t for kw in WEB_SEARCH_TRIGGERS)
153
-
154
-
155
- def _wants_hindi(text: str) -> bool:
156
- t = text.lower()
157
- return any(kw in t for kw in HINDI_TRIGGERS)
158
-
159
-
160
- def _is_summary_request(text: str) -> bool:
161
- t = text.lower()
162
- return any(kw in t for kw in SUMMARY_TRIGGERS)
163
-
164
-
165
- def _extract_time_range(text: str) -> Optional[tuple]:
166
- """Try to extract minute range like 'last 10 minutes' or 'from 20 to 30 minutes'."""
167
- m = re.search(r'last\s+(\d+)\s+minute', text, re.I)
168
- if m:
169
- return ("last", int(m.group(1)))
170
- m = re.search(r'from\s+(\d+)\s+to\s+(\d+)\s+minute', text, re.I)
171
- if m:
172
- return ("range", int(m.group(1)), int(m.group(2)))
173
- return None
174
-
175
-
176
- # ── System prompt ─────────────────────────────────────────────────────────────
177
-
178
- SYSTEM_PROMPT = """You are CineAI, an expert movie and video companion AI assistant.
179
- You help users deeply understand any movie or video they upload.
180
-
181
- Your personality:
182
- - Intelligent, insightful, like a knowledgeable friend watching together
183
- - Explain scenes clearly, including emotions, symbolism, and subtext
184
- - Remember everything from the video: characters, plot, dialogue, timeline
185
- - Give confident, detailed answers — never refuse to discuss movie content
186
- - If asked in Hindi or for Hindi output, respond in Hindi
187
- - Keep responses concise but complete (2-4 paragraphs max unless summarizing)
188
-
189
- You have access to:
190
- 1. VIDEO CONTEXT: Transcribed dialogue and scene descriptions from the uploaded video
191
- 2. WEB CONTEXT: Real-time internet information about the movie/show
192
- 3. CONVERSATION HISTORY: Previous questions and answers in this session
193
-
194
- Always prioritize VIDEO CONTEXT for specific scene questions.
195
- Use WEB CONTEXT for cast, ratings, background information, and hidden meanings.
196
- """
197
-
198
-
199
- # ── Main chatbot ───────────────────────────────────────────────────────────────
200
-
201
- class CineAIChatbot:
202
-
203
- MAX_NEW_TOKENS = 512
204
- TEMPERATURE = 0.7
205
- TOP_P = 0.9
206
- REPETITION_PENALTY = 1.15
207
-
208
- def __init__(self):
209
- self.searcher = WebSearcher()
210
- self.translator = Translator()
211
-
212
- # ── Main streaming response ────────────────────────────────────────────────
213
- def stream_response(
214
- self,
215
- user_message: str,
216
- memory: MemoryStore,
217
- video_title: str = "",
218
- video_duration_sec: float = 0.0,
219
- translate_to_hindi: bool = False,
220
- ) -> Generator[str, None, None]:
221
- """
222
- Yields response tokens one by one (streaming).
223
- Falls back to full response if streaming fails.
224
- """
225
- try:
226
- yield from self._stream_impl(
227
- user_message, memory, video_title,
228
- video_duration_sec, translate_to_hindi
229
- )
230
- except Exception as e:
231
- logger.error(f"Stream error: {e}")
232
- yield f"\n⚠️ Error generating response: {str(e)}"
233
-
234
- def _stream_impl(
235
- self,
236
- user_message: str,
237
- memory: MemoryStore,
238
- video_title: str,
239
- video_duration_sec: float,
240
- translate_to_hindi: bool,
241
- ) -> Generator[str, None, None]:
242
- model, tokenizer, _ = get_llm()
243
-
244
- # ── 1. Build context ──────────────────────────────────────────────────
245
- video_context = memory.build_context_for_query(user_message, video_duration_sec)
246
-
247
- # ── 2. Time-range handling ────────────────────────────────────────────
248
- time_range = _extract_time_range(user_message)
249
- if time_range:
250
- if time_range[0] == "last":
251
- chunks = memory.get_last_n_minutes(time_range[1], video_duration_sec)
252
- video_context = "\n".join(c.content for c in chunks) or video_context
253
- elif time_range[0] == "range":
254
- start_sec = time_range[1] * 60
255
- end_sec = time_range[2] * 60
256
- chunks = memory.get_timeline_range(start_sec, end_sec)
257
- video_context = "\n".join(c.content for c in chunks) or video_context
258
-
259
- # ── 3. Web search (if needed) ─────────────────────────────────────────
260
- web_context = ""
261
- if _needs_web_search(user_message) or not video_context.strip():
262
- yield "🔍 *Searching the web…*\n\n"
263
- web_context = self.searcher.search_for_query(user_message, video_title)
264
-
265
- # ── 4. Conversation history ───────────────────────────────────────────
266
- history = memory.get_conversation_history(last_n=4)
267
- history_text = "\n".join(
268
- f"{h['role'].upper()}: {h['content']}" for h in history
269
- )
270
-
271
- # ── 5. Build prompt ───────────────────────────────────────────────────
272
- want_hindi = translate_to_hindi or _wants_hindi(user_message)
273
- lang_instruction = "\nIMPORTANT: Respond ENTIRELY in Hindi (Devanagari script)." if want_hindi else ""
274
-
275
- prompt = _build_prompt(
276
- system=SYSTEM_PROMPT + lang_instruction,
277
- video_title=video_title,
278
- video_context=video_context,
279
- web_context=web_context,
280
- history=history_text,
281
- question=user_message,
282
- model_name=_loaded_llm_name,
283
- tokenizer=tokenizer,
284
- )
285
-
286
- # ── 6. Stream generation ──────────────────────────────────────────────
287
- inputs = tokenizer(
288
- prompt,
289
- return_tensors="pt",
290
- truncation=True,
291
- max_length=3800,
292
- )
293
- input_ids = inputs["input_ids"].to(next(model.parameters()).device)
294
-
295
- streamer = TextIteratorStreamer(
296
- tokenizer,
297
- skip_prompt=True,
298
- skip_special_tokens=True,
299
- timeout=60.0,
300
- )
301
-
302
- gen_kwargs = dict(
303
- input_ids=input_ids,
304
- streamer=streamer,
305
- max_new_tokens=self.MAX_NEW_TOKENS,
306
- do_sample=True,
307
- temperature=self.TEMPERATURE,
308
- top_p=self.TOP_P,
309
- repetition_penalty=self.REPETITION_PENALTY,
310
- pad_token_id=tokenizer.eos_token_id,
311
- )
312
-
313
- gen_thread = threading.Thread(target=model.generate, kwargs=gen_kwargs, daemon=True)
314
- gen_thread.start()
315
-
316
- full_response = ""
317
- for token in streamer:
318
- full_response += token
319
- yield token
320
-
321
- gen_thread.join(timeout=120)
322
-
323
- # ── 7. Post-process translation ───────────────────────────────────────
324
- if want_hindi and not _looks_hindi(full_response):
325
- yield "\n\n---\n🇮🇳 *Hindi translation:*\n"
326
- hindi = self.translator.translate_to_hindi(full_response)
327
- yield hindi
328
- full_response = full_response + "\n\n" + hindi
329
-
330
- # ── 8. Store in memory ────────────────────────────────────────────────
331
- memory.add_conversation("user", user_message)
332
- memory.add_conversation("assistant", full_response[:500])
333
- memory.add(
334
- content=f"Q: {user_message}\nA: {full_response[:300]}",
335
- timestamp_sec=0.0,
336
- memory_type="qa",
337
- )
338
-
339
- # ── Non-streaming (for TTS) ────────────────────────────────────────────────
340
- def get_response(
341
- self,
342
- user_message: str,
343
- memory: MemoryStore,
344
- video_title: str = "",
345
- video_duration_sec: float = 0.0,
346
- translate_to_hindi: bool = False,
347
- ) -> str:
348
- """Collect full streaming response into a single string."""
349
- parts = []
350
- for token in self.stream_response(
351
- user_message, memory, video_title, video_duration_sec, translate_to_hindi
352
- ):
353
- if not token.startswith("🔍"): # skip UI status messages
354
- parts.append(token)
355
- return "".join(parts).strip()
356
-
357
- # ── Scene summarizer ───────────────────────────────────────────────────────
358
- def summarize_scene(
359
- self,
360
- scene_text: str,
361
- timestamp_label: str = "",
362
- memory: Optional[MemoryStore] = None,
363
- ) -> str:
364
- """Generate a scene summary and store it in memory."""
365
- model, tokenizer, name = get_llm()
366
-
367
- prompt = _summarize_prompt(scene_text, timestamp_label, tokenizer, name)
368
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=2048)
369
- input_ids = inputs["input_ids"].to(next(model.parameters()).device)
370
-
371
- with torch.no_grad():
372
- ids = model.generate(
373
- input_ids,
374
- max_new_tokens=200,
375
- do_sample=False,
376
- temperature=1.0,
377
- pad_token_id=tokenizer.eos_token_id,
378
- )
379
- summary = tokenizer.decode(ids[0][input_ids.shape[1]:], skip_special_tokens=True).strip()
380
-
381
- if memory and summary:
382
- memory.add(
383
- content=summary,
384
- timestamp_sec=0.0,
385
- memory_type="scene",
386
- metadata={"is_summary": True, "label": timestamp_label},
387
- )
388
- return summary
389
-
390
- # ── Whole-movie summary ────────────────────────────────────────────────────
391
- def generate_full_summary(self, memory: MemoryStore, video_title: str = "") -> str:
392
- """Generate a structured full movie/video summary from all stored memories."""
393
- scenes = memory.get_recent_scenes(n=20)
394
- if not scenes:
395
- return "No video content processed yet. Please upload and process a video first."
396
-
397
- scene_text = "\n".join(
398
- f"[{_fmt_time(c.timestamp_sec)}] {c.content}"
399
- for c in reversed(scenes)
400
- )[:3000]
401
-
402
- fake_memory = type('obj', (object,), {
403
- 'build_context_for_query': lambda *a, **kw: scene_text,
404
- 'get_last_n_minutes': lambda *a: scenes,
405
- 'get_timeline_range': lambda *a: scenes,
406
- 'get_conversation_history': lambda *a: [],
407
- })()
408
-
409
- return self.get_response(
410
- "Give me a comprehensive structured summary of this entire video/movie. "
411
- "Include: main plot, key characters, major events in order, emotional arc, and ending.",
412
- memory=memory,
413
- video_title=video_title,
414
- )
415
-
416
-
417
- # ── Prompt builders ────────────────────────────────────────────────────────────
418
-
419
- def _build_prompt(
420
- system: str,
421
- video_title: str,
422
- video_context: str,
423
- web_context: str,
424
- history: str,
425
- question: str,
426
- model_name: str,
427
- tokenizer,
428
- ) -> str:
429
- """
430
- Build the correct prompt format for each model family.
431
- Phi-3 uses <|system|>…<|user|>…<|assistant|> format.
432
- TinyLlama uses ChatML: <|im_start|>system…<|im_end|>.
433
- """
434
- context_block = ""
435
- if video_title:
436
- context_block += f"VIDEO TITLE: {video_title}\n\n"
437
- if video_context and video_context.strip() != "No prior video context available.":
438
- context_block += f"VIDEO CONTEXT:\n{video_context}\n\n"
439
- if web_context:
440
- context_block += f"WEB INFORMATION:\n{web_context}\n\n"
441
- if history:
442
- context_block += f"RECENT CONVERSATION:\n{history}\n\n"
443
-
444
- full_system = system
445
- if context_block:
446
- full_system += "\n\n" + context_block
447
-
448
- if "phi-3" in model_name.lower() or "phi3" in model_name.lower():
449
- return (
450
- f"<|system|>\n{full_system}<|end|>\n"
451
- f"<|user|>\n{question}<|end|>\n"
452
- f"<|assistant|>\n"
453
- )
454
- elif "tinyllama" in model_name.lower():
455
- return (
456
- f"<|im_start|>system\n{full_system}<|im_end|>\n"
457
- f"<|im_start|>user\n{question}<|im_end|>\n"
458
- f"<|im_start|>assistant\n"
459
- )
460
- else:
461
- # Generic instruct format
462
- return f"### System:\n{full_system}\n\n### User:\n{question}\n\n### Assistant:\n"
463
-
464
-
465
- def _summarize_prompt(text: str, label: str, tokenizer, model_name: str) -> str:
466
- instruction = (
467
- f"Summarize the following {'scene at ' + label if label else 'content'} "
468
- f"in 3-5 sentences. Capture key events, characters, emotions, and important dialogue.\n\n"
469
- f"CONTENT:\n{text}\n\nSUMMARY:"
470
- )
471
- if "phi-3" in model_name.lower():
472
- return f"<|system|>\nYou are a movie analyst.<|end|>\n<|user|>\n{instruction}<|end|>\n<|assistant|>\n"
473
- return f"### Instruction:\n{instruction}\n### Response:\n"
474
-
475
-
476
- # ── Helpers ────────────────────────────────────────────────────────────────────
477
-
478
- def _looks_hindi(text: str) -> bool:
479
- """Detect if text already contains Devanagari script."""
480
- return bool(re.search(r'[\u0900-\u097F]', text))
481
-
482
-
483
- def _fmt_time(sec: float) -> str:
484
- sec = int(sec)
485
- h, rem = divmod(sec, 3600)
486
- m, s = divmod(rem, 60)
487
- return f"{h:02d}:{m:02d}:{s:02d}" if h else f"{m:02d}:{s:02d}"