Update app.py
Browse files
app.py
CHANGED
|
@@ -1,131 +1,128 @@
|
|
| 1 |
-
import os
|
| 2 |
import streamlit as st
|
|
|
|
|
|
|
| 3 |
import pandas as pd
|
| 4 |
-
import
|
| 5 |
-
from langchain.embeddings import HuggingFaceEmbeddings
|
| 6 |
-
from moviepy.editor import VideoFileClip
|
| 7 |
-
import whisper
|
| 8 |
-
import tempfile
|
| 9 |
-
import time
|
| 10 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
-
#
|
| 14 |
chroma_client = chromadb.Client()
|
| 15 |
-
collection_name = "
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
collection = chroma_client.create_collection(name=collection_name)
|
| 19 |
-
else:
|
| 20 |
-
collection = chroma_client.get_collection(name=collection_name)
|
| 21 |
-
|
| 22 |
-
# Load Whisper model
|
| 23 |
-
st.title("🎥 AI-Powered Subtitle Extraction with Chunked Uploading")
|
| 24 |
-
model = whisper.load_model("base")
|
| 25 |
-
|
| 26 |
-
# ✅ Chunked Upload Config (50 MB chunks to bypass 200 MB limit)
|
| 27 |
-
MAX_CHUNK_SIZE = 50 * 1024 * 1024 # 50 MB
|
| 28 |
-
|
| 29 |
-
def upload_file_in_chunks(file):
|
| 30 |
-
"""Split file into 50 MB chunks to bypass the 200 MB limit."""
|
| 31 |
-
chunk_list = []
|
| 32 |
-
bytes_data = file.read()
|
| 33 |
-
total_size = len(bytes_data)
|
| 34 |
-
num_chunks = (total_size // MAX_CHUNK_SIZE) + 1
|
| 35 |
-
|
| 36 |
-
st.write(f"🔹 Splitting into {num_chunks} chunks...")
|
| 37 |
-
|
| 38 |
-
for i in range(num_chunks):
|
| 39 |
-
start = i * MAX_CHUNK_SIZE
|
| 40 |
-
end = min((i + 1) * MAX_CHUNK_SIZE, total_size)
|
| 41 |
-
chunk_list.append(bytes_data[start:end])
|
| 42 |
-
|
| 43 |
-
# Combine all chunks into a single CSV
|
| 44 |
-
full_csv_data = b"".join(chunk_list)
|
| 45 |
-
return full_csv_data
|
| 46 |
-
|
| 47 |
-
# ✅ Upload CSV file (chunked)
|
| 48 |
-
st.sidebar.header("📥 Upload CSV File (Subtitles DB)")
|
| 49 |
-
uploaded_csv = st.sidebar.file_uploader("Upload large CSV file (up to 1 GB)", type=["csv"])
|
| 50 |
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
df = pd.read_csv("uploaded_large_file.csv")
|
| 63 |
-
st.sidebar.write("📊 Preview of CSV data:")
|
| 64 |
-
st.sidebar.dataframe(df.head())
|
| 65 |
-
|
| 66 |
-
# ✅ Generate embeddings and store in ChromaDB
|
| 67 |
-
st.sidebar.write("🔹 Generating embeddings and storing in ChromaDB...")
|
| 68 |
-
|
| 69 |
-
embeddings_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
| 70 |
-
|
| 71 |
-
subtitles = df["subtitle"].tolist()
|
| 72 |
-
|
| 73 |
-
for i, subtitle in enumerate(subtitles):
|
| 74 |
-
emb = embeddings_model.embed_query(subtitle) # Generate embedding
|
| 75 |
-
collection.add(
|
| 76 |
-
ids=[f"subtitle_{i}"],
|
| 77 |
-
embeddings=[emb],
|
| 78 |
-
metadatas=[{"text": subtitle}]
|
| 79 |
-
)
|
| 80 |
-
|
| 81 |
-
st.sidebar.success("✅ Subtitles stored in ChromaDB!")
|
| 82 |
|
| 83 |
-
#
|
| 84 |
-
st.
|
| 85 |
-
uploaded_video = st.sidebar.file_uploader("Upload a video", type=["mp4", "avi", "mov"])
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
|
| 90 |
-
|
| 91 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video:
|
| 92 |
-
temp_video.write(
|
| 93 |
video_path = temp_video.name
|
| 94 |
|
| 95 |
-
|
| 96 |
-
start_time = time.time()
|
| 97 |
|
| 98 |
-
# Extract audio
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
clip.audio.write_audiofile(audio_path)
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
|
| 107 |
-
st.
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
#
|
| 110 |
-
st.
|
| 111 |
-
|
| 112 |
-
# Embed the transcribed text
|
| 113 |
-
transcribed_emb = embeddings_model.embed_query(transcribed_text)
|
| 114 |
|
| 115 |
-
#
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
n_results=5 # Top 5 similar subtitles
|
| 119 |
-
)
|
| 120 |
|
| 121 |
-
# Display
|
| 122 |
-
st.
|
| 123 |
-
for res in results["metadatas"][0]:
|
| 124 |
-
st.write(f"- {res['text']}")
|
| 125 |
|
| 126 |
-
|
| 127 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
#
|
| 130 |
os.remove(video_path)
|
| 131 |
os.remove(audio_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import ffmpeg
|
| 3 |
+
import numpy as np
|
| 4 |
import pandas as pd
|
| 5 |
+
from sentence_transformers import SentenceTransformer
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
from sklearn.metrics.pairwise import cosine_similarity
|
| 7 |
+
from transformers import pipeline
|
| 8 |
+
import os
|
| 9 |
+
import tempfile
|
| 10 |
+
import chromadb
|
| 11 |
|
| 12 |
+
# Chroma DB initialization
|
| 13 |
chroma_client = chromadb.Client()
|
| 14 |
+
collection_name = "subtitle_chunks"
|
| 15 |
+
|
| 16 |
+
# Hugging Face Whisper Model
|
| 17 |
+
whisper_model = pipeline("automatic-speech-recognition", model="openai/whisper-base")
|
| 18 |
+
|
| 19 |
+
# Function to extract audio from video
|
| 20 |
+
def extract_audio(video_file, audio_file):
|
| 21 |
+
input_file = ffmpeg.input(video_file)
|
| 22 |
+
output_file = ffmpeg.output(input_file, audio_file, **{'vn': None, 'ar': 16000, 'ac': 1, 'f': 'wav'})
|
| 23 |
+
ffmpeg.run(output_file)
|
| 24 |
+
|
| 25 |
+
# Function to transcribe audio using Hugging Face Whisper
|
| 26 |
+
def transcribe_audio(audio_file):
|
| 27 |
+
result = whisper_model(audio_file)
|
| 28 |
+
return result['text']
|
| 29 |
+
|
| 30 |
+
# Function to generate embeddings
|
| 31 |
+
def generate_embedding(text):
|
| 32 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
| 33 |
+
return model.encode(text).tolist()
|
| 34 |
+
|
| 35 |
+
# Function to split large CSV into smaller chunks
|
| 36 |
+
def split_csv(csv_path, chunk_size=50000):
|
| 37 |
+
chunks = []
|
| 38 |
+
for i, chunk in enumerate(pd.read_csv(csv_path, chunksize=chunk_size)):
|
| 39 |
+
chunk_file = f"chunk_{i}.csv"
|
| 40 |
+
chunk.to_csv(chunk_file, index=False)
|
| 41 |
+
chunks.append(chunk_file)
|
| 42 |
+
return chunks
|
| 43 |
+
|
| 44 |
+
# Function to store subtitle chunks in Chroma DB
|
| 45 |
+
def store_chunks_in_chroma(chunk_files):
|
| 46 |
collection = chroma_client.create_collection(name=collection_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
for chunk_file in chunk_files:
|
| 49 |
+
chunk = pd.read_csv(chunk_file)
|
| 50 |
+
|
| 51 |
+
for idx, row in chunk.iterrows():
|
| 52 |
+
text = row['text']
|
| 53 |
+
embedding = generate_embedding(text)
|
| 54 |
+
|
| 55 |
+
collection.add(
|
| 56 |
+
documents=[text],
|
| 57 |
+
metadatas=[{"source": chunk_file}],
|
| 58 |
+
ids=[f"{chunk_file}_{idx}"]
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
# Function to search subtitles using Chroma DB
|
| 62 |
+
def search_in_chroma(transcribed_text, top_k=10):
|
| 63 |
+
query_embedding = generate_embedding(transcribed_text)
|
| 64 |
+
collection = chroma_client.get_collection(name=collection_name)
|
| 65 |
|
| 66 |
+
results = collection.query(
|
| 67 |
+
query_embeddings=[query_embedding],
|
| 68 |
+
n_results=top_k
|
| 69 |
+
)
|
| 70 |
|
| 71 |
+
matches = []
|
| 72 |
+
for doc, meta in zip(results['documents'][0], results['metadatas'][0]):
|
| 73 |
+
matches.append({"text": doc, "source": meta['source']})
|
| 74 |
+
|
| 75 |
+
return matches
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# Streamlit UI
|
| 78 |
+
st.title("🎥 Video Subtitle Search with Hugging Face Whisper + Chroma DB")
|
|
|
|
| 79 |
|
| 80 |
+
# Upload video
|
| 81 |
+
uploaded_file = st.file_uploader("Upload a video", type=["mp4", "avi", "mov", "mkv"])
|
| 82 |
|
| 83 |
+
if uploaded_file:
|
| 84 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video:
|
| 85 |
+
temp_video.write(uploaded_file.getbuffer())
|
| 86 |
video_path = temp_video.name
|
| 87 |
|
| 88 |
+
audio_path = "temp_audio.wav"
|
|
|
|
| 89 |
|
| 90 |
+
# Extract audio
|
| 91 |
+
st.info("Extracting audio...")
|
| 92 |
+
extract_audio(video_path, audio_path)
|
|
|
|
| 93 |
|
| 94 |
+
# Transcribe audio using Hugging Face Whisper
|
| 95 |
+
st.info("Transcribing audio...")
|
| 96 |
+
transcribed_text = transcribe_audio(audio_path)
|
| 97 |
+
st.text_area("Transcribed Text", transcribed_text, height=150)
|
| 98 |
|
| 99 |
+
# Split the large CSV database into smaller chunks
|
| 100 |
+
st.info("Splitting large database into smaller chunks...")
|
| 101 |
+
subtitle_db_path = "database.csv"
|
| 102 |
+
chunk_files = split_csv(subtitle_db_path, chunk_size=50000)
|
| 103 |
|
| 104 |
+
# Store chunks in Chroma DB
|
| 105 |
+
st.info("Storing subtitle chunks in Chroma DB...")
|
| 106 |
+
store_chunks_in_chroma(chunk_files)
|
|
|
|
|
|
|
| 107 |
|
| 108 |
+
# Search subtitles in Chroma DB
|
| 109 |
+
st.info("Searching subtitles in Chroma DB...")
|
| 110 |
+
matching_subtitles = search_in_chroma(transcribed_text)
|
|
|
|
|
|
|
| 111 |
|
| 112 |
+
# Display video
|
| 113 |
+
st.video(video_path)
|
|
|
|
|
|
|
| 114 |
|
| 115 |
+
# Display matching subtitles
|
| 116 |
+
st.subheader("📜 Matching Subtitles (Chroma DB + Cosine Similarity)")
|
| 117 |
+
for sub in matching_subtitles:
|
| 118 |
+
st.write(f"**Subtitle:** {sub['text']}")
|
| 119 |
+
st.write(f"**Source:** {sub['source']}")
|
| 120 |
+
st.write("---")
|
| 121 |
|
| 122 |
+
# Cleanup
|
| 123 |
os.remove(video_path)
|
| 124 |
os.remove(audio_path)
|
| 125 |
+
|
| 126 |
+
# Remove chunk files
|
| 127 |
+
for chunk_file in chunk_files:
|
| 128 |
+
os.remove(chunk_file)
|