Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1 |
-
# app.py
|
2 |
import os
|
3 |
import gradio as gr
|
4 |
from langchain_community.vectorstores import FAISS
|
@@ -9,64 +8,74 @@ from langchain.chains import RetrievalQA
|
|
9 |
from langchain_community.llms import HuggingFaceEndpoint
|
10 |
from huggingface_hub import login
|
11 |
|
12 |
-
#
|
13 |
if not os.environ.get('HF_TOKEN'):
|
14 |
-
raise
|
15 |
login(token=os.environ.get('HF_TOKEN'))
|
16 |
|
17 |
-
# 2. PDF processing with error handling
|
18 |
def create_qa_system():
|
19 |
try:
|
20 |
-
#
|
21 |
if not os.path.exists("file.pdf"):
|
22 |
-
raise FileNotFoundError("PDF
|
23 |
|
24 |
-
#
|
25 |
loader = PyMuPDFLoader("file.pdf")
|
26 |
documents = loader.load()
|
27 |
if len(documents) == 0:
|
28 |
-
raise ValueError("PDF
|
29 |
-
|
30 |
-
#
|
31 |
-
text_splitter = CharacterTextSplitter(
|
|
|
|
|
|
|
32 |
texts = text_splitter.split_documents(documents)
|
33 |
|
|
|
34 |
embeddings = HuggingFaceEmbeddings(
|
35 |
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
36 |
)
|
37 |
|
|
|
38 |
db = FAISS.from_documents(texts, embeddings)
|
39 |
|
40 |
-
#
|
41 |
llm = HuggingFaceEndpoint(
|
42 |
repo_id="google/flan-t5-small",
|
43 |
-
|
44 |
-
|
|
|
|
|
|
|
45 |
huggingfacehub_api_token=os.environ.get('HF_TOKEN')
|
46 |
)
|
47 |
|
48 |
return RetrievalQA.from_chain_type(
|
49 |
llm=llm,
|
50 |
chain_type="stuff",
|
51 |
-
retriever=db.as_retriever(search_kwargs={"k":
|
52 |
-
) # Closing parenthesis added here
|
53 |
except Exception as e:
|
54 |
-
raise gr.Error(f"
|
55 |
|
56 |
-
#
|
57 |
try:
|
58 |
qa = create_qa_system()
|
59 |
except Exception as e:
|
60 |
-
print(f"
|
61 |
raise
|
62 |
|
63 |
-
# 4. Chat interface with error messages
|
64 |
def chat_response(message, history):
|
65 |
try:
|
66 |
response = qa({"query": message})
|
67 |
return response["result"]
|
68 |
except Exception as e:
|
69 |
-
print(f"
|
70 |
-
return f"Error: {str(e)}"
|
71 |
|
72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import os
|
2 |
import gradio as gr
|
3 |
from langchain_community.vectorstores import FAISS
|
|
|
8 |
from langchain_community.llms import HuggingFaceEndpoint
|
9 |
from huggingface_hub import login
|
10 |
|
11 |
+
# Authentication
|
12 |
if not os.environ.get('HF_TOKEN'):
|
13 |
+
raise ValueError("❌ Add HF_TOKEN in Space secrets!")
|
14 |
login(token=os.environ.get('HF_TOKEN'))
|
15 |
|
|
|
16 |
def create_qa_system():
|
17 |
try:
|
18 |
+
# Validate PDF
|
19 |
if not os.path.exists("file.pdf"):
|
20 |
+
raise FileNotFoundError("Upload PDF via Files tab")
|
21 |
|
22 |
+
# Process PDF
|
23 |
loader = PyMuPDFLoader("file.pdf")
|
24 |
documents = loader.load()
|
25 |
if len(documents) == 0:
|
26 |
+
raise ValueError("PDF is empty or corrupted")
|
27 |
+
|
28 |
+
# Split text
|
29 |
+
text_splitter = CharacterTextSplitter(
|
30 |
+
chunk_size=300,
|
31 |
+
chunk_overlap=50
|
32 |
+
)
|
33 |
texts = text_splitter.split_documents(documents)
|
34 |
|
35 |
+
# Create embeddings
|
36 |
embeddings = HuggingFaceEmbeddings(
|
37 |
model_name="sentence-transformers/all-MiniLM-L6-v2"
|
38 |
)
|
39 |
|
40 |
+
# Build vector store
|
41 |
db = FAISS.from_documents(texts, embeddings)
|
42 |
|
43 |
+
# Initialize LLM
|
44 |
llm = HuggingFaceEndpoint(
|
45 |
repo_id="google/flan-t5-small",
|
46 |
+
task="text2text-generation",
|
47 |
+
model_kwargs={
|
48 |
+
"temperature": 0.2,
|
49 |
+
"max_length": 128
|
50 |
+
},
|
51 |
huggingfacehub_api_token=os.environ.get('HF_TOKEN')
|
52 |
)
|
53 |
|
54 |
return RetrievalQA.from_chain_type(
|
55 |
llm=llm,
|
56 |
chain_type="stuff",
|
57 |
+
retriever=db.as_retriever(search_kwargs={"k": 2})
|
|
|
58 |
except Exception as e:
|
59 |
+
raise gr.Error(f"Initialization failed: {str(e)}")
|
60 |
|
61 |
+
# Initialize system
|
62 |
try:
|
63 |
qa = create_qa_system()
|
64 |
except Exception as e:
|
65 |
+
print(f"Fatal error: {str(e)}")
|
66 |
raise
|
67 |
|
|
|
68 |
def chat_response(message, history):
|
69 |
try:
|
70 |
response = qa({"query": message})
|
71 |
return response["result"]
|
72 |
except Exception as e:
|
73 |
+
print(f"Error during query: {str(e)}")
|
74 |
+
return f"⚠️ Error: {str(e)[:100]}"
|
75 |
|
76 |
+
# Create interface
|
77 |
+
gr.ChatInterface(
|
78 |
+
chat_response,
|
79 |
+
title="PDF Chat Assistant",
|
80 |
+
description="Ask questions about your PDF document"
|
81 |
+
).launch()
|