Spaces:
Sleeping
Sleeping
Madiharehan
commited on
Commit
β’
454484f
1
Parent(s):
5af8d29
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
import streamlit as st
|
4 |
+
from io import BytesIO
|
5 |
+
from PyPDF2 import PdfReader
|
6 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
7 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
8 |
+
from langchain.vectorstores import FAISS
|
9 |
+
from transformers import pipeline
|
10 |
+
import torch
|
11 |
+
|
12 |
+
# Set up the page configuration as the first Streamlit command
|
13 |
+
st.set_page_config(page_title="RAG-based PDF Chat", layout="centered", page_icon="π")
|
14 |
+
|
15 |
+
# Load the summarization pipeline model
|
16 |
+
@st.cache_resource
|
17 |
+
def load_summarization_pipeline():
|
18 |
+
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")
|
19 |
+
return summarizer
|
20 |
+
|
21 |
+
summarizer = load_summarization_pipeline()
|
22 |
+
|
23 |
+
# Dictionary of Hugging Face PDF URLs grouped by folders
|
24 |
+
PDF_FOLDERS = {
|
25 |
+
"PPC and Administration": [
|
26 |
+
"https://huggingface.co/spaces/tahirsher/GenAI_Lawyers_Guide/tree/main/PPC%20and%20Administration",
|
27 |
+
],
|
28 |
+
"IHC": [
|
29 |
+
"https://huggingface.co/spaces/tahirsher/GenAI_Lawyers_Guide/tree/main/IHC"
|
30 |
+
"LHC": [
|
31 |
+
"https://huggingface.co/spaces/tahirsher/GenAI_Lawyers_Guide/tree/main/LHC"
|
32 |
+
"Lahore High Court Rules and Orders": [
|
33 |
+
"https://huggingface.co/spaces/tahirsher/GenAI_Lawyers_Guide/tree/main/Lahore%20High%20Court%20Rules%20and%20Orders"
|
34 |
+
"PHC": [
|
35 |
+
"https://huggingface.co/spaces/tahirsher/GenAI_Lawyers_Guide/tree/main/PHC"
|
36 |
+
"SC": [
|
37 |
+
"https://huggingface.co/spaces/tahirsher/GenAI_Lawyers_Guide/tree/main/SC"
|
38 |
+
],
|
39 |
+
}
|
40 |
+
|
41 |
+
# Helper function to convert Hugging Face blob URLs to direct download URLs
|
42 |
+
def get_huggingface_raw_url(url):
|
43 |
+
if "huggingface.co" in url and "/blob/" in url:
|
44 |
+
return url.replace("/blob/", "/resolve/")
|
45 |
+
return url
|
46 |
+
|
47 |
+
# Fetch and extract text from all PDFs in specified folders
|
48 |
+
def fetch_pdf_text_from_folders(pdf_folders):
|
49 |
+
all_text = ""
|
50 |
+
for folder_name, urls in pdf_folders.items():
|
51 |
+
folder_text = f"\n[Folder: {folder_name}]\n"
|
52 |
+
for url in urls:
|
53 |
+
raw_url = get_huggingface_raw_url(url)
|
54 |
+
response = requests.get(raw_url)
|
55 |
+
if response.status_code == 200:
|
56 |
+
pdf_file = BytesIO(response.content)
|
57 |
+
try:
|
58 |
+
pdf_reader = PdfReader(pdf_file)
|
59 |
+
for page in pdf_reader.pages:
|
60 |
+
page_text = page.extract_text()
|
61 |
+
if page_text:
|
62 |
+
folder_text += page_text
|
63 |
+
except Exception as e:
|
64 |
+
st.error(f"Failed to read PDF from URL {url}: {e}")
|
65 |
+
else:
|
66 |
+
st.error(f"Failed to fetch PDF from URL: {url}")
|
67 |
+
all_text += folder_text
|
68 |
+
return all_text
|
69 |
+
|
70 |
+
# Split text into manageable chunks
|
71 |
+
@st.cache_data
|
72 |
+
def get_text_chunks(text):
|
73 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=10000, chunk_overlap=1000)
|
74 |
+
chunks = text_splitter.split_text(text)
|
75 |
+
return chunks
|
76 |
+
|
77 |
+
# Initialize embedding function
|
78 |
+
embedding_function = HuggingFaceEmbeddings(model_name="sentence-transformers/all-MiniLM-L6-v2")
|
79 |
+
|
80 |
+
# Create a FAISS vector store with embeddings
|
81 |
+
@st.cache_resource
|
82 |
+
def load_or_create_vector_store(text_chunks):
|
83 |
+
vector_store = FAISS.from_texts(text_chunks, embedding=embedding_function)
|
84 |
+
return vector_store
|
85 |
+
|
86 |
+
# Generate summary based on the retrieved text
|
87 |
+
def generate_summary_with_huggingface(query, retrieved_text):
|
88 |
+
summarization_input = f"{query}\n\nRelated information:\n{retrieved_text}"
|
89 |
+
max_input_length = 1024
|
90 |
+
summarization_input = summarization_input[:max_input_length]
|
91 |
+
summary = summarizer(summarization_input, max_length=500, min_length=50, do_sample=False)
|
92 |
+
return summary[0]["summary_text"]
|
93 |
+
|
94 |
+
# Generate response for user query
|
95 |
+
def user_input(user_question, vector_store):
|
96 |
+
docs = vector_store.similarity_search(user_question)
|
97 |
+
context_text = " ".join([doc.page_content for doc in docs])
|
98 |
+
return generate_summary_with_huggingface(user_question, context_text)
|
99 |
+
|
100 |
+
# Main function to run the Streamlit app
|
101 |
+
def main():
|
102 |
+
st.title("π Gen AI Lawyers Guide")
|
103 |
+
raw_text = fetch_pdf_text_from_folders(PDF_FOLDERS)
|
104 |
+
text_chunks = get_text_chunks(raw_text)
|
105 |
+
vector_store = load_or_create_vector_store(text_chunks)
|
106 |
+
|
107 |
+
user_question = st.text_input("Ask a Question:", placeholder="Type your question here...")
|
108 |
+
|
109 |
+
if st.button("Get Response"):
|
110 |
+
if not user_question:
|
111 |
+
st.warning("Please enter a question before submitting.")
|
112 |
+
else:
|
113 |
+
with st.spinner("Generating response..."):
|
114 |
+
answer = user_input(user_question, vector_store)
|
115 |
+
st.markdown(f"**π€ AI:** {answer}")
|
116 |
+
|
117 |
+
if __name__ == "__main__":
|
118 |
+
main()
|
119 |
+
|