Spaces:
Sleeping
Sleeping
File size: 8,604 Bytes
d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 d8bd965 14c2543 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 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 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | from flask import Flask, render_template, request, redirect, url_for, flash
import os
import fitz
import requests
import json
import logging
from dotenv import load_dotenv
from retrieval_engine import HybridRetriever
# --- Setup ---
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
app = Flask(__name__)
app.secret_key = "dev-secret-key"
load_dotenv()
TOGETHER_API_KEY = os.getenv("TOGETHER_API_KEY")
TOGETHER_API_URL = "https://api.together.xyz/v1/chat/completions"
LLM_MODEL = "meta-llama/Llama-3.3-70B-Instruct-Turbo-Free"
# --- Load prompt template ---
def load_prompt_template():
"""Load the metadata extraction prompt template from file."""
prompt_path = os.path.join(os.path.dirname(__file__), "prompts", "metadata_extraction.txt")
try:
with open(prompt_path, "r", encoding="utf-8") as f:
return f.read()
except FileNotFoundError:
logger.error(f"Prompt template not found at {prompt_path}")
raise
except Exception as e:
logger.error(f"Error loading prompt template: {e}")
raise
# --- PDF text extraction ---
def extract_text_from_pdf(pdf_path):
doc = fitz.open(pdf_path)
text = []
for page_num, page in enumerate(doc, 1):
text.append(page.get_text())
return '\n'.join(text)
# --- Fetch PDF from DOI ---
def download_pdf_from_doi(doi):
"""
Try to locate and download a PDF from a given DOI using open access APIs.
Returns path to downloaded PDF or None if not found.
"""
try:
# Normalize DOI
doi = doi.strip().lower().replace("https://doi.org/", "").replace("http://doi.org/", "")
logger.info(f"Looking up DOI: {doi}")
# Step 1: Try Unpaywall API for an open-access PDF
unpaywall_url = f"https://api.unpaywall.org/v2/{doi}?email=demo@openai.com"
r = requests.get(unpaywall_url, timeout=15)
if r.status_code == 200:
data = r.json()
pdf_url = None
# First try best_oa_location
if data.get("best_oa_location"):
pdf_url = data["best_oa_location"].get("url_for_pdf")
# Then try other oa_locations
if not pdf_url and data.get("oa_locations"):
for loc in data["oa_locations"]:
if loc.get("url_for_pdf"):
pdf_url = loc["url_for_pdf"]
break
# If we found a PDF link, download it
if pdf_url:
logger.info(f"Found PDF via Unpaywall: {pdf_url}")
pdf_data = requests.get(pdf_url, timeout=20)
if pdf_data.status_code == 200 and pdf_data.headers.get("Content-Type", "").startswith("application/pdf"):
os.makedirs("downloads", exist_ok=True)
pdf_path = os.path.join("downloads", f"{doi.replace('/', '_')}.pdf")
with open(pdf_path, "wb") as f:
f.write(pdf_data.content)
return pdf_path
# If no PDF found, fallback to landing page URL
landing_url = None
if data.get("best_oa_location"):
landing_url = data["best_oa_location"].get("url_for_landing_page")
if not landing_url and data.get("oa_locations"):
for loc in data["oa_locations"]:
if loc.get("url_for_landing_page"):
landing_url = loc["url_for_landing_page"]
break
if landing_url:
logger.warning(f"No PDF found for DOI {doi}, but landing page exists: {landing_url}")
flash(f'The paper is open-access but no direct PDF link was found. Please download it manually: <a href="{landing_url}" target="_blank">{landing_url}</a>', 'warning')
return None
# Step 2: Fallback – try direct DOI link
doi_url = f"https://doi.org/{doi}"
head = requests.head(doi_url, allow_redirects=True, timeout=15)
pdf_link = head.url if head.url.endswith(".pdf") else None
if pdf_link:
logger.info(f"Found direct PDF: {pdf_link}")
pdf_data = requests.get(pdf_link, timeout=20)
if pdf_data.status_code == 200:
os.makedirs("downloads", exist_ok=True)
pdf_path = os.path.join("downloads", f"{doi.replace('/', '_')}.pdf")
with open(pdf_path, "wb") as f:
f.write(pdf_data.content)
return pdf_path
logger.warning(f"No PDF found for DOI: {doi}")
return None
except Exception as e:
logger.error(f"Error fetching PDF for DOI {doi}: {e}")
return None
def prompt_llm(prompt):
"""
Prompt the LLM with the given prompt and return the response.
"""
headers = {
"Authorization": f"Bearer {TOGETHER_API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": LLM_MODEL,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 2000,
"temperature": 0.0
}
try:
response = requests.post(TOGETHER_API_URL, headers=headers, json=data)
response.raise_for_status()
content = response.json()["choices"][0]["message"]["content"].strip()
if content.startswith("```"):
content = content.split("```")[1].replace("json", "", 1).strip()
return json.loads(content)
except Exception as e:
logger.error(f"Error prompting LLM: {e}")
return None
# --- Metadata extraction ---
def extract_metadata_from_pdf(pdf_text, retriever, custom_keys=""):
chunks = [pdf_text[i:i+2000] for i in range(0, len(pdf_text), 2000)]
retriever.fit(chunks)
query = "Extract metadata from this research paper including title, authors, abstract, methods, datasets, and findings."
retrieved_docs = retriever.retrieve(query, top_k=5)
context = "\n\n".join(retrieved_docs)
# with open(os.path.join("tmp", "last_context.txt"), "w", encoding="utf-8") as f:
# write(context)
# Define data-level metadata fields
default_data_fields = [
"Study methods", "Datasets used", "Geographic coverage", "Temporal coverage", "Sample size"
]
# Use custom keys if provided, otherwise use default data fields
if custom_keys:
data_fields = [field.strip() for field in custom_keys.split(",") if field.strip()]
else:
data_fields = default_data_fields
# Load prompt template and format with dynamic fields
prompt_template = load_prompt_template()
data_fields_list = "\n".join(f"- {field.lower().replace(' ', '_').replace('_and_', '_')}" for field in data_fields)
prompt = prompt_template.format(data_fields=data_fields_list, context=context)
# Prompt the LLM with the formatted prompt
response = prompt_llm(prompt)
return response
# --- Flask routes ---
@app.route("/", methods=["GET"])
def index():
return render_template("index.html", metadata=None)
@app.route("/process", methods=["POST"])
def process():
uploaded_file = request.files.get("pdf_file")
doi = request.form.get("doi", "").strip()
custom_keys = request.form.get("custom_keys", "").strip()
has_pdf = uploaded_file and uploaded_file.filename != ""
has_doi = bool(doi)
if has_pdf and has_doi:
flash("Please provide either a PDF file OR a DOI, not both.")
return redirect(url_for("index"))
if not has_pdf and not has_doi:
flash("Please upload a PDF or enter a DOI.")
return redirect(url_for("index"))
# --- PDF upload path ---
if has_pdf:
uploads_dir = os.path.join(os.getcwd(), "uploads")
os.makedirs(uploads_dir, exist_ok=True)
pdf_path = os.path.join(uploads_dir, uploaded_file.filename)
uploaded_file.save(pdf_path)
else:
# --- DOI handling path ---
pdf_path = download_pdf_from_doi(doi)
if not pdf_path:
# The download_pdf_from_doi function already shows appropriate flash messages
return redirect(url_for("index"))
# --- Process the PDF ---
logger.info(f"Processing PDF at {pdf_path}")
pdf_text = extract_text_from_pdf(pdf_path)
if not pdf_text:
flash("Failed to extract text from PDF.")
return redirect(url_for("index"))
retriever = HybridRetriever()
metadata = extract_metadata_from_pdf(pdf_text, retriever, custom_keys)
return render_template("index.html", metadata=metadata)
if __name__ == "__main__":
app.run(debug=True)
|