Phaneendrabayi commited on
Commit
a45737f
·
verified ·
1 Parent(s): 9c2b918

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -38
app.py CHANGED
@@ -11,10 +11,28 @@ from pydub import AudioSegment
11
  chroma_client = chromadb.PersistentClient(path="./chroma_db")
12
  collection = chroma_client.get_or_create_collection(name="subtitles")
13
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  # App Title and Config
15
- st.set_page_config(page_title="Subtitle Search Engine", layout="wide")
16
- st.title("🎬 AI-Powered Subtitle Search Engine")
17
- st.markdown("Upload an audio file to generate subtitles and search within subtitles using AI.")
18
 
19
  # Load Whisper Model
20
  @st.cache_resource()
@@ -23,20 +41,6 @@ def load_model():
23
 
24
  whisper_model = load_model()
25
 
26
- # Load Pickle Data and Add to ChromaDB
27
- @st.cache_resource()
28
- def load_and_store_pickle_data():
29
- with open('subtitle_embeddings.pkl', 'rb') as f:
30
- data = pickle.load(f)
31
- if isinstance(data, np.ndarray):
32
- data = data.tolist()
33
- for i, item in enumerate(data):
34
- if isinstance(item, dict) and 'text' in item:
35
- collection.add(documents=[item['text']], ids=[str(i)])
36
- return data
37
-
38
- subtitle_data = load_and_store_pickle_data()
39
-
40
  # Format Time for SRT
41
  def format_time(seconds):
42
  hours = int(seconds // 3600)
@@ -45,29 +49,38 @@ def format_time(seconds):
45
  milliseconds = int((seconds % 1) * 1000)
46
  return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
47
 
48
- # Transcribe Audio
49
  @st.cache_resource()
50
  def transcribe_audio(audio_file):
51
  result = whisper_model.transcribe(audio_file, beam_size=1)
52
  segments = result['segments']
53
  subtitles = []
54
  plain_subtitles = []
55
- for segment in segments:
 
56
  start_time = format_time(segment['start'])
57
  end_time = format_time(segment['end'])
58
  text = segment['text']
59
- subtitles.append(f"{len(subtitles) + 1}\n{start_time} --> {end_time}\n{text}\n")
60
  plain_subtitles.append(text)
 
 
 
 
 
 
 
61
  return "\n".join(subtitles), " ".join(plain_subtitles)
62
 
63
- # Perform Word Search Using ChromaDB
64
- def search_word_with_chromadb(word):
65
- results = collection.query(query_texts=[word], n_results=5)
66
- return results['documents'][0] if results['documents'] else []
67
 
68
- # UI Layout with Tabs
69
- tab1, tab2 = st.tabs(["Upload & Generate Subtitles", "Search Subtitles"])
70
 
 
71
  with tab1:
72
  st.markdown("### Upload Section")
73
  uploaded_file = st.file_uploader("Upload Audio File (MP3, WAV)", type=["mp3", "wav"])
@@ -90,17 +103,20 @@ with tab1:
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
- collection.add(documents=[plain_text], ids=["audio_transcript"])
94
 
 
 
 
 
95
  with tab2:
96
- st.subheader("Search Subtitles")
97
- search_word = st.text_input("Search for a word using ChromaDB")
98
- if search_word.strip():
99
- top_results = search_word_with_chromadb(search_word)
100
-
101
- st.write("### Top 5 Search Results from Transcribed Text & Pickle Data")
102
- if not top_results:
103
- st.warning("No results found.")
104
- else:
105
- for i, result in enumerate(top_results, 1):
106
- st.info(f"{i}. {result}")
 
11
  chroma_client = chromadb.PersistentClient(path="./chroma_db")
12
  collection = chroma_client.get_or_create_collection(name="subtitles")
13
 
14
+ # Load Pickle Data
15
+ @st.cache_resource()
16
+ def load_pickle_data():
17
+ try:
18
+ with open("subtitle_embeddings.pkl", "rb") as f:
19
+ data = pickle.load(f)
20
+ # Add data to ChromaDB if not already present
21
+ for i, item in enumerate(data):
22
+ collection.upsert(
23
+ documents=[item['text']],
24
+ ids=[str(i)]
25
+ )
26
+ return data
27
+ except FileNotFoundError:
28
+ return []
29
+
30
+ pickle_data = load_pickle_data()
31
+
32
  # App Title and Config
33
+ st.set_page_config(page_title="Subtitle Generator")
34
+ st.title("🎬 AI-Powered Subtitle Generator & Search")
35
+ st.markdown("Upload an audio file to generate subtitles using AI, or search for specific words within the subtitles.")
36
 
37
  # Load Whisper Model
38
  @st.cache_resource()
 
41
 
42
  whisper_model = load_model()
43
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
44
  # Format Time for SRT
45
  def format_time(seconds):
46
  hours = int(seconds // 3600)
 
49
  milliseconds = int((seconds % 1) * 1000)
50
  return f"{hours:02}:{minutes:02}:{seconds:02},{milliseconds:03}"
51
 
52
+ # Transcribe Audio and Store in ChromaDB
53
  @st.cache_resource()
54
  def transcribe_audio(audio_file):
55
  result = whisper_model.transcribe(audio_file, beam_size=1)
56
  segments = result['segments']
57
  subtitles = []
58
  plain_subtitles = []
59
+
60
+ for i, segment in enumerate(segments):
61
  start_time = format_time(segment['start'])
62
  end_time = format_time(segment['end'])
63
  text = segment['text']
64
+ subtitles.append(f"{i+1}\n{start_time} --> {end_time}\n{text}\n")
65
  plain_subtitles.append(text)
66
+
67
+ # Store into ChromaDB
68
+ collection.upsert(
69
+ documents=[text],
70
+ ids=[f"transcribe_{i}"]
71
+ )
72
+
73
  return "\n".join(subtitles), " ".join(plain_subtitles)
74
 
75
+ # Search Function using ChromaDB
76
+ def search_subtitles(query):
77
+ results = collection.query(query_texts=[query], n_results=5)
78
+ return results['documents'][0] if results and 'documents' in results else []
79
 
80
+ # Tabs for Subtitles and Search
81
+ tab1, tab2 = st.tabs(["Generate Subtitles", "Search Subtitles"])
82
 
83
+ # Tab 1: Generate Subtitles
84
  with tab1:
85
  st.markdown("### Upload Section")
86
  uploaded_file = st.file_uploader("Upload Audio File (MP3, WAV)", type=["mp3", "wav"])
 
103
  st.text_area("Subtitles (SRT Format)", transcribed_text, height=300)
104
  st.download_button("Download Subtitles (SRT)", transcribed_text, file_name="subtitles.srt", mime="text/plain")
105
  st.download_button("Download Subtitles (Plain Text)", plain_text, file_name="subtitles.txt", mime="text/plain")
 
106
 
107
+ os.remove(temp_audio_path)
108
+ st.success("Process completed successfully!")
109
+
110
+ # Tab 2: Search Subtitles
111
  with tab2:
112
+ st.markdown("### 🔎 Search Subtitles")
113
+ search_query = st.text_input("Enter a word or phrase to search within the subtitles")
114
+ if search_query:
115
+ with st.spinner('Searching subtitles...'):
116
+ search_results = search_subtitles(search_query)
117
+ if search_results:
118
+ st.write("### Top 5 Search Results")
119
+ for i, result in enumerate(search_results, 1):
120
+ st.write(f"{i}. {result}")
121
+ else:
122
+ st.warning("No matching subtitles found.")