Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,10 +16,26 @@ model_path = "nvidia/Mistral-NeMo-Minitron-8B-Base"
|
|
| 16 |
mistral_tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 17 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 18 |
dtype = torch.bfloat16
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
def initialize(file_path, question):
|
| 22 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
|
| 24 |
prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
|
| 25 |
not contained in the context, say "answer not available in context" \n\n
|
|
@@ -30,43 +46,86 @@ def initialize(file_path, question):
|
|
| 30 |
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
| 31 |
|
| 32 |
if os.path.exists(file_path):
|
|
|
|
| 33 |
pdf_loader = PyPDFLoader(file_path)
|
| 34 |
pages = pdf_loader.load_and_split()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
context = "\n".join(str(page.page_content) for page in pages[:30])
|
|
|
|
|
|
|
| 36 |
stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
|
| 37 |
-
stuff_answer = stuff_chain(
|
|
|
|
|
|
|
|
|
|
| 38 |
gemini_answer = stuff_answer['output_text']
|
| 39 |
|
| 40 |
# Use Mistral model for additional text generation
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
return combined_output
|
| 49 |
else:
|
| 50 |
-
return "Error:
|
| 51 |
except Exception as e:
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
input_file = gr.File(label="Upload PDF File")
|
| 56 |
-
input_question = gr.Textbox(label="Ask about the document")
|
| 57 |
-
output_text = gr.Textbox(label="Answer - Combined Gemini and Mistral")
|
| 58 |
|
|
|
|
| 59 |
def pdf_qa(file, question):
|
| 60 |
if file is None:
|
| 61 |
return "Please upload a PDF file first."
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
# Create Gradio Interface
|
| 65 |
-
gr.Interface(
|
| 66 |
fn=pdf_qa,
|
| 67 |
-
inputs=[
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
| 69 |
title="RAG Knowledge Retrieval using Gemini API and Mistral Model",
|
| 70 |
-
description="Upload a PDF file and ask questions about the content."
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
mistral_tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 17 |
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 18 |
dtype = torch.bfloat16
|
| 19 |
+
|
| 20 |
+
# Improved model loading with error handling
|
| 21 |
+
try:
|
| 22 |
+
mistral_model = AutoModelForCausalLM.from_pretrained(
|
| 23 |
+
model_path,
|
| 24 |
+
torch_dtype=dtype,
|
| 25 |
+
device_map=device
|
| 26 |
+
)
|
| 27 |
+
print(f"Mistral model loaded successfully on {device}")
|
| 28 |
+
except Exception as e:
|
| 29 |
+
print(f"Error loading Mistral model: {str(e)}")
|
| 30 |
+
mistral_model = None
|
| 31 |
|
| 32 |
def initialize(file_path, question):
|
| 33 |
try:
|
| 34 |
+
# Check if API key is set
|
| 35 |
+
api_key = os.getenv("GOOGLE_API_KEY")
|
| 36 |
+
if not api_key:
|
| 37 |
+
return "Error: GOOGLE_API_KEY environment variable is not set."
|
| 38 |
+
|
| 39 |
model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
|
| 40 |
prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
|
| 41 |
not contained in the context, say "answer not available in context" \n\n
|
|
|
|
| 46 |
prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
|
| 47 |
|
| 48 |
if os.path.exists(file_path):
|
| 49 |
+
# Load and process PDF
|
| 50 |
pdf_loader = PyPDFLoader(file_path)
|
| 51 |
pages = pdf_loader.load_and_split()
|
| 52 |
+
|
| 53 |
+
if not pages:
|
| 54 |
+
return "Error: The PDF file appears to be empty or could not be processed."
|
| 55 |
+
|
| 56 |
context = "\n".join(str(page.page_content) for page in pages[:30])
|
| 57 |
+
|
| 58 |
+
# Generate Gemini answer
|
| 59 |
stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
|
| 60 |
+
stuff_answer = stuff_chain(
|
| 61 |
+
{"input_documents": pages, "question": question, "context": context},
|
| 62 |
+
return_only_outputs=True
|
| 63 |
+
)
|
| 64 |
gemini_answer = stuff_answer['output_text']
|
| 65 |
|
| 66 |
# Use Mistral model for additional text generation
|
| 67 |
+
if mistral_model is not None:
|
| 68 |
+
mistral_prompt = f"Based on this answer: {gemini_answer}\nGenerate a follow-up question:"
|
| 69 |
+
mistral_inputs = mistral_tokenizer.encode(mistral_prompt, return_tensors='pt').to(device)
|
| 70 |
+
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
mistral_outputs = mistral_model.generate(
|
| 73 |
+
mistral_inputs,
|
| 74 |
+
max_length=200, # Increased max length
|
| 75 |
+
min_length=20, # Set min length
|
| 76 |
+
do_sample=True, # Enable sampling
|
| 77 |
+
top_p=0.95, # Top-p sampling
|
| 78 |
+
temperature=0.7 # Temperature for creativity
|
| 79 |
+
)
|
| 80 |
+
mistral_output = mistral_tokenizer.decode(mistral_outputs[0], skip_special_tokens=True)
|
| 81 |
+
# Clean up the output to get just the follow-up question
|
| 82 |
+
if "Generate a follow-up question:" in mistral_output:
|
| 83 |
+
mistral_output = mistral_output.split("Generate a follow-up question:")[1].strip()
|
| 84 |
+
|
| 85 |
+
combined_output = f"Gemini Answer: {gemini_answer}\n\nMistral Follow-up: {mistral_output}"
|
| 86 |
+
else:
|
| 87 |
+
combined_output = f"Gemini Answer: {gemini_answer}\n\n(Mistral model unavailable)"
|
| 88 |
+
|
| 89 |
return combined_output
|
| 90 |
else:
|
| 91 |
+
return f"Error: File not found at path '{file_path}'. Please ensure the PDF file is valid."
|
| 92 |
except Exception as e:
|
| 93 |
+
import traceback
|
| 94 |
+
error_details = traceback.format_exc()
|
| 95 |
+
return f"An error occurred: {str(e)}\n\nDetails: {error_details}"
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
# Define Gradio Interface with improved error handling
|
| 98 |
def pdf_qa(file, question):
|
| 99 |
if file is None:
|
| 100 |
return "Please upload a PDF file first."
|
| 101 |
+
|
| 102 |
+
if not question or question.strip() == "":
|
| 103 |
+
return "Please enter a question about the document."
|
| 104 |
+
|
| 105 |
+
try:
|
| 106 |
+
return initialize(file.name, question)
|
| 107 |
+
except Exception as e:
|
| 108 |
+
import traceback
|
| 109 |
+
error_details = traceback.format_exc()
|
| 110 |
+
return f"Error processing request: {str(e)}\n\nDetails: {error_details}"
|
| 111 |
|
| 112 |
+
# Create Gradio Interface with additional options
|
| 113 |
+
demo = gr.Interface(
|
| 114 |
fn=pdf_qa,
|
| 115 |
+
inputs=[
|
| 116 |
+
gr.File(label="Upload PDF File", file_types=[".pdf"]),
|
| 117 |
+
gr.Textbox(label="Ask about the document", placeholder="What is the main topic of this document?")
|
| 118 |
+
],
|
| 119 |
+
outputs=gr.Textbox(label="Answer - Combined Gemini and Mistral"),
|
| 120 |
title="RAG Knowledge Retrieval using Gemini API and Mistral Model",
|
| 121 |
+
description="Upload a PDF file and ask questions about the content. The system uses Gemini for answering and Mistral for generating follow-up questions.",
|
| 122 |
+
examples=[
|
| 123 |
+
[None, "What are the main findings in this document?"],
|
| 124 |
+
[None, "Summarize the key points discussed in this paper."]
|
| 125 |
+
],
|
| 126 |
+
allow_flagging="never"
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
# Launch the app with additional parameters
|
| 130 |
+
if __name__ == "__main__":
|
| 131 |
+
demo.launch(share=True, debug=True)
|