Phaneendrabayi commited on
Commit
c4bb37f
Β·
verified Β·
1 Parent(s): 56389fa

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -102
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 concurrent.futures import ThreadPoolExecutor
 
11
 
12
- # Load the subtitle embeddings (Already Generated)
13
- with open("subtitle_embeddings.pkl", "rb") as f:
14
- subtitle_data = pickle.load(f)
15
 
16
- # Initialize ChromaDB for fast search
17
  chroma_client = chromadb.PersistentClient(path="./chroma_db")
18
  collection = chroma_client.get_or_create_collection(name="subtitles")
19
 
20
- # Load Whisper Tiny Model for faster processing
21
- whisper_model = whisper.load_model("tiny")
 
 
 
 
22
 
23
  # Load Sentence Transformer Model (For Semantic Search)
24
- embedder = SentenceTransformer("all-MiniLM-L6-v2")
 
 
25
 
26
- # Function to Transcribe Audio using Whisper (Optimized)
27
- @st.cache_data
28
- def transcribe_audio(audio_file):
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
- # Fast Search for a Word in Subtitles using NumPy (Display Timestamp)
69
- def search_word_in_subtitles(subtitles, search_word):
70
- search_word_lower = search_word.lower()
71
- results = []
72
- for subtitle in subtitles:
73
- if search_word_lower in subtitle.lower():
74
- results.append(subtitle)
75
- return results if results else ["No matches found."]
76
-
77
- # Function to Search Similar Words in ChromaDB with Parallel Processing
78
- def search_word_in_chromadb(search_word, n_results=5):
79
- search_embedding = embedder.encode([search_word]).tolist()
80
- with ThreadPoolExecutor() as executor:
81
- future = executor.submit(collection.query, query_embeddings=search_embedding, n_results=n_results)
82
- results = future.result()
83
- return results.get("documents", ["No similar matches found in ChromaDB."])
84
-
85
- st.set_page_config(page_title="AI Subtitle Generator & Search", layout="wide")
86
- st.title("🎬 AI-Powered Subtitle Generator & Search")
87
-
88
- # Tabs for different functionalities
89
- with st.container():
90
- tab1, tab2 = st.tabs(["🎡 Generate Subtitles", "πŸ”Ž Search Subtitles"])
91
-
92
- with tab1:
93
- st.markdown("### Upload an audio file to generate subtitles.")
94
- uploaded_audio = st.file_uploader("Upload Audio (MP3, WAV Only)", type=["mp3", "wav"])
95
-
96
- if uploaded_audio:
97
- st.audio(uploaded_audio, format="audio/mp3")
98
-
99
- with st.spinner("πŸ“ Generating subtitles..."):
100
- subtitles = transcribe_audio(uploaded_audio)
101
-
102
- if subtitles:
103
- st.markdown("### πŸ“œ Generated Subtitles")
104
- st.text_area("", "\n".join(subtitles), height=300)
105
-
106
- # Download Subtitles in SRT and TXT without File I/O
107
- st.download_button(f"πŸ“₯ Download Subtitles (SRT)", data="\n".join(subtitles), file_name="subtitles.srt", mime="text/plain")
108
- st.download_button(f"πŸ“₯ Download Subtitles (TXT)", data="\n".join(subtitles), file_name="subtitles.txt", mime="text/plain")
109
-
110
- with tab2:
111
- st.markdown("### Search for a word within generated subtitles and ChromaDB.")
112
- search_word = st.text_input("πŸ”Ž Enter word to search")
113
- if search_word and subtitles:
114
- results = search_word_in_subtitles(subtitles, search_word)
115
- st.markdown("### πŸ”Ž Search Results in Subtitles (with Timestamps)")
116
- st.write(results)
117
-
118
- chromadb_results = search_word_in_chromadb(search_word)
119
- st.markdown("### πŸ”Ž Search Results in ChromaDB (Similar Words)")
120
- st.write(chromadb_results)
121
- elif search_word and not subtitles:
122
- st.warning("Please generate subtitles first in the 'Generate Subtitles' tab.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.")