nishayaseen001 commited on
Commit
445dcdd
·
verified ·
1 Parent(s): e563f4a

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -0
app.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import requests
4
+ from bs4 import BeautifulSoup
5
+ from youtube_transcript_api import YouTubeTranscriptApi
6
+ from pytube import YouTube
7
+ from PyPDF2 import PdfReader
8
+ import docx
9
+ import pptx
10
+ import faiss
11
+ import numpy as np
12
+
13
+ from groq import Groq
14
+
15
+ # Initialize Groq client
16
+ client = Groq(api_key=os.environ.get("MY_API"))
17
+
18
+ # -------------------------------
19
+ # Global storage for embeddings + chunks
20
+ # -------------------------------
21
+ global_index = None
22
+ global_chunks = []
23
+
24
+ # -------------------------------
25
+ # Utility Functions
26
+ # -------------------------------
27
+
28
+ def chunk_text(text, chunk_size=500):
29
+ return [text[i:i+chunk_size] for i in range(0, len(text), chunk_size)]
30
+
31
+ def embed_text(chunks):
32
+ return [np.random.rand(768).astype("float32") for _ in chunks]
33
+
34
+ def store_in_faiss(embeddings):
35
+ dim = len(embeddings[0])
36
+ index = faiss.IndexFlatL2(dim)
37
+ index.add(np.array(embeddings))
38
+ return index
39
+
40
+ def summarize_text(text):
41
+ chat_completion = client.chat.completions.create(
42
+ messages=[{"role": "user", "content": f"Summarize this text:\n{text}"}],
43
+ model="llama-3.1-8b-instant",
44
+ )
45
+ return chat_completion.choices[0].message.content
46
+
47
+ def generate_mcqs(text):
48
+ chat_completion = client.chat.completions.create(
49
+ messages=[{"role": "user", "content": f"Generate 20 MCQs with answers from:\n{text}"}],
50
+ model="llama-3.1-8b-instant",
51
+ )
52
+ return chat_completion.choices[0].message.content
53
+
54
+ def answer_question(question):
55
+ """Answer user question based on stored chunks using Groq."""
56
+ if not global_chunks:
57
+ return "No data loaded yet. Please upload a document, website, or YouTube video first."
58
+
59
+ context = " ".join(global_chunks[:10]) # simple retrieval (first 10 chunks)
60
+ chat_completion = client.chat.completions.create(
61
+ messages=[{"role": "user", "content": f"Answer the question based on context:\n{context}\n\nQuestion: {question}"}],
62
+ model="llama-3.1-8b-instant",
63
+ )
64
+ return chat_completion.choices[0].message.content
65
+
66
+ # -------------------------------
67
+ # Input Handlers
68
+ # -------------------------------
69
+
70
+ def process_document(file):
71
+ if file.name.endswith(".pdf"):
72
+ reader = PdfReader(file)
73
+ text = " ".join([page.extract_text() for page in reader.pages])
74
+ elif file.name.endswith(".docx"):
75
+ doc = docx.Document(file)
76
+ text = " ".join([para.text for para in doc.paragraphs])
77
+ elif file.name.endswith(".pptx"):
78
+ pres = pptx.Presentation(file)
79
+ text = " ".join([shape.text for slide in pres.slides for shape in slide.shapes if hasattr(shape, "text")])
80
+ else:
81
+ text = file.read().decode("utf-8")
82
+ return text
83
+
84
+ def process_website(url):
85
+ response = requests.get(url)
86
+ soup = BeautifulSoup(response.text, "html.parser")
87
+ return " ".join([p.get_text() for p in soup.find_all("p")])
88
+
89
+ def process_youtube(url):
90
+ yt = YouTube(url)
91
+ video_id = yt.video_id
92
+ transcript = YouTubeTranscriptApi.get_transcript(video_id)
93
+ return " ".join([t["text"] for t in transcript])
94
+
95
+ # -------------------------------
96
+ # Main Pipeline
97
+ # -------------------------------
98
+
99
+ def rag_pipeline(input_type, input_data):
100
+ global global_index, global_chunks
101
+
102
+ if input_type == "Document":
103
+ text = process_document(input_data)
104
+ elif input_type == "Website":
105
+ text = process_website(input_data)
106
+ elif input_type == "YouTube":
107
+ text = process_youtube(input_data)
108
+ else:
109
+ return "Invalid input type", "Invalid input type"
110
+
111
+ # Chunk, embed, store
112
+ chunks = chunk_text(text)
113
+ embeddings = embed_text(chunks)
114
+ index = store_in_faiss(embeddings)
115
+
116
+ # Save globally for chatbot
117
+ global_index = index
118
+ global_chunks = chunks
119
+
120
+ # Summarize + MCQs
121
+ summary = summarize_text(text)
122
+ mcqs = generate_mcqs(text)
123
+
124
+ return summary, mcqs
125
+
126
+ # -------------------------------
127
+ # Gradio UI
128
+ # -------------------------------
129
+
130
+ with gr.Blocks() as demo:
131
+ gr.Markdown("# 📚 RAG-based Knowledge Assistant (Groq + FAISS + Gradio)")
132
+
133
+ with gr.Tab("Upload Document"):
134
+ doc_input = gr.File(label="Upload PDF/DOCX/PPTX")
135
+ doc_output_summary = gr.Textbox(label="Summary")
136
+ doc_output_mcqs = gr.Textbox(label="MCQs")
137
+ doc_button = gr.Button("Process Document")
138
+ doc_button.click(rag_pipeline, inputs=["Document", doc_input], outputs=[doc_output_summary, doc_output_mcqs])
139
+
140
+ with gr.Tab("Website"):
141
+ web_input = gr.Textbox(label="Enter Website URL")
142
+ web_output_summary = gr.Textbox(label="Summary")
143
+ web_output_mcqs = gr.Textbox(label="MCQs")
144
+ web_button = gr.Button("Process Website")
145
+ web_button.click(rag_pipeline, inputs=["Website", web_input], outputs=[web_output_summary, web_output_mcqs])
146
+
147
+ with gr.Tab("YouTube"):
148
+ yt_input = gr.Textbox(label="Enter YouTube URL")
149
+ yt_output_summary = gr.Textbox(label="Summary")
150
+ yt_output_mcqs = gr.Textbox(label="MCQs")
151
+ yt_button = gr.Button("Process YouTube")
152
+ yt_button.click(rag_pipeline, inputs=["YouTube", yt_input], outputs=[yt_output_summary, yt_output_mcqs])
153
+
154
+ with gr.Tab("Chatbot"):
155
+ chatbot_input = gr.Textbox(label="Ask a question about your uploaded content")
156
+ chatbot_output = gr.Textbox(label="Answer")
157
+ chatbot_button = gr.Button("Ask")
158
+ chatbot_button.click(answer_question, inputs=chatbot_input, outputs=chatbot_output)
159
+
160
+ demo.launch()