File size: 4,942 Bytes
0ebf67e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

"""
Parse Arctander "Perfume and Flavor Chemicals" monographs from extracted text.

Arctander entries have a regular structure:
    <number>:
    <NAME> [<synonyms>]
    <empirical formula>
    <description of appearance, odor, taste, uses, production>

We extract:
    - name, synonyms, cas (if known from cross-reference)
    - empirical_formula, molecular_weight
    - odor_description, taste_description
    - physical_notes (B.P., Sp.Gr., color, solubility)
    - usage_notes (perfumery/flavor uses)
    - source_page
"""

import json
import logging
import re
from pathlib import Path
from typing import Any

logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger("parse_arctander")


def _extract_number_and_name(block: str) -> tuple[int, str, str]:
    """Parse the leading '123:' monograph number and name."""
    m = re.match(r"(\d+):\s*\n?\s*([^\n]+(?:\n[^\n]+){0,5})", block, re.DOTALL)
    if not m:
        return 0, "", ""
    raw = m.group(2).strip()
    # Name is the first ALL-CAPS or Title-Case line; synonyms follow after a period.
    lines = [l.strip() for l in raw.splitlines() if l.strip()]
    name = lines[0] if lines else ""
    synonyms = " ".join(lines[1:]) if len(lines) > 1 else ""
    return int(m.group(1)), name, synonyms


def _extract_formula_and_weight(block: str) -> tuple[str | None, float | None]:
    """Find empirical formula and molecular weight from the block."""
    # Look for patterns like C10H12O2 = 164.20
    m = re.search(r"([C][^\s=]{0,40}[H][^\s=]{0,40})\s*=\s*([\d\.]+)", block)
    if m:
        formula = m.group(1).strip()
        try:
            weight = float(m.group(2))
        except ValueError:
            weight = None
        return formula, weight
    # Fallback: molecular weight line like "M.W. 164.20"
    m = re.search(r"M\.?W\.?\s*=?\s*([\d\.]+)", block, re.IGNORECASE)
    if m:
        return None, float(m.group(1))
    return None, None


def _extract_bullet_notes(block: str) -> dict[str, str]:
    """Pull out physical properties and odor/taste notes from the description."""
    notes: dict[str, str] = {}
    for label, key in [
        ("B\.P\.", "boiling_point"),
        ("Sp\.Gr\.", "specific_gravity"),
        ("color", "color"),
        ("odor", "odor"),
        ("taste", "taste"),
    ]:
        m = re.search(rf"{label}\s*[^\.\n]{{0,10}}[\.\:]\s*([^\.\n]{{5,200}})", block, re.IGNORECASE)
        if m:
            notes[key] = m.group(1).strip()
    return notes


def parse_arctander_pages(records: list[dict[str, Any]]) -> list[dict[str, Any]]:
    """Parse a list of page records into monograph entries."""
    monographs: list[dict[str, Any]] = []
    for record in records:
        text = record.get("text", "")
        source = record.get("source", "")
        page = record.get("page", 0)
        # Split by monograph numbers followed by a colon and newline
        blocks = re.split(r"(?=\n\s*\d+:\s*\n)", "\n" + text)
        for block in blocks:
            block = block.strip()
            if not block:
                continue
            number, name, synonyms = _extract_number_and_name(block)
            if not name or number == 0:
                continue
            formula, mw = _extract_formula_and_weight(block)
            notes = _extract_bullet_notes(block)
            monographs.append({
                "monograph_number": number,
                "name": name,
                "synonyms": synonyms,
                "empirical_formula": formula,
                "molecular_weight": mw,
                "odor_description": notes.get("odor", ""),
                "taste_description": notes.get("taste", ""),
                "physical_notes": notes,
                "raw_text": block[:3000],
                "source": source,
                "page": page,
            })
    return monographs


def main() -> int:
    parser = argparse.ArgumentParser(description="Parse Arctander monographs from extracted text")
    parser.add_argument("--input", required=True, help="Input JSONL from extract_pdf_text.py")
    parser.add_argument("--output", required=True, help="Output JSONL of parsed monographs")
    args = parser.parse_args()

    input_path = Path(args.input)
    output_path = Path(args.output)
    output_path.parent.mkdir(parents=True, exist_ok=True)

    records = [json.loads(line) for line in input_path.read_text(encoding="utf-8").strip().splitlines()]
    arctander_records = [r for r in records if "Arctander" in r.get("source", "")]
    monographs = parse_arctander_pages(arctander_records)

    with output_path.open("w", encoding="utf-8") as out:
        for mono in monographs:
            out.write(json.dumps(mono, ensure_ascii=False) + "\n")

    logger.info("Parsed %d monographs from Arctander", len(monographs))
    return 0


if __name__ == "__main__":
    import argparse
    raise SystemExit(main())