Update app.py
Browse files
app.py
CHANGED
|
@@ -1,167 +1,160 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import
|
| 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 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
return
|
| 50 |
-
|
| 51 |
-
#
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
for
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
uploaded_video = st.file_uploader("Upload a video", type=["mp4", "avi", "mov", "mkv"])
|
| 107 |
-
|
| 108 |
-
# If both CSV and video are uploaded
|
| 109 |
-
if csv_file and uploaded_video:
|
| 110 |
-
# Handle large CSV upload using 50 MB chunks
|
| 111 |
-
st.info("Uploading CSV in 50 MB chunks...")
|
| 112 |
-
full_csv_data = upload_file_in_chunks(csv_file)
|
| 113 |
-
|
| 114 |
-
# Save CSV locally
|
| 115 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".csv") as temp_csv:
|
| 116 |
-
temp_csv.write(full_csv_data)
|
| 117 |
-
csv_path = temp_csv.name
|
| 118 |
-
|
| 119 |
-
# Save video locally
|
| 120 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".mp4") as temp_video:
|
| 121 |
-
temp_video.write(uploaded_video.getbuffer())
|
| 122 |
-
video_path = temp_video.name
|
| 123 |
-
|
| 124 |
-
audio_path = "temp_audio.wav"
|
| 125 |
-
|
| 126 |
-
# Extract audio
|
| 127 |
-
st.info("Extracting audio...")
|
| 128 |
-
extract_audio(video_path, audio_path)
|
| 129 |
-
|
| 130 |
-
# Transcribe audio using Hugging Face Whisper
|
| 131 |
-
st.info("Transcribing audio...")
|
| 132 |
-
transcribed_text = transcribe_audio(audio_path)
|
| 133 |
-
st.text_area("Transcribed Text", transcribed_text, height=150)
|
| 134 |
-
|
| 135 |
-
# Split the CSV database into smaller chunks
|
| 136 |
-
st.info("Splitting CSV into smaller chunks...")
|
| 137 |
-
chunk_files = split_csv(csv_path, chunk_size=50000)
|
| 138 |
-
|
| 139 |
-
# Store chunks in Chroma DB
|
| 140 |
-
st.info("Storing subtitle chunks in Chroma DB...")
|
| 141 |
-
store_chunks_in_chroma(chunk_files)
|
| 142 |
-
|
| 143 |
-
# Search subtitles in Chroma DB
|
| 144 |
-
st.info("Searching subtitles in Chroma DB...")
|
| 145 |
-
matching_subtitles = search_in_chroma(transcribed_text)
|
| 146 |
-
|
| 147 |
-
# Display video
|
| 148 |
-
st.video(video_path)
|
| 149 |
-
|
| 150 |
-
# Display matching subtitles
|
| 151 |
-
st.subheader("π Matching Subtitles (Chroma DB + Cosine Similarity)")
|
| 152 |
-
for sub in matching_subtitles:
|
| 153 |
-
st.write(f"**Subtitle:** {sub['text']}")
|
| 154 |
-
st.write(f"**Source:** {sub['source']}")
|
| 155 |
-
st.write("---")
|
| 156 |
-
|
| 157 |
-
# Cleanup
|
| 158 |
-
os.remove(video_path)
|
| 159 |
-
os.remove(audio_path)
|
| 160 |
-
os.remove(csv_path)
|
| 161 |
-
|
| 162 |
-
# Remove chunk files
|
| 163 |
-
for chunk_file in chunk_files:
|
| 164 |
-
os.remove(chunk_file)
|
| 165 |
-
|
| 166 |
-
else:
|
| 167 |
-
st.warning("Please upload both a video file and a CSV file to proceed.")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
+
import whisper
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import tempfile
|
| 4 |
+
import os
|
| 5 |
import chromadb
|
| 6 |
+
from pydub import AudioSegment
|
| 7 |
+
from sentence_transformers import SentenceTransformer
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pickle
|
| 10 |
+
|
| 11 |
+
# π‘ Set Page Configuration
|
| 12 |
+
st.set_page_config(page_title="Audio Subtitle Tool", layout="wide")
|
| 13 |
+
|
| 14 |
+
# π Initialize ChromaDB
|
| 15 |
+
db_client = chromadb.PersistentClient(path="./chroma_data")
|
| 16 |
+
sub_db = db_client.get_or_create_collection(name="audio_subtitles")
|
| 17 |
+
|
| 18 |
+
# βοΈ Load Whisper Model
|
| 19 |
+
@st.cache_resource()
|
| 20 |
+
def load_transcriber():
|
| 21 |
+
return whisper.load_model("base")
|
| 22 |
+
|
| 23 |
+
transcriber = load_transcriber()
|
| 24 |
+
|
| 25 |
+
# βοΈ Load Sentence Transformer
|
| 26 |
+
@st.cache_resource()
|
| 27 |
+
def load_encoder():
|
| 28 |
+
return SentenceTransformer("paraphrase-MiniLM-L6-v2")
|
| 29 |
+
|
| 30 |
+
semantic_encoder = load_encoder()
|
| 31 |
+
|
| 32 |
+
# π₯ Load Subtitle Data from Pickle
|
| 33 |
+
@st.cache_resource()
|
| 34 |
+
def load_subtitle_store():
|
| 35 |
+
with open("subtitle_data.pkl", "rb") as file:
|
| 36 |
+
subtitle_store = pickle.load(file)
|
| 37 |
+
|
| 38 |
+
# β±οΈ Format Time into SRT format
|
| 39 |
+
def time_formatter(sec):
|
| 40 |
+
hr = int(sec // 3600)
|
| 41 |
+
mins = int((sec % 3600) // 60)
|
| 42 |
+
secs = int(sec % 60)
|
| 43 |
+
millis = int((sec % 1) * 1000)
|
| 44 |
+
return f"{hr:02}:{mins:02}:{secs:02},{millis:03}"
|
| 45 |
+
|
| 46 |
+
# ποΈ Transcribe Audio and Store in ChromaDB
|
| 47 |
+
@st.cache_resource()
|
| 48 |
+
def process_audio(file_path):
|
| 49 |
+
result = transcriber.transcribe(file_path, beam_size=1)
|
| 50 |
+
segments = result['segments']
|
| 51 |
+
srt_subtitles = []
|
| 52 |
+
plain_text_subs = []
|
| 53 |
+
|
| 54 |
+
for idx, seg in enumerate(segments):
|
| 55 |
+
start = time_formatter(seg['start'])
|
| 56 |
+
end = time_formatter(seg['end'])
|
| 57 |
+
content = seg['text']
|
| 58 |
+
|
| 59 |
+
# Create SRT format
|
| 60 |
+
srt_subtitles.append(f"{idx + 1}\n{start} --> {end}\n{content}\n")
|
| 61 |
+
plain_text_subs.append(content)
|
| 62 |
+
|
| 63 |
+
# Store in ChromaDB
|
| 64 |
+
sub_db.upsert(
|
| 65 |
+
documents=[content],
|
| 66 |
+
metadatas=[{"start_time": start, "end_time": end}],
|
| 67 |
+
ids=[f"subtitle_{idx}"]
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
return "\n".join(srt_subtitles), " ".join(plain_text_subs)
|
| 71 |
+
|
| 72 |
+
# π Subtitle Search Function
|
| 73 |
+
def search_content(query):
|
| 74 |
+
query_vec = semantic_encoder.encode(query).tolist()
|
| 75 |
+
matches = sub_db.query(query_embeddings=[query_vec], n_results=5)
|
| 76 |
+
|
| 77 |
+
if 'documents' in matches and matches['documents']:
|
| 78 |
+
results = []
|
| 79 |
+
for idx, doc in enumerate(matches['documents'][0]):
|
| 80 |
+
meta = matches['metadatas'][0][idx]
|
| 81 |
+
results.append(f"π {doc} (From: {meta['start_time']} β To: {meta['end_time']})")
|
| 82 |
+
return results
|
| 83 |
+
return []
|
| 84 |
+
|
| 85 |
+
# π₯ Sidebar Navigation
|
| 86 |
+
st.sidebar.title("π― Navigation")
|
| 87 |
+
page = st.sidebar.radio("Choose Action", ["Generate Subtitles", "Search Subtitles"])
|
| 88 |
+
|
| 89 |
+
# ποΈ Sidebar Styling
|
| 90 |
+
st.sidebar.markdown(
|
| 91 |
+
"""
|
| 92 |
+
<style>
|
| 93 |
+
.sidebar .sidebar-content {
|
| 94 |
+
background-color: #f0f0f5;
|
| 95 |
+
color: #333;
|
| 96 |
+
}
|
| 97 |
+
</style>
|
| 98 |
+
""",
|
| 99 |
+
unsafe_allow_html=True
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# π¬ Header Section
|
| 103 |
+
st.markdown(
|
| 104 |
+
"""
|
| 105 |
+
<h1 style='text-align: center; color: #673AB7;'>π€ Audio Subtitle Generator & Search</h1>
|
| 106 |
+
<p style='text-align: center; font-size: 18px; color: #666;'>Generate subtitles from audio files and search through them.</p>
|
| 107 |
+
""",
|
| 108 |
+
unsafe_allow_html=True
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# π Load Subtitle Data
|
| 112 |
+
load_subtitle_store()
|
| 113 |
+
|
| 114 |
+
# π΅ File Upload Section
|
| 115 |
+
st.markdown("### π§ Upload Your Audio File")
|
| 116 |
+
audio_file = st.file_uploader("Supported formats: MP3, WAV", type=["mp3", "wav"])
|
| 117 |
+
|
| 118 |
+
# π― Page Logic
|
| 119 |
+
if page == "Generate Subtitles":
|
| 120 |
+
if audio_file:
|
| 121 |
+
st.audio(audio_file, format='audio/mp3')
|
| 122 |
+
|
| 123 |
+
with st.spinner("π§ Processing audio... Please wait."):
|
| 124 |
+
# Temporary file handling
|
| 125 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_audio:
|
| 126 |
+
if audio_file.name.endswith(".mp3"):
|
| 127 |
+
audio = AudioSegment.from_mp3(audio_file)
|
| 128 |
+
elif audio_file.name.endswith(".wav"):
|
| 129 |
+
audio = AudioSegment.from_wav(audio_file)
|
| 130 |
+
audio = audio.set_frame_rate(16000)
|
| 131 |
+
audio.export(tmp_audio.name, format="wav")
|
| 132 |
+
|
| 133 |
+
# Transcribe and store in ChromaDB
|
| 134 |
+
subtitle_output, plain_output = process_audio(tmp_audio.name)
|
| 135 |
+
st.success("β
Transcription Completed!")
|
| 136 |
+
|
| 137 |
+
# Display Subtitles
|
| 138 |
+
st.markdown("### π Generated Subtitles")
|
| 139 |
+
st.text_area("Subtitles (SRT Format)", subtitle_output, height=300)
|
| 140 |
+
|
| 141 |
+
# Download Options
|
| 142 |
+
st.download_button("β¬οΈ Download SRT File", subtitle_output, file_name="subtitles.srt", mime="text/plain")
|
| 143 |
+
st.download_button("β¬οΈ Download Plain Text", plain_output, file_name="subtitles.txt", mime="text/plain")
|
| 144 |
+
|
| 145 |
+
os.remove(tmp_audio.name)
|
| 146 |
+
|
| 147 |
+
elif page == "Search Subtitles":
|
| 148 |
+
st.subheader("π Search Subtitles")
|
| 149 |
+
query_input = st.text_input("Enter text to search")
|
| 150 |
|
| 151 |
+
if query_input:
|
| 152 |
+
with st.spinner("π Searching..."):
|
| 153 |
+
search_matches = search_content(query_input)
|
| 154 |
+
|
| 155 |
+
if search_matches:
|
| 156 |
+
st.success("β
Results Found:")
|
| 157 |
+
for match in search_matches:
|
| 158 |
+
st.write(match)
|
| 159 |
+
else:
|
| 160 |
+
st.warning("β οΈ No matching results. Try a different query.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|