Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import sqlite3
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import re
|
| 6 |
+
import speech_recognition as sr
|
| 7 |
+
from sklearn.feature_extraction.text import TfidfVectorizer
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
from chromadb import Client
|
| 10 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 11 |
+
import threading
|
| 12 |
+
|
| 13 |
+
# Step 1: Read and Decode Data from SQLite Database
|
| 14 |
+
def load_data():
|
| 15 |
+
conn = sqlite3.connect("eng_subtitles_database.db")
|
| 16 |
+
query = "SELECT * FROM subtitles"
|
| 17 |
+
df = pd.read_sql_query(query, conn)
|
| 18 |
+
conn.close()
|
| 19 |
+
return df
|
| 20 |
+
|
| 21 |
+
# Step 2: Data Cleaning
|
| 22 |
+
def clean_text(text):
|
| 23 |
+
text = re.sub(r'\[.*?\]', '', text) # Remove timestamps
|
| 24 |
+
text = re.sub(r'[^a-zA-Z0-9\s]', '', text) # Remove special characters
|
| 25 |
+
return text.lower()
|
| 26 |
+
|
| 27 |
+
# Step 3: Data Sampling (Optional)
|
| 28 |
+
def sample_data(df, sample_fraction=0.3):
|
| 29 |
+
return df.sample(frac=sample_fraction, random_state=42)
|
| 30 |
+
|
| 31 |
+
# Step 4: Document Chunking with Overlap
|
| 32 |
+
def chunk_document(text, chunk_size=500, overlap=50):
|
| 33 |
+
words = text.split()
|
| 34 |
+
chunks = []
|
| 35 |
+
for i in range(0, len(words), chunk_size - overlap):
|
| 36 |
+
chunk = ' '.join(words[i:i+chunk_size])
|
| 37 |
+
chunks.append(chunk)
|
| 38 |
+
return chunks
|
| 39 |
+
|
| 40 |
+
# Step 5: Generate Embeddings using Sentence Transformers
|
| 41 |
+
def generate_embeddings(texts, model_name='sentence-transformers/all-MiniLM-L6-v2'):
|
| 42 |
+
model = SentenceTransformer(model_name)
|
| 43 |
+
return model.encode(texts)
|
| 44 |
+
|
| 45 |
+
# Step 6: Store Embeddings in ChromaDB
|
| 46 |
+
def store_in_chromadb(texts, embeddings):
|
| 47 |
+
client = Client()
|
| 48 |
+
collection = client.create_collection(name="video_subtitles")
|
| 49 |
+
for i, (text, embedding) in enumerate(zip(texts, embeddings)):
|
| 50 |
+
collection.add(ids=[str(i)], embeddings=[embedding.tolist()], metadatas=[{"text": text}])
|
| 51 |
+
print("Embeddings stored in ChromaDB.")
|
| 52 |
+
|
| 53 |
+
# Background Process
|
| 54 |
+
def background_processing():
|
| 55 |
+
try:
|
| 56 |
+
df = load_data()
|
| 57 |
+
df['clean_text'] = df['text'].apply(clean_text)
|
| 58 |
+
df = sample_data(df)
|
| 59 |
+
df['chunks'] = df['clean_text'].apply(lambda x: chunk_document(x))
|
| 60 |
+
all_chunks = [chunk for chunks in df['chunks'] for chunk in chunks]
|
| 61 |
+
|
| 62 |
+
embeddings = generate_embeddings(all_chunks)
|
| 63 |
+
store_in_chromadb(all_chunks, embeddings)
|
| 64 |
+
print("Data Processed and Stored in Background.")
|
| 65 |
+
except Exception as e:
|
| 66 |
+
print(f"Error in background processing: {e}")
|
| 67 |
+
|
| 68 |
+
# Start background processing using threading
|
| 69 |
+
thread = threading.Thread(target=background_processing)
|
| 70 |
+
thread.start()
|
| 71 |
+
|
| 72 |
+
# Step 7: Querying Process
|
| 73 |
+
def query_search(user_query, model_name='sentence-transformers/all-MiniLM-L6-v2'):
|
| 74 |
+
model = SentenceTransformer(model_name)
|
| 75 |
+
query_embedding = model.encode([user_query])[0]
|
| 76 |
+
|
| 77 |
+
# Retrieve from ChromaDB
|
| 78 |
+
client = Client()
|
| 79 |
+
collection = client.get_collection(name="video_subtitles")
|
| 80 |
+
results = collection.query(query_embeddings=[query_embedding.tolist()], n_results=5)
|
| 81 |
+
|
| 82 |
+
return results
|
| 83 |
+
|
| 84 |
+
# Step 8: Convert Audio to Text (Up to 2 Minutes)
|
| 85 |
+
def audio_to_text(audio_file=None):
|
| 86 |
+
recognizer = sr.Recognizer()
|
| 87 |
+
if audio_file:
|
| 88 |
+
with sr.AudioFile(audio_file) as source:
|
| 89 |
+
audio_data = recognizer.record(source, duration=120) # Up to 2 minutes
|
| 90 |
+
else:
|
| 91 |
+
with sr.Microphone() as source:
|
| 92 |
+
st.write("Listening... Speak now (up to 2 minutes)")
|
| 93 |
+
audio_data = recognizer.listen(source, timeout=120)
|
| 94 |
+
|
| 95 |
+
try:
|
| 96 |
+
text = recognizer.recognize_google(audio_data)
|
| 97 |
+
return text
|
| 98 |
+
except sr.UnknownValueError:
|
| 99 |
+
st.error("Could not understand the audio.")
|
| 100 |
+
except sr.RequestError:
|
| 101 |
+
st.error("Error connecting to the recognition service.")
|
| 102 |
+
return None
|
| 103 |
+
|
| 104 |
+
# Streamlit UI
|
| 105 |
+
st.title("Video Subtitle Search Engine")
|
| 106 |
+
st.header("Search Subtitles")
|
| 107 |
+
user_query = st.text_input("Enter your search query:")
|
| 108 |
+
|
| 109 |
+
st.subheader("Upload Audio for Search Query (Up to 2 Minutes) or Use Microphone")
|
| 110 |
+
audio_file = st.file_uploader("Upload Audio File", type=["wav", "mp3"])
|
| 111 |
+
use_microphone = st.checkbox("Use Microphone for Voice Input")
|
| 112 |
+
|
| 113 |
+
if st.button("Search"):
|
| 114 |
+
if audio_file:
|
| 115 |
+
user_query = audio_to_text(audio_file)
|
| 116 |
+
st.write(f"Converted Audio to Text: {user_query}")
|
| 117 |
+
elif use_microphone:
|
| 118 |
+
user_query = audio_to_text()
|
| 119 |
+
st.write(f"Converted Voice to Text: {user_query}")
|
| 120 |
+
|
| 121 |
+
if user_query:
|
| 122 |
+
results = query_search(user_query)
|
| 123 |
+
st.subheader("Top Results:")
|
| 124 |
+
for result in results["metadatas"][0]:
|
| 125 |
+
st.write(result["text"])
|