Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,16 +1,18 @@
|
|
| 1 |
-
import
|
|
|
|
| 2 |
import spacy
|
| 3 |
-
import camelot
|
| 4 |
import fitz # PyMuPDF
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
import google.generativeai as genai
|
| 6 |
-
import os
|
| 7 |
-
import re # For regular expressions
|
| 8 |
from dotenv import load_dotenv
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
# Load environment variables
|
| 11 |
load_dotenv()
|
| 12 |
-
|
| 13 |
-
# Set the API key for Gemini
|
| 14 |
genai.configure(api_key=os.getenv('AIzaSyCYy1NLIOei1b6ZAG4Wtab4-md8MOW0yAk'))
|
| 15 |
|
| 16 |
# Load SpaCy model
|
|
@@ -19,19 +21,18 @@ nlp = spacy.load("en_core_web_sm")
|
|
| 19 |
class ResearchPaperAnalyzer:
|
| 20 |
def __init__(self, model_name: str):
|
| 21 |
self.model = genai.GenerativeModel(model_name=model_name)
|
|
|
|
| 22 |
self.tables_data = {}
|
| 23 |
self.extracted_text = ""
|
| 24 |
|
| 25 |
def extract_text(self, pdf_path):
|
| 26 |
-
|
| 27 |
-
doc = fitz.open(pdf_path)
|
| 28 |
text = ""
|
| 29 |
-
for page in
|
| 30 |
-
text +=
|
| 31 |
return text
|
| 32 |
|
| 33 |
def segment_text(self, text):
|
| 34 |
-
# Segment the text into sections based on headings
|
| 35 |
heading_pattern = r"^\d+\.\s.+"
|
| 36 |
paragraphs = text.split("\n\n")
|
| 37 |
sections = []
|
|
@@ -77,90 +78,48 @@ class ResearchPaperAnalyzer:
|
|
| 77 |
return structured_text, analyzed_data
|
| 78 |
|
| 79 |
def extract_tables(self, pdf_path):
|
| 80 |
-
# Extract tables using Camelot
|
| 81 |
tables = camelot.read_pdf(pdf_path, pages='all')
|
| 82 |
return tables
|
| 83 |
|
| 84 |
def process_paper(self, pdf_path):
|
| 85 |
-
# Step 1: Extract and process text
|
| 86 |
self.extracted_text = self.extract_text(pdf_path)
|
| 87 |
structured_text, _ = self.process_text(self.extracted_text)
|
| 88 |
|
| 89 |
-
# Step 2: Extract and process tables
|
| 90 |
tables = self.extract_tables(pdf_path)
|
| 91 |
for i, table in enumerate(tables):
|
| 92 |
csv_data = table.df.to_csv(index=False)
|
| 93 |
self.tables_data[f"table_{i + 1}"] = csv_data
|
| 94 |
|
| 95 |
-
return structured_text, self.tables_data
|
| 96 |
-
|
| 97 |
def handle_query(self, query):
|
| 98 |
-
|
| 99 |
-
combined_info = f"{self.extracted_text}\n\nTables Data:\n{self.tables_data}"
|
| 100 |
|
| 101 |
-
|
| 102 |
-
prompt = f"Given the following information, answer the query:\n\n{combined_info}\n\nQuery: {query}"
|
| 103 |
|
| 104 |
-
# Debugging: Display the prompt
|
| 105 |
-
st.write(f"Prompt sent to Gemini: {prompt}")
|
| 106 |
-
|
| 107 |
try:
|
| 108 |
response = self.model.generate_content(prompt)
|
| 109 |
-
|
| 110 |
-
st.write(f"Full response from Gemini: {response.text}") # Debugging
|
| 111 |
-
return response.text # Return Gemini's generated answer
|
| 112 |
except Exception as e:
|
| 113 |
-
|
| 114 |
-
return None
|
| 115 |
|
| 116 |
-
# Streamlit
|
| 117 |
-
st.title("Research Paper Analyzer
|
|
|
|
| 118 |
|
| 119 |
-
# Upload PDF
|
| 120 |
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 121 |
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
st.session_state.messages = []
|
| 128 |
-
|
| 129 |
-
def add_message(message, is_user=True):
|
| 130 |
-
st.session_state.messages.append({"message": message, "is_user": is_user})
|
| 131 |
-
|
| 132 |
-
def display_messages():
|
| 133 |
-
for msg in st.session_state.messages:
|
| 134 |
-
if msg['is_user']:
|
| 135 |
-
st.markdown(f"**You:** {msg['message']}")
|
| 136 |
-
else:
|
| 137 |
-
st.markdown(f"**Bot:** {msg['message']}")
|
| 138 |
-
|
| 139 |
-
# Display existing messages
|
| 140 |
-
display_messages()
|
| 141 |
-
|
| 142 |
-
# Button to process the file
|
| 143 |
-
if st.button("Process Text and Tables"):
|
| 144 |
-
with open("uploaded_pdf.pdf", "wb") as f:
|
| 145 |
f.write(uploaded_file.getbuffer())
|
| 146 |
-
|
| 147 |
-
# Process the uploaded PDF
|
| 148 |
-
structured_text, tables_data = analyzer.process_paper("uploaded_pdf.pdf")
|
| 149 |
-
|
| 150 |
-
# Chatbot functionality: Ask a question
|
| 151 |
-
st.header("Ask a Question")
|
| 152 |
-
user_query = st.text_input("Enter your query:")
|
| 153 |
-
|
| 154 |
-
# Button to generate answer using Gemini
|
| 155 |
-
if st.button("Answer"):
|
| 156 |
-
# Add user message to chat
|
| 157 |
-
add_message(user_input.strip(), is_user=True)
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
add_message(bot_response, is_user=False)
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import re
|
| 3 |
import spacy
|
|
|
|
| 4 |
import fitz # PyMuPDF
|
| 5 |
+
import camelot
|
| 6 |
+
from pdf2image import convert_from_path
|
| 7 |
+
from pytesseract import image_to_string
|
| 8 |
+
from PIL import Image
|
| 9 |
import google.generativeai as genai
|
|
|
|
|
|
|
| 10 |
from dotenv import load_dotenv
|
| 11 |
+
import io
|
| 12 |
+
import streamlit as st
|
| 13 |
|
| 14 |
+
# Load environment variables
|
| 15 |
load_dotenv()
|
|
|
|
|
|
|
| 16 |
genai.configure(api_key=os.getenv('AIzaSyCYy1NLIOei1b6ZAG4Wtab4-md8MOW0yAk'))
|
| 17 |
|
| 18 |
# Load SpaCy model
|
|
|
|
| 21 |
class ResearchPaperAnalyzer:
|
| 22 |
def __init__(self, model_name: str):
|
| 23 |
self.model = genai.GenerativeModel(model_name=model_name)
|
| 24 |
+
self.image_descriptions = {}
|
| 25 |
self.tables_data = {}
|
| 26 |
self.extracted_text = ""
|
| 27 |
|
| 28 |
def extract_text(self, pdf_path):
|
| 29 |
+
pages = convert_from_path(pdf_path)
|
|
|
|
| 30 |
text = ""
|
| 31 |
+
for page in pages:
|
| 32 |
+
text += image_to_string(page)
|
| 33 |
return text
|
| 34 |
|
| 35 |
def segment_text(self, text):
|
|
|
|
| 36 |
heading_pattern = r"^\d+\.\s.+"
|
| 37 |
paragraphs = text.split("\n\n")
|
| 38 |
sections = []
|
|
|
|
| 78 |
return structured_text, analyzed_data
|
| 79 |
|
| 80 |
def extract_tables(self, pdf_path):
|
|
|
|
| 81 |
tables = camelot.read_pdf(pdf_path, pages='all')
|
| 82 |
return tables
|
| 83 |
|
| 84 |
def process_paper(self, pdf_path):
|
|
|
|
| 85 |
self.extracted_text = self.extract_text(pdf_path)
|
| 86 |
structured_text, _ = self.process_text(self.extracted_text)
|
| 87 |
|
|
|
|
| 88 |
tables = self.extract_tables(pdf_path)
|
| 89 |
for i, table in enumerate(tables):
|
| 90 |
csv_data = table.df.to_csv(index=False)
|
| 91 |
self.tables_data[f"table_{i + 1}"] = csv_data
|
| 92 |
|
|
|
|
|
|
|
| 93 |
def handle_query(self, query):
|
| 94 |
+
combined_info = f"{self.extracted_text}\n\nImage Descriptions:\n{self.image_descriptions}\n\nTables Data:\n{self.tables_data}"
|
|
|
|
| 95 |
|
| 96 |
+
prompt = f"Based on the following information, answer the query:\n\n{combined_info}\n\nQuery: {query}"
|
|
|
|
| 97 |
|
|
|
|
|
|
|
|
|
|
| 98 |
try:
|
| 99 |
response = self.model.generate_content(prompt)
|
| 100 |
+
return response.text
|
|
|
|
|
|
|
| 101 |
except Exception as e:
|
| 102 |
+
return f"An error occurred: {str(e)}"
|
|
|
|
| 103 |
|
| 104 |
+
# Streamlit UI setup
|
| 105 |
+
st.title("Research Paper Analyzer")
|
| 106 |
+
st.write("Upload a PDF document to analyze and ask questions about it.")
|
| 107 |
|
|
|
|
| 108 |
uploaded_file = st.file_uploader("Choose a PDF file", type="pdf")
|
| 109 |
|
| 110 |
+
if uploaded_file is not None:
|
| 111 |
+
analyzer = ResearchPaperAnalyzer("gemini-1.5-pro-latest")
|
| 112 |
+
|
| 113 |
+
# Process the uploaded PDF file
|
| 114 |
+
with open("temp.pdf", "wb") as f:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
f.write(uploaded_file.getbuffer())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
+
analyzer.process_paper("temp.pdf")
|
| 118 |
+
|
| 119 |
+
# User query input
|
| 120 |
+
user_query = st.text_input("Ask a question about the document:")
|
|
|
|
| 121 |
|
| 122 |
+
if st.button("Submit"):
|
| 123 |
+
if user_query:
|
| 124 |
+
response = analyzer.handle_query(user_query)
|
| 125 |
+
st.write("Response:", response)
|