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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -34
app.py CHANGED
@@ -17,33 +17,45 @@ with open("subtitle_embeddings.pkl", "rb") as f:
17
  chroma_client = chromadb.PersistentClient(path="./chroma_db")
18
  collection = chroma_client.get_or_create_collection(name="subtitles")
19
 
20
- # Load Whisper Model
21
- whisper_model = whisper.load_model("base")
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 with Batch Processing)
27
  @st.cache_data
28
  def transcribe_audio(audio_file):
29
- with tempfile.NamedTemporaryFile(delete=False) as temp_input_file:
30
- temp_input_file.write(audio_file.getbuffer())
31
- temp_input_path = temp_input_file.name
32
-
33
- # Convert to WAV with optimized settings
34
- sound = AudioSegment.from_file(temp_input_path).set_channels(1).set_frame_rate(16000)
35
- temp_wav_path = temp_input_path + ".wav"
36
- sound.export(temp_wav_path, format="wav")
37
-
38
- # Transcribe using Whisper
39
- result = whisper_model.transcribe(temp_wav_path, word_timestamps=True)
40
-
41
- # Remove temp files
42
- os.remove(temp_input_path)
43
- os.remove(temp_wav_path)
44
-
45
- subtitles = [f"{i+1}\n{format_time(segment['start'])} --> {format_time(segment['end'])}\n{segment['text']}\n" for i, segment in enumerate(result["segments"])]
46
- return "\n".join(subtitles)
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  # Format time for SRT (HH:MM:SS,MS)
49
  def format_time(seconds):
@@ -53,12 +65,14 @@ def format_time(seconds):
53
  milliseconds = int((seconds % 1) * 1000)
54
  return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
55
 
56
- # Fast Search for a Word in Subtitles using NumPy
57
  def search_word_in_subtitles(subtitles, search_word):
58
  search_word_lower = search_word.lower()
59
- lines = np.array(subtitles.split('\n'))
60
- results = lines[np.char.find(np.char.lower(lines), search_word_lower) >= 0]
61
- return results.tolist() if results.size > 0 else ["No matches found."]
 
 
62
 
63
  # Function to Search Similar Words in ChromaDB with Parallel Processing
64
  def search_word_in_chromadb(search_word, n_results=5):
@@ -85,23 +99,24 @@ with st.container():
85
  with st.spinner("πŸ“ Generating subtitles..."):
86
  subtitles = transcribe_audio(uploaded_audio)
87
 
88
- st.markdown("### πŸ“œ Generated Subtitles")
89
- st.text_area("", subtitles, height=300)
90
-
91
- # Download Subtitles in SRT and TXT without File I/O
92
- st.download_button(f"πŸ“₯ Download Subtitles (SRT)", data=subtitles, file_name="subtitles.srt", mime="text/plain")
93
- st.download_button(f"πŸ“₯ Download Subtitles (TXT)", data=subtitles, file_name="subtitles.txt", mime="text/plain")
 
94
 
95
  with tab2:
96
  st.markdown("### Search for a word within generated subtitles and ChromaDB.")
97
  search_word = st.text_input("πŸ”Ž Enter word to search")
98
- if search_word and 'subtitles' in locals():
99
  results = search_word_in_subtitles(subtitles, search_word)
100
- st.markdown("### πŸ”Ž Search Results in Subtitles")
101
  st.write(results)
102
 
103
  chromadb_results = search_word_in_chromadb(search_word)
104
  st.markdown("### πŸ”Ž Search Results in ChromaDB (Similar Words)")
105
  st.write(chromadb_results)
106
- elif search_word and 'subtitles' not in locals():
107
  st.warning("Please generate subtitles first in the 'Generate Subtitles' tab.")
 
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):
 
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):
 
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.")