Mpavan45 commited on
Commit
8995acb
Β·
verified Β·
1 Parent(s): 371e0f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +52 -124
app.py CHANGED
@@ -1,150 +1,78 @@
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 shutil
11
- import chromadb
12
-
13
- # Initialize Chroma DB client
14
- client = chromadb.Client()
15
-
16
- # Sidebar for CSV Upload and Permanent Save
17
- st.sidebar.title("πŸ“‚ Upload CSV File")
18
- csv_file = st.sidebar.file_uploader("Choose a CSV file", type=["csv"])
19
-
20
- # Save CSV permanently
21
- def save_csv_permanently(uploaded_file):
22
- save_path = os.path.join(os.getcwd(), "permanent_subtitle_data.csv")
23
- with open(save_path, "wb") as f:
24
- f.write(uploaded_file.getbuffer())
25
- return save_path
26
-
27
- # Load the CSV into Chroma DB
28
- def load_csv_to_chroma(csv_path):
29
- df = pd.read_csv(csv_path)
30
 
31
- # Ensure the embedding column is properly formatted
32
- df['embedding'] = df['embedding'].apply(lambda x: np.array(eval(x)).tolist())
 
33
 
34
- # Create Chroma collection
35
- collection_name = "video_subtitles"
36
- if collection_name in [col.name for col in client.list_collections()]:
37
- client.delete_collection(name=collection_name)
38
 
39
- collection = client.create_collection(name=collection_name)
 
 
40
 
41
- # Add data to Chroma DB
42
- for i, row in df.iterrows():
43
  collection.add(
44
- ids=[str(i)],
45
- documents=[row['text']],
46
- embeddings=[row['embedding']]
47
  )
 
48
 
49
- return collection
50
-
51
- # Handle CSV upload and save permanently
52
- if csv_file:
53
- st.sidebar.success("CSV uploaded successfully!")
54
-
55
- # Save CSV permanently
56
- csv_path = save_csv_permanently(csv_file)
57
- st.sidebar.success(f"CSV saved permanently at: {csv_path}")
58
-
59
- # Load into Chroma DB
60
- with st.spinner("Loading CSV into Chroma DB..."):
61
- collection = load_csv_to_chroma(csv_path)
62
- st.sidebar.success("CSV loaded into Chroma DB βœ…")
63
-
64
- # Whisper model for transcription
65
- whisper_model = pipeline("automatic-speech-recognition", model="openai/whisper-base")
66
-
67
- # Function to extract audio from video
68
- def extract_audio(video_file, audio_file):
69
- input_file = ffmpeg.input(video_file)
70
- output_file = ffmpeg.output(input_file, audio_file, **{'vn': None, 'ar': 16000, 'ac': 1, 'f': 'wav'})
71
- ffmpeg.run(output_file)
72
-
73
- # Function to transcribe audio
74
- def transcribe_audio(audio_file):
75
- result = whisper_model(audio_file)
76
  return result['text']
77
 
78
- # Generate embeddings for the transcription
79
- def generate_embedding(text):
80
- model = SentenceTransformer('all-MiniLM-L6-v2')
81
- return model.encode(text).tolist()
 
82
 
83
- # Search subtitles in Chroma DB
84
- def search_in_chroma(transcribed_text, collection, top_k=10):
85
- query_embedding = np.array(generate_embedding(transcribed_text))
86
 
87
- # Query Chroma DB
88
- results = collection.query(
89
- query_embeddings=[query_embedding.tolist()],
90
- n_results=top_k
91
- )
92
 
93
- # Prepare results with cosine similarity
94
- subtitles = []
95
- for i, doc in enumerate(results['documents'][0]):
96
- embedding = np.array(results['embeddings'][0][i])
97
- similarity = cosine_similarity([query_embedding], [embedding])[0][0]
98
 
99
- subtitles.append({
100
- "text": doc,
101
- "cosine_similarity": similarity
102
- })
103
-
104
- # Sort results by similarity
105
- subtitles = sorted(subtitles, key=lambda x: x['cosine_similarity'], reverse=True)
106
- return subtitles
107
 
108
  # Streamlit UI
109
- st.title("πŸŽ₯ Video Subtitle Search with Chroma DB")
110
 
111
  # Upload video
