mzaeem30 commited on
Commit
3bcdc07
·
verified ·
1 Parent(s): db684a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +112 -71
app.py CHANGED
@@ -1,87 +1,128 @@
1
- import os
2
  import gradio as gr
3
- import faiss
4
- import numpy as np
5
  import torch
6
- from langchain_community.vectorstores import FAISS # Updated import for FAISS
7
- from langchain_community.embeddings import SentenceTransformerEmbeddings
8
- from langchain_community.llms import OpenAI # Use Groq API or your LLM here
9
- import PyPDF2
10
- from gtts import gTTS
11
  import whisper
12
- from groq import GroqClient # Corrected import for Groq SDK
 
 
 
 
 
 
 
 
 
 
 
13
 
14
- # Initialize FAISS vector store and embeddings
15
- embedding_model = SentenceTransformerEmbeddings("all-MiniLM-L6-v2")
16
 
17
- # Function to process PDF and create embeddings
18
- def process_pdf(pdf_file):
19
- with open(pdf_file, 'rb') as f:
20
- reader = PyPDF2.PdfReader(f)
21
- text = ""
22
- for page in reader.pages:
23
- text += page.extract_text()
24
-
25
- # Create embeddings for the extracted text from PDF
26
- embeddings = embedding_model.embed(text.split("\n"))
27
-
28
- # Create FAISS index for embeddings
29
- index = faiss.IndexFlatL2(embedding_model.embedding_dim)
30
- index.add(np.array(embeddings).astype(np.float32)) # Convert embeddings to float32 format for FAISS
31
-
32
- return index, text
33
 
34
- # Set up Groq API for LLM interaction using GroqClient
35
- def generate_answer_from_llm(query, model="groq"):
36
- client = GroqClient(api_key="your_api_key") # Initialize the Groq client with your API key
37
- response = client.query(model=model, text=query) # Call the Groq API to get the answer
38
- return response['answer']
39
 
40
- # Main processing function for user input
41
- def process_input(query, pdf_file=None):
42
- # If PDF is provided, process it to create embeddings
43
- if pdf_file is not None:
44
- index, pdf_text = process_pdf(pdf_file)
45
- # Retrieve answer based on closest match from the PDF embeddings
46
- faiss_results = index.search(np.array([embedding_model.embed(query)]).astype(np.float32), k=1)
47
- answer = pdf_text[faiss_results[1][0]] # Adjust to retrieve the closest text chunk
48
- else:
49
- # If no PDF, generate a general answer using LLM via Groq API
50
- answer = generate_answer_from_llm(query)
51
 
52
- # Convert answer to speech
53
- tts = gTTS(answer)
54
- audio_fp = "/tmp/response.mp3"
55
- tts.save(audio_fp)
 
 
56
 
57
- return answer, audio_fp
 
 
 
 
 
 
 
58
 
