Spaces:
Sleeping
Sleeping
Download app.py from schmidj/Metafinder_AI: direct link, hf CLI and curl.
- Browser
- Download file 8.6 kB
-
https://huggingface.co/spaces/schmidj/Metafinder_AI/resolve/main/app.py
- Command line
-
hf download hf://spaces/schmidj/Metafinder_AI/app.py
-
curl -L -o app.py https://huggingface.co/spaces/schmidj/Metafinder_AI/resolve/main/app.py
8.6 kB
| 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 --- | |
| def index(): | |
| return render_template("index.html", metadata=None) | |
| 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) | |