112
- uploaded_file = st.file_uploader("Upload a video", type=["mp4", "avi", "mov", "mkv"])
113
-
114
- if uploaded_file and csv_file:
115
- # Create temporary directory
116
- temp_dir = tempfile.mkdtemp()
117
-
118
- # Save video temporarily
119
- video_path = os.path.join(temp_dir, "temp_video.mp4")
120
- with open(video_path, "wb") as f:
121
- f.write(uploaded_file.getbuffer())
122
-
123
- audio_path = os.path.join(temp_dir, "temp_audio.wav")
124
-
125
- # Extract audio
126
- st.info("Extracting audio...")
127
- extract_audio(video_path, audio_path)
128
 
129
- # Transcribe audio
130
- st.info("Transcribing audio...")
131
- transcribed_text = transcribe_audio(audio_path)
132
- st.text_area("Transcribed Text", transcribed_text, height=150)
 
 
133
 
134
- # Search in Chroma DB
135
- st.info("Searching subtitles in Chroma DB...")
136
- matching_subtitles = search_in_chroma(transcribed_text, collection)
137
 
138
- # Display video
139
- st.video(video_path)
140
 
141
- # Display matching subtitles
142
- st.subheader("πŸ“œ Matching Subtitles with Cosine Similarity")
143
- for sub in matching_subtitles:
144
- st.write(f"**Subtitle:** {sub['text']}")
145
- st.write(f"**Cosine Similarity:** {sub['cosine_similarity']:.4f}")
146
- st.write("---")
147
 
148
- # Cleanup temporary files and directory
149
- shutil.rmtree(temp_dir)
150
- st.success("Temporary files cleaned up successfully βœ…")
 
1
  import streamlit as st
 
 
2
  import pandas as pd
3
+ import chromadb
4
+ from sklearn.feature_extraction.text import TfidfVectorizer
5
  from sklearn.metrics.pairwise import cosine_similarity
6
+ import whisper
7
  import os
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Initialize Chroma DB
10
+ chroma_client = chromadb.Client()
11
+ collection = chroma_client.create_collection(name="subtitles")
12
 
13
+ # Sidebar for subtitle upload
14
+ st.sidebar.header("πŸ“‚ Upload Subtitle CSV")
15
+ subtitle_file = st.sidebar.file_uploader("Upload subtitle dataset (CSV)", type=["csv"])
 
16
 
17
+ if subtitle_file:
18
+ # Read CSV and store in Chroma DB
19
+ subtitle_df = pd.read_csv(subtitle_file)
20
 
21
+ for i, row in subtitle_df.iterrows():
 
22
  collection.add(
23
+ documents=[row['cleaned_subtitle']],
24
+ metadatas=[{"subtitle": row['subtitle']}],
25
+ ids=[f"subtitle_{i}"]
26
  )
27
+ st.sidebar.success("βœ… Subtitles stored in Chroma DB permanently.")
28
 
29
+ # Function to transcribe video using Whisper
30
+ def video_to_text(video_path):
31
+ model = whisper.load_model("small")
32
+ result = model.transcribe(video_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  return result['text']
34
 
35
+ # Function to match transcribed text with subtitles
36
+ def match_with_chroma(transcription, collection):
37
+ # Retrieve all subtitle texts from Chroma DB
38
+ docs = collection.get()
39
+ subtitles = [doc['document'] for doc in docs['documents']]
40
 
41
+ # Vectorization with TF-IDF
42
+ vectorizer = TfidfVectorizer()
43
+ vectors = vectorizer.fit_transform([transcription] + subtitles)
44
 
45
+ # Cosine similarity
46
+ similarity_scores = cosine_similarity(vectors[0:1], vectors[1:])
 
 
 
47
 
48
+ # Best match
49
+ best_match_index = similarity_scores.argmax()
50
+ best_match = docs['metadatas'][best_match_index]['subtitle']
 
 
51
 
52
+ return best_match
 
 
 
 
 
 
 
53
 
54
  # Streamlit UI
55
+ st.title("πŸŽ₯ Video Subtitle Extractor")
56
 
57
  # Upload video
58
+ video_file = st.file_uploader("Upload a video", type=["mp4", "mkv", "avi"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ if video_file:
61
+ with st.spinner("Processing video..."):
62
+ # Save uploaded video temporarily
63
+ video_path = "uploaded_video.mp4"
64
+ with open(video_path, "wb") as f:
65
+ f.write(video_file.read())
66
 
67
+ # Transcribe video
68
+ transcription = video_to_text(video_path)
 
69
 
70
+ # Find best-matching subtitle
71
+ best_match = match_with_chroma(transcription, collection)
72
 
73
+ # Display results
74
+ st.subheader("πŸ” Extracted Subtitle")
75
+ st.write(best_match)
 
 
 
76
 
77
+ # Clean up temporary video file
78
+ os.remove(video_path)