Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,21 +1,24 @@
|
|
1 |
import os
|
2 |
-
import faiss
|
3 |
-
import numpy as np
|
4 |
-
import PyPDF2
|
5 |
import io
|
|
|
|
|
6 |
from docx import Document
|
|
|
7 |
from nltk.tokenize import sent_tokenize
|
8 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
9 |
from sentence_transformers import SentenceTransformer
|
10 |
-
from langchain_community.vectorstores import FAISS
|
11 |
-
from langchain_community.embeddings import HuggingFaceEmbeddings
|
12 |
import gradio as gr
|
13 |
-
import pickle
|
14 |
|
15 |
# Download NLTK punkt tokenizer if not already downloaded
|
16 |
import nltk
|
17 |
nltk.download('punkt')
|
18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
19 |
# Function to extract text from a PDF file
|
20 |
def extract_text_from_pdf(pdf_data):
|
21 |
text = ""
|
@@ -37,37 +40,12 @@ def extract_text_from_docx(docx_data):
|
|
37 |
print(f"Error extracting text from DOCX: {e}")
|
38 |
return text
|
39 |
|
40 |
-
#
|
41 |
-
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
42 |
-
|
43 |
-
# Initialize Hugging Face API token
|
44 |
-
api_token = os.getenv('HUGGINGFACEHUB_API_TOKEN')
|
45 |
-
if not api_token:
|
46 |
-
raise ValueError("HUGGINGFACEHUB_API_TOKEN environment variable is not set")
|
47 |
-
|
48 |
-
# Initialize RAG models from Hugging Face
|
49 |
-
generator_model_name = "facebook/bart-base"
|
50 |
-
retriever_model_name = "facebook/bart-base"
|
51 |
-
generator = AutoModelForSeq2SeqLM.from_pretrained(generator_model_name)
|
52 |
-
generator_tokenizer = AutoTokenizer.from_pretrained(generator_model_name)
|
53 |
-
retriever = AutoModelForSeq2SeqLM.from_pretrained(retriever_model_name)
|
54 |
-
retriever_tokenizer = AutoTokenizer.from_pretrained(retriever_model_name)
|
55 |
-
|
56 |
-
# Initialize FAISS index using LangChain
|
57 |
-
hf_embeddings = HuggingFaceEmbeddings(model_name='sentence-transformers/all-MiniLM-L6-v2')
|
58 |
-
|
59 |
-
# Load or create FAISS index
|
60 |
-
index_path = "faiss_index.pkl"
|
61 |
-
if os.path.exists(index_path):
|
62 |
-
with open(index_path, "rb") as f:
|
63 |
-
faiss_index = pickle.load(f)
|
64 |
-
print("Loaded FAISS index from faiss_index.pkl")
|
65 |
-
else:
|
66 |
-
faiss_index = FAISS(embedding_function=hf_embeddings)
|
67 |
-
|
68 |
def preprocess_text(text):
|
69 |
sentences = sent_tokenize(text)
|
70 |
return sentences
|
|
|
|
|
71 |
def upload_files(files):
|
72 |
global faiss_index
|
73 |
try:
|
@@ -92,79 +70,51 @@ def upload_files(files):
|
|
92 |
|
93 |
# Encode sentences and add to FAISS index
|
94 |
embeddings = embedding_model.encode(sentences)
|
95 |
-
|
96 |
-
|
|
|
97 |
|
98 |
-
# Save the updated index
|
99 |
-
|
100 |
-
pickle.dump(faiss_index, f)
|
101 |
|
102 |
return {"message": "Files processed successfully"}
|
103 |
except Exception as e:
|
104 |
print(f"Error processing files: {e}")
|
105 |
return {"error": str(e)} # Provide informative error message
|
106 |
|
107 |
-
|
108 |
def process_and_query(state, question):
|
109 |
if question:
|
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 |
-
# Create Gradio interface
|
145 |
-
with gr.Interface(fn=None, live=True, capture_session=True) as demo:
|
146 |
-
gr.Markdown("## Document Upload and Query System")
|
147 |
-
|
148 |
-
with gr.Tab("Upload Files"):
|
149 |
-
upload = gr.File(file_count="multiple", label="Upload PDF or DOCX files")
|
150 |
-
upload_button = gr.Button("Upload")
|
151 |
-
upload_output = gr.Textbox()
|
152 |
-
upload_button.click(upload_files, inputs=upload, outputs=upload_output)
|
153 |
-
|
154 |
-
with gr.Tab("Query"):
|
155 |
-
query_input = gr.Textbox(label="Enter your query")
|
156 |
-
query_output = gr.Textbox()
|
157 |
-
|
158 |
-
# Define function to handle query and update state
|
159 |
-
def query_handler():
|
160 |
-
question = query_input.value # Get user's question from the input box
|
161 |
-
state = [] # Initialize or update state as needed
|
162 |
-
response = process_and_query(state, question) # Process query and retrieve response
|
163 |
-
query_output.value = response.get("message", "Error: No response") # Update output textbox
|
164 |
-
|
165 |
-
# Setup the click event with correct inputs and outputs
|
166 |
-
query_button = gr.Button("Search", click=query_handler)
|
167 |
-
demo.Interface(layout="vertical").launch()
|
168 |
-
|
169 |
-
|
170 |
-
|
|
|
1 |
import os
|
|
|
|
|
|
|
2 |
import io
|
3 |
+
import pickle
|
4 |
+
import PyPDF2
|
5 |
from docx import Document
|
6 |
+
import numpy as np
|
7 |
from nltk.tokenize import sent_tokenize
|
8 |
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
9 |
from sentence_transformers import SentenceTransformer
|
|
|
|
|
10 |
import gradio as gr
|
|
|
11 |
|
12 |
# Download NLTK punkt tokenizer if not already downloaded
|
13 |
import nltk
|
14 |
nltk.download('punkt')
|
15 |
|
16 |
+
# Initialize Sentence Transformer model for embeddings
|
17 |
+
embedding_model = SentenceTransformer('all-MiniLM-L6-v2')
|
18 |
+
|
19 |
+
# Initialize FAISS index using LangChain
|
20 |
+
faiss_index = None # Initialize or load your FAISS index as needed
|
21 |
+
|
22 |
# Function to extract text from a PDF file
|
23 |
def extract_text_from_pdf(pdf_data):
|
24 |
text = ""
|
|
|
40 |
print(f"Error extracting text from DOCX: {e}")
|
41 |
return text
|
42 |
|
43 |
+
# Function to preprocess text into sentences
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
44 |
def preprocess_text(text):
|
45 |
sentences = sent_tokenize(text)
|
46 |
return sentences
|
47 |
+
|
48 |
+
# Function to handle file uploads
|
49 |
def upload_files(files):
|
50 |
global faiss_index
|
51 |
try:
|
|
|
70 |
|
71 |
# Encode sentences and add to FAISS index
|
72 |
embeddings = embedding_model.encode(sentences)
|
73 |
+
if faiss_index is not None:
|
74 |
+
for embedding in embeddings:
|
75 |
+
faiss_index.add(np.expand_dims(embedding, axis=0))
|
76 |
|
77 |
+
# Save the updated index (if needed)
|
78 |
+
# Add your logic here to save the FAISS index if you're using persistence
|
|
|
79 |
|
80 |
return {"message": "Files processed successfully"}
|
81 |
except Exception as e:
|
82 |
print(f"Error processing files: {e}")
|
83 |
return {"error": str(e)} # Provide informative error message
|
84 |
|
85 |
+
# Function to process queries
|
86 |
def process_and_query(state, question):
|
87 |
if question:
|
88 |
+
try:
|
89 |
+
# Placeholder response based on query processing
|
90 |
+
response_message = "Placeholder response based on query processing"
|
91 |
+
return {"message": response_message, "conversation": state}
|
92 |
+
except Exception as e:
|
93 |
+
print(f"Error processing query: {e}")
|
94 |
+
return {"error": str(e)}
|
95 |
+
else:
|
96 |
+
return {"error": "No question provided"}
|
97 |
+
|
98 |
+
# Define the Gradio interface
|
99 |
+
def main():
|
100 |
+
gr.Interface(
|
101 |
+
fn=None, # Replace with your function that handles interface logic
|
102 |
+
inputs=gr.Interface.Layout([
|
103 |
+
gr.Tab("Upload Files", gr.Interface.Layout([
|
104 |
+
gr.File(label="Upload PDF or DOCX files", multiple=True),
|
105 |
+
gr.Button("Upload", onclick=upload_files),
|
106 |
+
gr.Textbox("Upload Status", default="No file uploaded yet", multiline=True)
|
107 |
+
])),
|
108 |
+
gr.Tab("Query", gr.Interface.Layout([
|
109 |
+
gr.Textbox("Enter your query", label="Query Input"),
|
110 |
+
gr.Button("Search", onclick=process_and_query),
|
111 |
+
gr.Textbox("Query Response", default="No query processed yet", multiline=True)
|
112 |
+
]))
|
113 |
+
]),
|
114 |
+
outputs=gr.Textbox("Output", label="Output", default="Output will be shown here", multiline=True),
|
115 |
+
live=True,
|
116 |
+
capture_session=True
|
117 |
+
).launch()
|
118 |
+
|
119 |
+
if __name__ == "__main__":
|
120 |
+
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|