Update app.py
Browse files
app.py
CHANGED
|
@@ -1,63 +1,34 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import whisper
|
| 3 |
-
import numpy as np
|
| 4 |
-
import pickle
|
| 5 |
-
import chromadb
|
| 6 |
-
from sentence_transformers import SentenceTransformer
|
| 7 |
import tempfile
|
| 8 |
import os
|
|
|
|
| 9 |
from pydub import AudioSegment
|
| 10 |
-
from
|
|
|
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
subtitle_data = pickle.load(f)
|
| 15 |
|
| 16 |
-
# Initialize ChromaDB
|
| 17 |
chroma_client = chromadb.PersistentClient(path="./chroma_db")
|
| 18 |
collection = chroma_client.get_or_create_collection(name="subtitles")
|
| 19 |
|
| 20 |
-
# Load Whisper
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
# Load Sentence Transformer Model (For Semantic Search)
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
try:
|
| 30 |
-
with tempfile.NamedTemporaryFile(delete=False) as temp_input_file:
|
| 31 |
-
temp_input_file.write(audio_file.getbuffer())
|
| 32 |
-
temp_input_path = temp_input_file.name
|
| 33 |
-
|
| 34 |
-
# Convert to WAV with optimized settings
|
| 35 |
-
sound = AudioSegment.from_file(temp_input_path).set_channels(1).set_frame_rate(16000)
|
| 36 |
-
temp_wav_path = temp_input_path + ".wav"
|
| 37 |
-
sound.export(temp_wav_path, format="wav")
|
| 38 |
-
|
| 39 |
-
# Transcribe using Whisper
|
| 40 |
-
st.info("π Transcribing with Whisper Tiny model...")
|
| 41 |
-
result = whisper_model.transcribe(temp_wav_path, word_timestamps=True)
|
| 42 |
-
|
| 43 |
-
# Remove temp files
|
| 44 |
-
os.remove(temp_input_path)
|
| 45 |
-
os.remove(temp_wav_path)
|
| 46 |
-
|
| 47 |
-
subtitles = []
|
| 48 |
-
for i, segment in enumerate(result["segments"]):
|
| 49 |
-
start_time = format_time(segment['start'])
|
| 50 |
-
end_time = format_time(segment['end'])
|
| 51 |
-
text = segment['text']
|
| 52 |
-
subtitles.append(f"{i+1}\n{start_time} --> {end_time}\n{text}\n")
|
| 53 |
-
|
| 54 |
-
return subtitles
|
| 55 |
-
|
| 56 |
-
except Exception as e:
|
| 57 |
-
st.error(f"Error during transcription: {e}")
|
| 58 |
-
return []
|
| 59 |
-
|
| 60 |
-
# Format time for SRT (HH:MM:SS,MS)
|
| 61 |
def format_time(seconds):
|
| 62 |
hours = int(seconds // 3600)
|
| 63 |
minutes = int((seconds % 3600) // 60)
|
|
@@ -65,58 +36,73 @@ def format_time(seconds):
|
|
| 65 |
milliseconds = int((seconds % 1) * 1000)
|
| 66 |
return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
|
| 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 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
st.
|
| 116 |
-
st.write(
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
st.
|
| 120 |
-
st.
|
| 121 |
-
|
| 122 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
|
| 10 |
+
# Set Page Config (First Command)
|
| 11 |
+
st.set_page_config(page_title="Subtitle Generator & Search")
|
|
|
|
| 12 |
|
| 13 |
+
# Initialize ChromaDB
|
| 14 |
chroma_client = chromadb.PersistentClient(path="./chroma_db")
|
| 15 |
collection = chroma_client.get_or_create_collection(name="subtitles")
|
| 16 |
|
| 17 |
+
# Load Whisper Model
|
| 18 |
+
@st.cache_resource()
|
| 19 |
+
def load_model():
|
| 20 |
+
return whisper.load_model("tiny")
|
| 21 |
+
|
| 22 |
+
whisper_model = load_model()
|
| 23 |
|
| 24 |
# Load Sentence Transformer Model (For Semantic Search)
|
| 25 |
+
@st.cache_resource()
|
| 26 |
+
def load_embedder():
|
| 27 |
+
return SentenceTransformer("all-MiniLM-L6-v2")
|
| 28 |
|
| 29 |
+
embedder = load_embedder()
|
| 30 |
+
|
| 31 |
+
# Format Time for SRT
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def format_time(seconds):
|
| 33 |
hours = int(seconds // 3600)
|
| 34 |
minutes = int((seconds % 3600) // 60)
|
|
|
|
| 36 |
milliseconds = int((seconds % 1) * 1000)
|
| 37 |
return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
|
| 38 |
|
| 39 |
+
# Transcribe Audio and Store in ChromaDB
|
| 40 |
+
@st.cache_resource()
|
| 41 |
+
def transcribe_audio(audio_file):
|
| 42 |
+
result = whisper_model.transcribe(audio_file, beam_size=1)
|
| 43 |
+
segments = result['segments']
|
| 44 |
+
subtitles = []
|
| 45 |
+
plain_subtitles = []
|
| 46 |
+
|
| 47 |
+
for i, segment in enumerate(segments):
|
| 48 |
+
start_time = format_time(segment['start'])
|
| 49 |
+
end_time = format_time(segment['end'])
|
| 50 |
+
text = segment['text']
|
| 51 |
+
subtitles.append(f"{i+1}\n{start_time} --> {end_time}\n{text}\n")
|
| 52 |
+
plain_subtitles.append(text)
|
| 53 |
+
|
| 54 |
+
# Store into ChromaDB
|
| 55 |
+
collection.upsert(
|
| 56 |
+
documents=[text],
|
| 57 |
+
ids=[f"transcribe_{i}"]
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
return "\n".join(subtitles), " ".join(plain_subtitles)
|
| 61 |
+
|
| 62 |
+
# Search using ChromaDB
|
| 63 |
+
def search_subtitles(query):
|
| 64 |
+
query_embedding = embedder.encode(query).tolist()
|
| 65 |
+
results = collection.query(query_embeddings=[query_embedding], n_results=5)
|
| 66 |
+
return results['documents'][0] if 'documents' in results and results['documents'] else []
|
| 67 |
+
|
| 68 |
+
# Upload Section
|
| 69 |
+
st.markdown("### Upload Section")
|
| 70 |
+
uploaded_file = st.file_uploader("Upload Audio File (MP3, WAV)", type=["mp3", "wav"])
|
| 71 |
+
|
| 72 |
+
tab1, tab2 = st.tabs(["Generate Subtitles", "Search Subtitles"])
|
| 73 |
+
|
| 74 |
+
with tab1:
|
| 75 |
+
if uploaded_file:
|
| 76 |
+
with st.spinner('Processing file... Please wait!'):
|
| 77 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as temp_audio:
|
| 78 |
+
if uploaded_file.name.endswith(".mp3"):
|
| 79 |
+
audio = AudioSegment.from_mp3(uploaded_file)
|
| 80 |
+
elif uploaded_file.name.endswith(".wav"):
|
| 81 |
+
audio = AudioSegment.from_wav(uploaded_file)
|
| 82 |
+
audio = audio.set_frame_rate(16000)
|
| 83 |
+
audio.export(temp_audio.name, format="wav")
|
| 84 |
+
temp_audio_path = temp_audio.name
|
| 85 |
+
|
| 86 |
+
st.audio(temp_audio_path, format='audio/wav')
|
| 87 |
+
st.write("Transcribing audio using Whisper tiny model...")
|
| 88 |
+
transcribed_text, plain_text = transcribe_audio(temp_audio_path)
|
| 89 |
+
st.subheader("Generated Subtitles")
|
| 90 |
+
st.text_area("Subtitles (SRT Format)", transcribed_text, height=300)
|
| 91 |
+
st.download_button("Download Subtitles (SRT)", transcribed_text, file_name="subtitles.srt", mime="text/plain")
|
| 92 |
+
st.download_button("Download Subtitles (Plain Text)", plain_text, file_name="subtitles.txt", mime="text/plain")
|
| 93 |
+
|
| 94 |
+
os.remove(temp_audio_path)
|
| 95 |
+
st.success("Process completed successfully!")
|
| 96 |
+
|
| 97 |
+
with tab2:
|
| 98 |
+
st.subheader("Search Subtitles")
|
| 99 |
+
search_query = st.text_input("Enter a word or sentence to search for in subtitles")
|
| 100 |
+
if search_query:
|
| 101 |
+
with st.spinner('Searching...'):
|
| 102 |
+
search_results = search_subtitles(search_query)
|
| 103 |
+
if search_results:
|
| 104 |
+
st.write("### Top 5 Matching Subtitles")
|
| 105 |
+
for result in search_results:
|
| 106 |
+
st.info(result)
|
| 107 |
+
else:
|
| 108 |
+
st.warning("No matching subtitles found.")
|