Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import zipfile
|
3 |
+
import streamlit as st
|
4 |
+
from langchain_community.document_loaders import DirectoryLoader, TextLoader
|
5 |
+
from langchain_community.vectorstores import FAISS
|
6 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
7 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
8 |
+
|
9 |
+
# Step 1: Extract ZIP
|
10 |
+
def extract_zip(zip_path, extract_to):
|
11 |
+
if os.path.exists(zip_path) and not os.path.exists(extract_to):
|
12 |
+
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
13 |
+
zip_ref.extractall(extract_to)
|
14 |
+
st.success("β
Knowledge Base extracted successfully!")
|
15 |
+
|
16 |
+
# Step 2: Load and embed knowledge base
|
17 |
+
@st.cache_resource
|
18 |
+
def load_knowledge_base(folder_path):
|
19 |
+
loader = DirectoryLoader(folder_path, glob="*.md", loader_cls=TextLoader)
|
20 |
+
docs = loader.load()
|
21 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)
|
22 |
+
split_docs = splitter.split_documents(docs)
|
23 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/paraphrase-MiniLM-L6-v2")
|
24 |
+
db = FAISS.from_documents(split_docs, embeddings)
|
25 |
+
return db
|
26 |
+
|
27 |
+
# Streamlit UI
|
28 |
+
st.title("π Fitlytic Chatbot")
|
29 |
+
|
30 |
+
# Step 3: Extract ZIP if needed
|
31 |
+
zip_path = "Knowledge_Base.zip"
|
32 |
+
extract_to = "Knowledge_Base"
|
33 |
+
extract_zip(zip_path, extract_to)
|
34 |
+
|
35 |
+
# Step 4: Load knowledge base
|
36 |
+
if os.path.exists(extract_to):
|
37 |
+
db = load_knowledge_base(extract_to)
|
38 |
+
else:
|
39 |
+
st.error("β ZIP file not found or extraction failed.")
|
40 |
+
st.stop()
|
41 |
+
|
42 |
+
# Step 5: User interaction
|
43 |
+
query = st.text_input("Ask me anything about Fitlytic:")
|
44 |
+
if query:
|
45 |
+
results = db.similarity_search(query, k=1)
|
46 |
+
if results:
|
47 |
+
st.success(results[0].page_content)
|
48 |
+
else:
|
49 |
+
st.error("π Sorry, I couldn't find an answer. Try rephrasing it.")
|