|
| 1 | +"""Export LlamaParse results to Markdown, Text, and schema-driven JSON.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from llama_cloud import LlamaCloud |
| 8 | +from pydantic import BaseModel, Field |
| 9 | + |
| 10 | +PDF_PATH = Path("sample_report.pdf") |
| 11 | + |
| 12 | + |
| 13 | +class RevenueRow(BaseModel): |
| 14 | + period: str = Field( |
| 15 | + description="Fiscal period label, e.g. FY 2025 or September 27, 2025", |
| 16 | + ) |
| 17 | + revenue_millions: float = Field( |
| 18 | + description="Revenue in millions of USD", |
| 19 | + ) |
| 20 | + growth_percent: float | None = Field( |
| 21 | + default=None, |
| 22 | + description="Year-over-year growth percentage if stated", |
| 23 | + ) |
| 24 | + |
| 25 | + |
| 26 | +class RevenueTable(BaseModel): |
| 27 | + rows: list[RevenueRow] = Field( |
| 28 | + description="One row per fiscal period in the table" |
| 29 | + ) |
| 30 | + |
| 31 | + |
| 32 | +def main() -> None: |
| 33 | + client = LlamaCloud(api_key=os.environ["LLAMA_CLOUD_API_KEY"]) |
| 34 | + |
| 35 | + uploaded = client.files.create(file=PDF_PATH, purpose="parse") |
| 36 | + |
| 37 | + parsed = client.parsing.parse( |
| 38 | + file_id=uploaded.id, |
| 39 | + tier="agentic", |
| 40 | + version="latest", |
| 41 | + expand=["markdown", "text"], |
| 42 | + ) |
| 43 | + |
| 44 | + markdown_pages = "\n\n".join( |
| 45 | + page.markdown for page in parsed.markdown.pages |
| 46 | + ) |
| 47 | + Path("output_llamaparse.md").write_text(markdown_pages, encoding="utf-8") |
| 48 | + |
| 49 | + if parsed.text and parsed.text.pages: |
| 50 | + text_pages = "\n".join(page.text for page in parsed.text.pages) |
| 51 | + Path("output_llamaparse.text").write_text(text_pages, encoding="utf-8") |
| 52 | + |
| 53 | + extract_file = client.files.create(file=PDF_PATH, purpose="extract") |
| 54 | + job = client.extract.run( |
| 55 | + file_input=extract_file.id, |
| 56 | + configuration={ |
| 57 | + "data_schema": RevenueTable.model_json_schema(), |
| 58 | + "extraction_target": "per_doc", |
| 59 | + "tier": "agentic", |
| 60 | + }, |
| 61 | + ) |
| 62 | + |
| 63 | + Path("output_llamaparse.json").write_text( |
| 64 | + json.dumps(job.extract_result, indent=2), |
| 65 | + encoding="utf-8", |
| 66 | + ) |
| 67 | + print(json.dumps(job.extract_result, indent=2)) |
| 68 | + |
| 69 | + |
| 70 | +if __name__ == "__main__": |
| 71 | + main() |
0 commit comments