59
- # Speech-to-Text (Whisper) function
60
- def speech_to_text(audio_file):
61
- model = whisper.load_model("base") # Load the OpenAI Whisper model (open-source)
62
- result = model.transcribe(audio_file)
63
- return result["text"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
- # Gradio interface
66
- def create_ui():
67
- with gr.Blocks() as demo:
68
- gr.Markdown("### Welcome to the AI-Powered Chatbot with RAG and Voice Input")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
- with gr.Row():
71
- pdf_upload = gr.File(label="Upload PDF File", type="file")
72
- query_input = gr.Textbox(label="Ask your question", placeholder="Type your query here")
73
- output_text = gr.Textbox(label="Answer", interactive=False)
74
- output_audio = gr.Audio(label="Response Audio", interactive=False)
75
 
76
- def on_query_submit(query, pdf_file):
77
- answer, audio_fp = process_input(query, pdf_file)
78
- output_text.update(value=answer)
79
- output_audio.update(value=audio_fp)
80
 
81
- query_input.submit(on_query_submit, inputs=[query_input, pdf_upload], outputs=[output_text, output_audio])
 
 
 
82
 
83
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
 
85
- # Run the Gradio app
86
- if __name__ == "__main__":
87
- create_ui()
 
 
1
  import gradio as gr
 
 
2
  import torch
 
 
 
 
 
3
  import whisper
4
+ from langchain_community.embeddings import HuggingFaceEmbeddings
5
+ from langchain.vectorstores import FAISS
6
+ from langchain.chains import RetrievalQA
7
+ from langchain.agents import initialize_agent, Tool, AgentType
8
+ from langchain.prompts import PromptTemplate
9
+ from langchain.memory import ConversationBufferMemory
10
+ from gtts import gTTS
11
+ import os
12
+ import PyPDF2
13
+ from groq import Groq
14
+ from sentence_transformers import SentenceTransformer
15
+ import numpy as np
16
 
17
+ # Load Whisper model for transcription
18
+ model = whisper.load_model("base")
19
 
20
+ # Initialize Groq client
21
+ client = Groq(api_key="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")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
+ # Initialize SentenceTransformer for PDF embedding
24
+ sentence_model = SentenceTransformer('all-MiniLM-L6-v2')
 
 
 
25
 
26
+ # Function to transcribe audio
27
+ def transcribe_audio(audio):
28
+ result = model.transcribe(audio)
29
+ return result["text"]
 
 
 
 
 
 
 
30
 
31
+ # Function for text-to-speech conversion
32
+ def text_to_speech(text):
33
+ tts = gTTS(text)
34
+ audio_path = "/tmp/response.mp3"
35
+ tts.save(audio_path)
36
+ return audio_path
37
 
38
+ # Function to interact with Groq API for LLM responses
39
+ def get_groq_response(question):
40
+ # Use Groq API to get the answer from LLM
41
+ chat_completion = client.chat.completions.create(
42
+ messages=[{"role": "user", "content": question}],
43
+ model="llama-3.3-70b-versatile",
44
+ )
45
+ return chat_completion.choices[0].message.content
46
 
47
+ # PDF Processing (chunking, embedding, FAISS)
48
+ def process_pdf(file):
49
+ # Extract text from PDF
50
+ pdf_reader = PyPDF2.PdfReader(file)
51
+ text = ""
52
+ for page in range(len(pdf_reader.pages)):
53
+ text += pdf_reader.pages[page].extract_text()
54
+
55
+ # Chunk text into smaller pieces
56
+ chunk_size = 500 # Can adjust based on requirement
57
+ chunks = [text[i:i + chunk_size] for i in range(0, len(text), chunk_size)]
58
+
59
+ # Generate embeddings using SentenceTransformer
60
+ embeddings = sentence_model.encode(chunks)
61
+
62
+ # Store embeddings in FAISS index
63
+ faiss_index = FAISS.from_embeddings(embeddings)
64
+
65
+ return faiss_index, chunks
66
 
67
+ # Function to handle query against PDF embedding
68
+ def get_pdf_response(query, faiss_index):
69
+ # Retrieve relevant chunk based on query
70
+ results = faiss_index.similarity_search(query, k=1) # Adjust k based on requirement
71
+
72
+ # Get the best match and return
73
+ return results[0].document
74
+
75
+ # Initialize Gradio components
76
+ with gr.Blocks(css="#output_text { font-size: 18px; margin: 10px 0; }"
77
+ "#output_audio { margin-top: 15px; }"
78
+ "gradio .gradio-container { background-color: #f8f9fa; border-radius: 15px; padding: 20px; box-shadow: 0 4px 8px rgba(0,0,0,0.1); }"
79
+ "gradio .gradio-interface { font-family: 'Arial', sans-serif; }") as demo:
80
+ gr.Markdown("""
81
+ # Quranic Therapy: Gen-AI Driven Mental Health & Wellness
82
+ ## Where Faith Meets Technology
83
+ Interact with the model using your voice or text input and get answers from documents!
84
+ """, elem_id="header")
85
+
86
+ with gr.Row():
87
+ with gr.Column(scale=2):
88
+ gr.Markdown("### Record or Upload Audio")
89
+ audio_input = gr.Audio(type="filepath", label="Record or Upload Audio", elem_id="audio_input")
90
 
91
+ with gr.Column(scale=3):
92
+ gr.Markdown("### Ask Your Question")
93
+ text_input = gr.Textbox(label="Enter your question", placeholder="Ask a question based on the document...", elem_id="text_input")
 
 
94
 
95
+ with gr.Column(scale=3):
96
+ gr.Markdown("### Upload PDF Document")
97
+ pdf_input = gr.File(label="Upload PDF", type="file", elem_id="pdf_input")
 
98
 
99
+ with gr.Row():
100
+ with gr.Column(scale=5):
101
+ output_text = gr.Textbox(label="Answer", elem_id="output_text", interactive=False)
102
+ output_audio = gr.Audio(label="Voice Response", type="filepath", elem_id="output_audio")
103
 
104
+ # Button to process the input and generate output
105
+ def process_input(audio_input, text_input, pdf_input):
106
+ if audio_input:
107
+ question = transcribe_audio(audio_input)
108
+ else:
109
+ question = text_input
110
+
111
+ # If PDF uploaded, use FAISS for RAG
112
+ if pdf_input:
113
+ faiss_index, _ = process_pdf(pdf_input)
114
+ answer = get_pdf_response(question, faiss_index)
115
+ else:
116
+ # Use Groq LLM for general response
117
+ answer = get_groq_response(question)
118
+
119
+ # Convert the answer to speech and return both text and audio
120
+ audio_path = text_to_speech(answer)
121
+ return answer, audio_path
122
+
123
+ # Bind the function to the interface
124
+ audio_input.change(process_input, inputs=[audio_input, text_input, pdf_input], outputs=[output_text, output_audio])
125
+ text_input.submit(process_input, inputs=[audio_input, text_input, pdf_input], outputs=[output_text, output_audio])
126
+ pdf_input.change(process_input, inputs=[audio_input, text_input, pdf_input], outputs=[output_text, output_audio])
127
 
128
+ demo.launch(debug=True)