suraj-ml-projects commited on
Commit
4543ba8
·
verified ·
1 Parent(s): 3407c3d

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -138
app.py DELETED
@@ -1,138 +0,0 @@
1
- import gradio as gr
2
- import cv2
3
- import os
4
- import gc
5
- import asyncio
6
- import torch
7
- import numpy as np
8
- import subprocess
9
- from PIL import Image
10
- from datetime import datetime
11
- from transformers import AutoModelForCausalLM, AutoTokenizer
12
- from faster_whisper import WhisperModel
13
- from sentence_transformers import SentenceTransformer
14
- import faiss
15
- from deep_translator import GoogleTranslator
16
- from duckduckgo_search import DDGS
17
- import edge_tts
18
-
19
- # --- CONFIGURATION ---
20
- TEMP_DIR = "/tmp/cinemind"
21
- os.makedirs(TEMP_DIR, exist_ok=True)
22
-
23
- class MovieEngine:
24
- def __init__(self):
25
- self.encoder = SentenceTransformer('all-MiniLM-L6-v2')
26
- self.index = faiss.IndexFlatL2(384)
27
- self.metadata = []
28
- self.whisper = WhisperModel("tiny", device="cpu", compute_type="int8")
29
-
30
- def add_memory(self, ts, text):
31
- vec = self.encoder.encode([text])
32
- self.index.add(np.array(vec).astype('float32'))
33
- self.metadata.append(f"[{int(ts)}s]: {text}")
34
-
35
- def search_memory(self, query):
36
- if not self.metadata: return ""
37
- vec = self.encoder.encode([query])
38
- _, I = self.index.search(np.array(vec).astype('float32'), 3)
39
- return " ".join([self.metadata[i] for i in I[0] if i != -1])
40
-
41
- engine = MovieEngine()
42
-
43
- # --- STEP 1: VIDEO PROCESSING ---
44
- def extract_video_data(video_path):
45
- # 1. Audio Extraction
46
- audio_path = os.path.join(TEMP_DIR, "audio.wav")
47
- subprocess.run(['ffmpeg', '-y', '-i', video_path, '-vn', '-acodec', 'pcm_s16le', '-ar', '16000', '-ac', '1', audio_path], capture_output=True)
48
-
49
- # 2. Transcription
50
- segments, _ = engine.whisper.transcribe(audio_path)
51
- for s in segments:
52
- engine.add_memory(s.start, s.text)
53
-
54
- # 3. Visual Analysis (Cold-Swap Load)
55
- # Using Moondream - very fast on CPU
56
- v_model = AutoModelForCausalLM.from_pretrained("vikhyatk/moondream2", trust_remote_code=True, revision="2024-08-05").to("cpu")
57
- v_tokenizer = AutoTokenizer.from_pretrained("vikhyatk/moondream2")
58
-
59
- cap = cv2.VideoCapture(video_path)
60
- fps = cap.get(cv2.CAP_PROP_FPS)
61
- count = 0
62
- while cap.isOpened():
63
- ret, frame = cap.read()
64
- if not ret: break
65
- if count % int(fps * 30) == 0: # Every 30 seconds
66
- rgb_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
67
- pil_img = Image.fromarray(rgb_frame)
68
- desc = v_model.answer_question(v_model.encode_image(pil_img), "Describe the scene briefly.", v_tokenizer)
69
- engine.add_memory(count/fps, desc)
70
- count += 1
71
- cap.release()
72
-
73
- # Clean up Vision Model to free RAM for Chat Model
74
- del v_model
75
- del v_tokenizer
76
- gc.collect()
77
- return "Movie analyzed! You can now chat."
78
-
79
- # --- STEP 2: SMART CHAT ---
80
- async def chat_response(message, history):
81
- # 1. Search Knowledge
82
- v_context = engine.search_memory(message)
83
-
84
- # 2. Web Search
85
- web_context = ""
86
- try:
87
- with DDGS() as ddgs:
88
- results = [r['body'] for r in ddgs.text(message, max_results=1)]
89
- web_context = results[0] if results else ""
90
- except: pass
91
-
92
- # 3. Generate Answer (Using Qwen-0.5B - the fastest CPU LLM)
93
- model_id = "Qwen/Qwen2.5-0.5B-Instruct"
94
- tokenizer = AutoTokenizer.from_pretrained(model_id)
95
- model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cpu")
96
-
97
- prompt = f"Context: {v_context} {web_context}\nUser: {message}"
98
- msgs = [{"role": "system", "content": "You are a movie expert friend. Answer the user in English based on context."},
99
- {"role": "user", "content": prompt}]
100
-
101
- input_text = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
102
- inputs = tokenizer([input_text], return_tensors="pt").to("cpu")
103
- ids = model.generate(inputs.input_ids, max_new_tokens=200)
104
- ans_en = tokenizer.batch_decode(ids, skip_special_tokens=True)[0].split("assistant\n")[-1]
105
-
106
- # 4. Translation & TTS
107
- ans_hi = GoogleTranslator(source='auto', target='hi').translate(ans_en)
108
- audio_path = os.path.join(TEMP_DIR, "speech.mp3")
109
- comm = edge_tts.Communicate(ans_hi, "hi-IN-MadhurNeural")
110
- await comm.save(audio_path)
111
-
112
- # Clean up Chat Model
113
- del model
114
- del tokenizer
115
- gc.collect()
116
-
117
- history.append((message, ans_hi))
118
- return history, audio_path
119
-
120
- # --- STEP 3: UI ---
121
- with gr.Blocks(theme=gr.themes.Soft()) as demo:
122
- gr.Markdown("# 🎬 CineMind AI (CPU Edition)\n**Upload a movie and I will analyze it using Visual and Audio memory.**")
123
-
124
- with gr.Row():
125
- with gr.Column(scale=1):
126
- v_in = gr.Video(label="Upload Movie")
127
- btn = gr.Button("Analyze Movie", variant="primary")
128
- st = gr.Textbox(label="Status")
129
- with gr.Column(scale=2):
130
- chat = gr.Chatbot(label="Hindi Conversation")
131
- msg = gr.Textbox(placeholder="Ask me anything (e.g., Who is the actor? What happened last?)")
132
- aud = gr.Audio(label="AI Voice", autoplay=True)
133
-
134
- btn.click(extract_video_data, [v_in], [st])
135
- msg.submit(lambda m, h: asyncio.run(chat_response(m, h)), [msg, chat], [chat, aud])
136
-
137
- if __name__ == "__main__":
138
- demo.launch()