gelpredict / app /citation_parser.py
awolter's picture
Upload folder using huggingface_hub
266eda8 verified
Raw History Blame Contribute Delete
5.65 kB
"""
Citation Parser for Literature Data Entry
- Auto-extract fields from pasted citations
- Generate source labels
- Support for multiple citation formats (APA, MLA, Chicago, Vancouver)
"""
import re
from typing import Dict, Optional
def parse_citation(citation: str) -> Dict[str, Optional[str]]:
"""
Auto-extract fields from pasted citation.
Handles common formats:
- "Smith J, Jones K. (2023). Title of paper. Journal Name. DOI: 10.1234/journal.2023.001"
- "Smith et al. Title of paper. Journal. 2023. https://doi.org/10.1234/..."
- APA, MLA, Chicago, Vancouver styles
Returns:
dict with keys: first_author, publication_year, paper_title, doi, journal, source_label
"""
result = {
"first_author": None,
"publication_year": None,
"paper_title": None,
"doi": None,
"journal": None,
"source_label": None
}
if not citation or not citation.strip():
return result
# Clean citation
citation = citation.strip()
# Extract DOI (multiple patterns)
doi_patterns = [
r'(?:doi:|DOI:)\s*(10\.\d{4,}/[^\s]+)', # doi: 10.1234/...
r'https?://doi\.org/(10\.\d{4,}/[^\s]+)', # https://doi.org/10.1234/...
r'(10\.\d{4,}/[^\s,]+)', # bare DOI
]
for pattern in doi_patterns:
match = re.search(pattern, citation, re.IGNORECASE)
if match:
result["doi"] = match.group(1).rstrip('.,;)')
break
# Extract year (4-digit number, typically in parens or after comma)
year_patterns = [
r'\((\d{4})\)', # (2023)
r'\s(\d{4})[.,;\s]', # 2023. or 2023,
r'\s(\d{4})$', # 2023 at end
]
for pattern in year_patterns:
match = re.search(pattern, citation)
if match:
year = int(match.group(1))
if 1950 <= year <= 2035:
result["publication_year"] = year
break
# Extract first author (before first comma or "et al")
# Handles: "Smith J," "Smith," "Smith et al."
author_patterns = [
r'^([A-Z][a-zA-Z\'\-]+)(?:\s+[A-Z]\.?)?[\s,]', # Smith J, or Smith,
r'^([A-Z][a-zA-Z\'\-]+)\s+et\s+al', # Smith et al
r'^([A-Z][a-zA-Z\'\-]+)', # Just "Smith"
]
for pattern in author_patterns:
match = re.match(pattern, citation)
if match:
result["first_author"] = match.group(1)
break
# Try to extract title (between year and journal, or in quotes)
# Pattern: After year/author, before journal/DOI
title_patterns = [
r'\.\s*([A-Z][^\.]+)\.\s+[A-Z][a-z]+', # Title between periods
r'[""]([^""]+)[""]', # In quotes
r'\(\d{4}\)\.\s*([^\.]+)\.', # After (year).
r',\s*([A-Z][^,\.]+)[,\.]', # After comma (some formats)
]
for pattern in title_patterns:
match = re.search(pattern, citation)
if match:
title = match.group(1).strip()
# Reasonable title length and doesn't look like a journal name
if 10 < len(title) < 300 and not re.match(r'^[A-Z][a-z]+$', title):
result["paper_title"] = title
break
# Try to extract journal (often italicized or after title)
# Look for pattern: Title. JournalName. or Title. JournalName, Year
journal_patterns = [
r'\.\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,4})[,\.]?\s+\d{4}', # Before year
r'\.\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+){0,4})\.', # Between periods
]
for pattern in journal_patterns:
match = re.search(pattern, citation)
if match:
journal = match.group(1).strip()
# Make sure it's not the title (titles are usually longer)
if len(journal) < 50:
result["journal"] = journal
break
# Auto-generate source_label: "Smith2023" or "Smith_2023_Biomaterials"
if result["first_author"] and result["publication_year"]:
source_label = f"{result['first_author']}{result['publication_year']}"
if result["journal"]:
# Add journal abbreviation (first word, max 10 chars)
journal_abbr = result["journal"].split()[0][:10]
source_label = f"{result['first_author']}_{result['publication_year']}_{journal_abbr}"
result["source_label"] = source_label
return result
# Example usage and test cases
if __name__ == "__main__":
test_citations = [
# APA format
"Smith, J., & Jones, K. (2023). Decellularized mammary ECM promotes organoid formation. Biomaterials, 45(3), 123-134. doi: 10.1016/j.biomaterials.2023.001",
# Nature format
"Smith, J. et al. Decellularized mammary ECM promotes organoid formation. Nature 612, 123-130 (2023). https://doi.org/10.1038/s41586-023-12345-6",
# Short format
"Smith et al. (2023). Decellularized ECM for organoids. Biomaterials. 10.1016/j.biomaterials.2023.001",
# Vancouver
"Smith J, Jones K, Brown M. Decellularized mammary ECM. Biomaterials. 2023;45:123-134.",
# With URL
"Smith J. Decellularized mammary ECM. Biomaterials, 2023. https://doi.org/10.1016/j.biomaterials.2023.001",
]
print("Testing Citation Parser:\n")
for i, citation in enumerate(test_citations, 1):
print(f"Test {i}:")
print(f"Input: {citation[:80]}...")
result = parse_citation(citation)
print(f"Parsed:")
for key, value in result.items():
if value:
print(f" {key}: {value}")
print()