Spaces:
Running
Running
File size: 3,539 Bytes
ba765de | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 | import os
import gradio as gr
import faiss
import numpy as np
import gdown
from groq import Groq
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_community.document_loaders import PyPDFLoader
from langchain_huggingface import HuggingFaceEmbeddings
# ==============================
# π Load Groq API Key Securely
# ==============================
groq_api_key = os.environ.get("GROQ_API_KEY")
client = Groq(api_key=groq_api_key)
# ==============================
# π₯ Download Knowledge Base
# ==============================
FILE_ID = "1ppfRoaQik3h1Gr9A15xSOLGVpNQtm8eH"
DOWNLOAD_URL = f"https://drive.google.com/uc?id={FILE_ID}"
PDF_PATH = "knowledge_base.pdf"
if not os.path.exists(PDF_PATH):
gdown.download(DOWNLOAD_URL, PDF_PATH, quiet=False)
# ==============================
# π Create Vector Database
# ==============================
embedding_model = HuggingFaceEmbeddings(
model_name="sentence-transformers/all-MiniLM-L6-v2"
)
loader = PyPDFLoader(PDF_PATH)
documents = loader.load()
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=600,
chunk_overlap=150
)
chunks = text_splitter.split_documents(documents)
texts = [chunk.page_content for chunk in chunks]
embeddings = embedding_model.embed_documents(texts)
embeddings = np.array(embeddings).astype("float32")
dimension = embeddings.shape[1]
vector_store = faiss.IndexFlatL2(dimension)
vector_store.add(embeddings)
print("β
Knowledge Base Loaded Successfully")
# ==============================
# π€ RAG Function
# ==============================
def ask_question(question):
question_embedding = embedding_model.embed_query(question)
question_embedding = np.array([question_embedding]).astype("float32")
distances, indices = vector_store.search(question_embedding, k=4)
retrieved_texts = [texts[i] for i in indices[0]]
context = "\n\n".join(retrieved_texts)
prompt = f"""
You are an expert assistant.
Use ONLY the context below to answer clearly.
Format with headings and bullet points if needed.
CONTEXT:
{context}
QUESTION:
{question}
"""
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model="llama-3.3-70b-versatile",
)
answer = chat_completion.choices[0].message.content
return f"""
## π Answer
{answer}
"""
# ==============================
# π¨ Professional Yellow UI
# ==============================
custom_css = """
body {
background-color: #ffffff;
font-family: Arial, sans-serif;
}
.gradio-container {
background-color: #fffbea;
border-radius: 15px;
padding: 25px;
}
button {
background-color: #ffc107 !important;
color: black !important;
font-weight: bold !important;
border-radius: 10px !important;
}
textarea {
border-radius: 10px !important;
}
.answer-box {
background-color: white;
border: 2px solid #ffc107;
padding: 20px;
border-radius: 12px;
min-height: 250px;
}
"""
with gr.Blocks(css=custom_css) as app:
gr.Markdown(
"""
# π‘ KnowledgeBase AI Assistant
### Ask questions from my curated knowledge base
"""
)
question_input = gr.Textbox(
label="Enter Your Question",
placeholder="Ask something from the knowledge base..."
)
ask_button = gr.Button("Get Answer")
answer_output = gr.Markdown(elem_classes="answer-box")
ask_button.click(ask_question, inputs=question_input, outputs=answer_output)
app.launch() |