CookingFAQ / app.py
aspect2309's picture
Update app.py
a58be8e verified
import pandas as pd
import faiss
import numpy as np
from sentence_transformers import SentenceTransformer
import gradio as gr
from gtts import gTTS
import os
# STEP 1: Load your CSV data
data = pd.read_csv("./data.csv")
# STEP 2: Clean the data
data = data.dropna(subset=["question", "answer"]).reset_index(drop=True)
data["question"] = data["question"].astype(str)
data["answer"] = data["answer"].astype(str)
# STEP 3: Load sentence embedding model
model = SentenceTransformer("all-MiniLM-L6-v2")
# STEP 4: Generate embeddings and FAISS index
embeddings = model.encode(data['question'].tolist())
index = faiss.IndexFlatL2(embeddings.shape[1])
index.add(np.array(embeddings))
# βœ… STEP 5: Define the function with TTS
def answer_with_audio(user_input):
query_embedding = model.encode([user_input])
_, I = index.search(np.array(query_embedding), k=1)
answer = data.iloc[I[0][0]]['answer']
# Convert answer to speech using gTTS
tts = gTTS(answer)
tts_path = "/tmp/tts_output.mp3"
tts.save(tts_path)
return answer, tts_path
# βœ… STEP 6: Create Gradio interface with text + audio output
gr.Interface(
fn=answer_with_audio,
inputs=gr.Textbox(lines=2, placeholder="Ask your question..."),
outputs=["text", "audio"],
title="πŸ”Š Cooking FAQ ",
description="Ask your question and listen to the response.",
).launch()