mirror of
https://github.com/run-llama/llama_cloud_services.git
synced 2026-07-20 00:54:09 -04:00
Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fe9668dbd3 | |||
| 478142e509 | |||
| e76d5ba679 | |||
| 23dc9c0f68 | |||
| 8b96176d8a | |||
| 1bbf5f4823 | |||
| 2f57682035 | |||
| 4c05160f98 | |||
| 3e9ad64a7f | |||
| 21fa19c73b | |||
| 58257d546b | |||
| 5e99d810fd | |||
| a2dc717d85 | |||
| 87062e6ca8 | |||
| ae3a21c5ff | |||
| ccebb8a2fa | |||
| 2d21d6e688 |
@@ -72,7 +72,7 @@ repos:
|
||||
args:
|
||||
[
|
||||
"--ignore-words-list",
|
||||
"astroid,gallary,momento,narl,ot,rouge,nin,gere,te,inh",
|
||||
"astroid,gallary,momento,narl,ot,rouge,nin,gere,te,inh,vor",
|
||||
]
|
||||
- repo: https://github.com/srstevenson/nb-clean
|
||||
rev: 3.1.0
|
||||
|
||||
@@ -6,6 +6,8 @@ LlamaParse directly integrates with [LlamaIndex](https://github.com/run-llama/ll
|
||||
|
||||
Free plan is up to 1000 pages a day. Paid plan is free 7k pages per week + 0.3c per additional page.
|
||||
|
||||
Read below for some quickstart information, or see the [full documentation](https://docs.cloud.llamaindex.ai/).
|
||||
|
||||
## Getting Started
|
||||
|
||||
First, login and get an api-key from [**https://cloud.llamaindex.ai ↗**](https://cloud.llamaindex.ai).
|
||||
@@ -53,6 +55,34 @@ documents = await parser.aload_data("./my_file.pdf")
|
||||
documents = await parser.aload_data(["./my_file1.pdf", "./my_file2.pdf"])
|
||||
```
|
||||
|
||||
## Using with file object
|
||||
|
||||
You can parse a file object directly:
|
||||
|
||||
```python
|
||||
import nest_asyncio
|
||||
|
||||
nest_asyncio.apply()
|
||||
|
||||
from llama_parse import LlamaParse
|
||||
|
||||
parser = LlamaParse(
|
||||
api_key="llx-...", # can also be set in your env as LLAMA_CLOUD_API_KEY
|
||||
result_type="markdown", # "markdown" and "text" are available
|
||||
num_workers=4, # if multiple files passed, split in `num_workers` API calls
|
||||
verbose=True,
|
||||
language="en", # Optionally you can define a language, default=en
|
||||
)
|
||||
|
||||
with open("./my_file1.pdf", "rb") as f:
|
||||
documents = parser.load_data(f)
|
||||
|
||||
# you can also pass file bytes directly
|
||||
with open("./my_file1.pdf", "rb") as f:
|
||||
file_bytes = f.read()
|
||||
documents = parser.load_data(file_bytes)
|
||||
```
|
||||
|
||||
## Using with `SimpleDirectoryReader`
|
||||
|
||||
You can also integrate the parser as the default PDF loader in `SimpleDirectoryReader`:
|
||||
@@ -87,6 +117,10 @@ Several end-to-end indexing examples can be found in the examples folder
|
||||
- [Advanced RAG Example](examples/demo_advanced.ipynb)
|
||||
- [Raw API Usage](examples/demo_api.ipynb)
|
||||
|
||||
## Documentation
|
||||
|
||||
[https://docs.cloud.llamaindex.ai/](https://docs.cloud.llamaindex.ai/)
|
||||
|
||||
## Terms of Service
|
||||
|
||||
See the [Terms of Service Here](./TOS.pdf).
|
||||
|
||||
Binary file not shown.
+427
-186
File diff suppressed because one or more lines are too long
+2738
-2886
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,493 @@
|
||||
{
|
||||
"cells": [
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "0db58db5-d4ee-4631-af5b-4fc53eb05170",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"# RAG with Excel Spreadsheet using LlamaPrase\n",
|
||||
"\n",
|
||||
"<a href=\"https://colab.research.google.com/github/run-llama/llama_parse/blob/main/examples/demo_excel.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>\n",
|
||||
"\n",
|
||||
"This notebook constructs a RAG pipeline over a simple DCF template [here](https://eqvista.com/app/uploads/2020/09/Eqvista_DCF-Excel-Template.xlsx).\n",
|
||||
"\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "5f7d99ad-6ebd-47d0-92a7-566630b0c22a",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Setup\n",
|
||||
"\n",
|
||||
"We first setup and load the data. If you haven't already, [download the template](https://eqvista.com/app/uploads/2020/09/Eqvista_DCF-Excel-Template.xlsx) and name it `dcf_template.xlxs` locally."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "d867d1a6-cfcf-4f53-952a-f4a6ff2fa205",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"%pip install llama-index\n",
|
||||
"%pip install llama-parse"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "103c7983-56d3-45be-b763-d1828d07c43e",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"import nest_asyncio\n",
|
||||
"\n",
|
||||
"nest_asyncio.apply()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7b694b56-e04b-4d87-aa37-f0725d6b3adb",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_parse import LlamaParse\n",
|
||||
"\n",
|
||||
"# api_key = \"llx-\" # get from cloud.llamaindex.ai"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "9c4693c7-c1c8-47b4-8a8c-25d7e9ef9d2c",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id cac11eca-d5da-4d46-90e6-321f40e11611\n",
|
||||
"Started parsing the file under job_id cac11eca-5450-4847-9da0-fa6879c4cf3a\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"parser = LlamaParse(\n",
|
||||
" # api_key=api_key, # can also be set in your env as LLAMA_CLOUD_API_KEY\n",
|
||||
" result_type=\"markdown\",\n",
|
||||
")\n",
|
||||
"docs = parser.load_data(\"./dcf_template.xlsx\")\n",
|
||||
"# docs_txt = LlamaParse(result_type=\"text\").load_data(\"./dcf_template.xlsx\")"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7302f1c8-e405-4cda-8ff7-1d55185816f7",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"# Cover Page\n",
|
||||
"\n",
|
||||
"|Thank you for downloading our DCF Model excel template. This DCF Model excel template helps you to value your business using Discounted Free Cash Flow or DCF Method. | |\n",
|
||||
"|----------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n",
|
||||
"| | |\n",
|
||||
"| |Eqvista is an equity management software that allows companies, investors and company shareholders to track, manage, and make intelligent decisions about their companies’ equity.|\n",
|
||||
"| | |\n",
|
||||
"| |GET STARTED- IT'S FREE |\n",
|
||||
"| | |\n",
|
||||
"| |Note: This template is not professional advice and not a substitute for professional advice. |\n",
|
||||
"|Accordingly, before taking any actions based upon such information, we encourage you to consult with the appropriate professionals. | |\n",
|
||||
"| | |\n",
|
||||
"| |@Eqvista Inc. All Rights Reserved |\n",
|
||||
"---\n",
|
||||
"# DCF Model\n",
|
||||
"\n",
|
||||
"|Discounted Cash Flow Excel Template | | | | | | | | | | | |\n",
|
||||
"|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|------------------------------|-----------|-----------|-----------------------|-----------|-----------------------|--------------|-----------|-----------|-----------|--------------|\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Here is a simple discounted cash flow excel template for estimating your company value based on this income valuation approach | | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Instructions: | | | | | | | | | | | |\n",
|
||||
"|1) Fill out the two assumptions in yellow highlight | | | | | | | | | | | |\n",
|
||||
"|2) Fill in either the 5 year or 3 year weighted average figures in yellow highlight | | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Assumptions | | | | | | | | | | | |\n",
|
||||
"|Tax Rate |20% | | | | | | | | | | |\n",
|
||||
"|Discount Rate |15% | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|5 Year Weighted Moving Average | | | | | | | | | | | |\n",
|
||||
"|Indication of Company Value |$242,995.43 | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|3 Year Weighted Moving Average | | | | | | | | | | | |\n",
|
||||
"|Indication of Company Value |$158,651.07 | | | | | | | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"| |5 Year Weighted Moving Average| | | | | | | | | | |\n",
|
||||
"| |Past Years | | | | |Forecasted Future Years| | | | | |\n",
|
||||
"| |Year 1 |Year 2 |Year 3 |Year 4 |Year 5 |Year 6 |Year 7 |Year 8 |Year 9 |Year 10 |Terminal Value|\n",
|
||||
"|Pre-tax income |50,000.00 |55,000.00 |45,000.00 |52,000.00 |60,000.00 | | | | | | |\n",
|
||||
"|Income Taxes |10,000.00 |11,000.00 |9,000.00 |10,400.00 |12,000.00 | | | | | | |\n",
|
||||
"|Net Income |40,000.00 |44,000.00 |36,000.00 |41,600.00 |48,000.00 | | | | | | |\n",
|
||||
"|Depreciation Expense |5,000.00 |4,000.00 |3,000.00 |2,000.00 |1,000.00 | | | | | | |\n",
|
||||
"|Capital Expenditures |10,000.00 |8,000.00 |5,000.00 |5,000.00 |7,000.00 | | | | | | |\n",
|
||||
"|Debt Repayments |5,000.00 |5,000.00 |5,000.00 |5,000.00 |5,000.00 | | | | | | |\n",
|
||||
"|Net Cash Flow |20,000.00 |27,000.00 |23,000.00 |29,600.00 |35,000.00 |29,093.33 |29,817.78 |30,177.48 |30,469.23 |30,379.74 |287,188.00 |\n",
|
||||
"|Discounting Factor | | | | | |0.8696 |0.7561 |0.6575 |0.5718 |0.4972 |0.4972 |\n",
|
||||
"|Present Value of Future Cash Flow | | | | | |25,298.55 |22,546.52 |19,842.18 |17,420.88 |15,104.10 |142,783.19 |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"| |3 Year Weighted Moving Average| | | | | | | | | | |\n",
|
||||
"| |Past Years | | |Forecasted Future Years| | | | | | | |\n",
|
||||
"| |Year 1 |Year 2 |Year 3 |Year 4 |Year 5 |Year 6 |Terminal Value| | | | |\n",
|
||||
"|Pre-tax income |50,000.00 |55,000.00 |45,000.00 | | | | | | | | |\n",
|
||||
"|Income Taxes |10,000.00 |11,000.00 |9,000.00 | | | | | | | | |\n",
|
||||
"|Net Income |40,000.00 |44,000.00 |36,000.00 | | | | | | | | |\n",
|
||||
"|Depreciation Expense |5,000.00 |4,000.00 |3,000.00 | | | | | | | | |\n",
|
||||
"|Capital Expenditures |10,000.00 |8,000.00 |5,000.00 | | | | | | | | |\n",
|
||||
"|Debt Repayments |5,000.00 |5,000.00 |5,000.00 | | | | | | | | |\n",
|
||||
"|Net Cash Flow |20,000.00 |27,000.00 |23,000.00 |23,833.33 |24,083.33 |23,819.44 |158,253.59 | | | | |\n",
|
||||
"|Discounting Factor | | | |0.8696 |0.7561 |0.6575 |0.6575 | | | | |\n",
|
||||
"|Present Value of Future Cash Flow | | | |20,724.64 |18,210.46 |15,661.67 |104,054.30 | | | | |\n",
|
||||
"| | | | | | | | | | | | |\n",
|
||||
"|Notes: | | | | | | | | | | | |\n",
|
||||
"|-We based this simple discounted cash flow excel model based on the weighted moving averages (5 year or 3 year) for simplicity, in case a constant growth rate cannot be easily determined.| | | | | | | | | | | |\n",
|
||||
"|-The factors such as Depreciation Expense, Capital Expense and Debt Repayments remain constant, so consider this when looking at the forecasted figures. | | | | | | | | | | | |\n",
|
||||
"|-For the terminal value constant growth rate, we make the assumption of the growth from the last forecasted year compared to the first forecasted year. Adjust in the formula as needed. | | | | | | | | | | | |\n",
|
||||
"\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(docs[0].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1aedd4bb-7939-4fbc-8f07-d362e24d9772",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Configure LLM, Setup Basic Summary Engine\n",
|
||||
"\n",
|
||||
"We setup a basic summary engine which retrieves the entire document as context to put into the prompt."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "f7c056a8-d098-4ebe-9341-d9f07081067c",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.llms.openai import OpenAI\n",
|
||||
"from llama_index.core import Settings\n",
|
||||
"\n",
|
||||
"llm = OpenAI(model=\"gpt-4-turbo-preview\")\n",
|
||||
"Settings.llm = llm"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c0fa2630-ee1b-4ce7-91e9-f9ffff8347f9",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import SummaryIndex\n",
|
||||
"\n",
|
||||
"index = SummaryIndex.from_documents(docs)\n",
|
||||
"# index = SummaryIndex.from_documents(docs_txt)\n",
|
||||
"\n",
|
||||
"query_engine = index.as_query_engine()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "1d39a075-46b8-4dcb-8aee-abd10343bedd",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Define Baseline\n",
|
||||
"\n",
|
||||
"Let's define a baseline query engine over this data, using a naive parser (our PandasExcelReader, available on LlamaHub)."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "632f918e-7811-4931-8a5f-4aa4850718db",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Collecting openpyxl\n",
|
||||
" Downloading openpyxl-3.1.3-py2.py3-none-any.whl (251 kB)\n",
|
||||
"\u001b[2K \u001b[38;2;114;156;31m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m251.3/251.3 kB\u001b[0m \u001b[31m5.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m MB/s\u001b[0m eta \u001b[36m0:00:01\u001b[0m\n",
|
||||
"\u001b[?25hCollecting et-xmlfile\n",
|
||||
" Using cached et_xmlfile-1.1.0-py3-none-any.whl (4.7 kB)\n",
|
||||
"Installing collected packages: et-xmlfile, openpyxl\n",
|
||||
"Successfully installed et-xmlfile-1.1.0 openpyxl-3.1.3\n",
|
||||
"\n",
|
||||
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m A new release of pip available: \u001b[0m\u001b[31;49m22.2.2\u001b[0m\u001b[39;49m -> \u001b[0m\u001b[32;49m24.0\u001b[0m\n",
|
||||
"\u001b[1m[\u001b[0m\u001b[34;49mnotice\u001b[0m\u001b[1;39;49m]\u001b[0m\u001b[39;49m To update, run: \u001b[0m\u001b[32;49mpip install --upgrade pip\u001b[0m\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"!pip install llama-index-readers-file\n",
|
||||
"!pip install openpyxl"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "85ff09fd-8a99-4aa4-8182-8d0cf30f7b85",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.readers.file import PandasExcelReader\n",
|
||||
"import importlib\n",
|
||||
"from pathlib import Path\n",
|
||||
"\n",
|
||||
"base_reader = PandasExcelReader()\n",
|
||||
"base_docs = base_reader.load_data(Path(\"dcf_template.xlsx\"))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ba45f806-58be-4f57-bf42-2721555136cb",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Discounted Cash Flow Excel Template \n",
|
||||
" \n",
|
||||
"Here is a simple discounted cash flow excel template for estimating your company value based on this income valuation approach \n",
|
||||
" \n",
|
||||
"Instructions: \n",
|
||||
"1) Fill out the two assumptions in yellow highlight \n",
|
||||
"2) Fill in either the 5 year or 3 year weighted average figures in yellow highlight \n",
|
||||
" \n",
|
||||
" \n",
|
||||
" \n",
|
||||
" \n",
|
||||
"Assumptions \n",
|
||||
"Tax Rate 0.2 \n",
|
||||
"Discount Rate 0.15 \n",
|
||||
" \n",
|
||||
"5 Year Weighted Moving Average \n",
|
||||
"Indication of Company Value 242995.4347636059 \n",
|
||||
" \n",
|
||||
"3 Year Weighted Moving Average \n",
|
||||
"Indication of Company Value 158651.0723286644 \n",
|
||||
" \n",
|
||||
" 5 Year Weighted Moving Average \n",
|
||||
" Past Years Forecasted Future Years \n",
|
||||
" Year 1 Year 2 Year 3 Year 4 Year 5 Year 6 Year 7 Year 8 Year 9 Year 10 Terminal Value\n",
|
||||
"Pre-tax income 50000 55000 45000 52000 60000 \n",
|
||||
"Income Taxes 10000 11000 9000 10400 12000 \n",
|
||||
"Net Income 40000 44000 36000 41600 48000 \n",
|
||||
"Depreciation Expense 5000 4000 3000 2000 1000 \n",
|
||||
"Capital Expenditures 10000 8000 5000 5000 7000 \n",
|
||||
"Debt Repayments 5000 5000 5000 5000 5000 \n",
|
||||
"Net Cash Flow 20000 27000 23000 29600 35000 29093.333333333332 29817.777777777774 30177.481481481478 30469.234567901232 30379.73991769547 287188.0007003137\n",
|
||||
"Discounting Factor 0.8695652173913044 0.7561436672967865 0.6575162324319883 0.5717532455930334 0.4971767352982899 0.4971767352982899\n",
|
||||
"Present Value of Future Cash Flow 25298.550724637684 22546.523839529513 19842.183927989798 17420.883754932976 15104.099911490972 142783.19260502496\n",
|
||||
" \n",
|
||||
" \n",
|
||||
" 3 Year Weighted Moving Average \n",
|
||||
" Past Years Forecasted Future Years \n",
|
||||
" Year 1 Year 2 Year 3 Year 4 Year 5 Year 6 Terminal Value \n",
|
||||
"Pre-tax income 50000 55000 45000 \n",
|
||||
"Income Taxes 10000 11000 9000 \n",
|
||||
"Net Income 40000 44000 36000 \n",
|
||||
"Depreciation Expense 5000 4000 3000 \n",
|
||||
"Capital Expenditures 10000 8000 5000 \n",
|
||||
"Debt Repayments 5000 5000 5000 \n",
|
||||
"Net Cash Flow 20000 27000 23000 23833.333333333332 24083.333333333332 23819.44444444444 158253.58851674633 \n",
|
||||
"Discounting Factor 0.8695652173913044 0.7561436672967865 0.6575162324319883 0.6575162324319883 \n",
|
||||
"Present Value of Future Cash Flow 20724.63768115942 18210.459987397608 15661.671369734164 104054.30329037321 \n",
|
||||
" \n",
|
||||
" \n",
|
||||
"Notes: \n",
|
||||
"-We based this simple discounted cash flow excel model based on the weighted moving averages (5 year or 3 year) for simplicity, in case a constant growth rate cannot be easily determined. \n",
|
||||
"-The factors such as Depreciation Expense, Capital Expense and Debt Repayments remain constant, so consider this when looking at the forecasted figures. \n",
|
||||
"-For the terminal value constant growth rate, we make the assumption of the growth from the last forecasted year compared to the first forecasted year. Adjust in the formula as needed. \n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(base_docs[1].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "ff6e812f-fa94-4b0f-8907-ee70983e53f1",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from llama_index.core import SummaryIndex\n",
|
||||
"\n",
|
||||
"base_index = SummaryIndex.from_documents([base_docs[1]])\n",
|
||||
"\n",
|
||||
"base_query_engine = base_index.as_query_engine()"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "markdown",
|
||||
"id": "fa75f1bc-6fed-4721-ba5e-dc5408395618",
|
||||
"metadata": {},
|
||||
"source": [
|
||||
"## Ask Questions over this Data\n",
|
||||
"\n",
|
||||
"Let's now ask questions over this data, using both the LlamaParse-powered pipeline and naive pipeline."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "a875a20e-a6b6-46b7-80d4-614546215ffc",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_str = \"Tell me about the income taxes in the past years (year 3-5) for the 5 year WMA table\"\n",
|
||||
"response = query_engine.query(query_str)\n",
|
||||
"base_response = base_query_engine.query(query_str)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "06b0b072-f159-47c4-9cad-9f0cc0d56b28",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"******* LlamaParse RAG *******\n",
|
||||
"The income taxes in the past years (year 3 to 5) for the 5-year Weighted Moving Average table were $9,000.00 in Year 3, $10,400.00 in Year 4, and $12,000.00 in Year 5.\n",
|
||||
"******* Naive RAG *******\n",
|
||||
"The income taxes in the past years (year 3-5) for the 5 year WMA table were $9,000, $10,400, and $12,000, respectively.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"******* LlamaParse RAG *******\")\n",
|
||||
"print(str(response))\n",
|
||||
"print(\"******* Naive RAG *******\")\n",
|
||||
"print(str(base_response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "8bd0998f-4f7f-46f9-9b51-cfb510f384ee",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"print(response.source_nodes[0].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "7a93af5f-fcea-4f14-80eb-5dfad230cd8a",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_str = \"Tell me about the discounting factors in year 5 for the 3 year WMA\"\n",
|
||||
"response = query_engine.query(query_str)\n",
|
||||
"base_response = base_query_engine.query(query_str)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "c6d3a5fb-c32c-4dea-8f2e-956af85456a4",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"******* LlamaParse RAG *******\n",
|
||||
"The discounting factor in year 5 for the 3-year Weighted Moving Average (WMA) is 0.7561.\n",
|
||||
"******* Naive RAG *******\n",
|
||||
"The discounting factor in year 5 for the 3-year Weighted Moving Average is 0.6575162324319883.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"******* LlamaParse RAG *******\")\n",
|
||||
"print(str(response))\n",
|
||||
"print(\"******* Naive RAG *******\")\n",
|
||||
"print(str(base_response))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "b96f3a9b-6e99-4192-b6d6-447319d3c4fa",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"query_str = \"Tell me about the projected net cash flow in years 7-9 for the 5 year WMA\"\n",
|
||||
"response = query_engine.query(query_str)\n",
|
||||
"base_response = base_query_engine.query(query_str)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "92b419b9-25ee-4d69-98d9-56c0a45b24af",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"******* LlamaParse RAG *******\n",
|
||||
"The projected net cash flow for years 7 to 9 in the 5-year Weighted Moving Average scenario is as follows: Year 7 is $29,817.78, Year 8 is $30,177.48, and Year 9 is $30,469.23.\n",
|
||||
"******* Naive RAG *******\n",
|
||||
"The projected net cash flow for years 7 to 9 in the 5-year weighted moving average scenario is as follows: Year 7 is $29,093.33, Year 8 is $29,817.78, and Year 9 is $30,177.48.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(\"******* LlamaParse RAG *******\")\n",
|
||||
"print(str(response))\n",
|
||||
"print(\"******* Naive RAG *******\")\n",
|
||||
"print(str(base_response))"
|
||||
]
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"kernelspec": {
|
||||
"display_name": "llama_parse",
|
||||
"language": "python",
|
||||
"name": "llama_parse"
|
||||
},
|
||||
"language_info": {
|
||||
"codemirror_mode": {
|
||||
"name": "ipython",
|
||||
"version": 3
|
||||
},
|
||||
"file_extension": ".py",
|
||||
"mimetype": "text/x-python",
|
||||
"name": "python",
|
||||
"nbconvert_exporter": "python",
|
||||
"pygments_lexer": "ipython3"
|
||||
}
|
||||
},
|
||||
"nbformat": 4,
|
||||
"nbformat_minor": 5
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 334 KiB |
@@ -113,6 +113,7 @@
|
||||
" result_type=\"markdown\",\n",
|
||||
" # api_key=api_key,\n",
|
||||
" gpt4o_mode=True,\n",
|
||||
" split_by_page=True,\n",
|
||||
" # gpt4o_api_key=\"<gpt4o_api_key>\"\n",
|
||||
")"
|
||||
]
|
||||
@@ -127,7 +128,8 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Started parsing the file under job_id 1a934a50-59a9-4bb4-bbb7-ecefff228537\n"
|
||||
"Started parsing the file under job_id bf7d4619-3e26-479d-80e9-25702186ef32\n",
|
||||
"."
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -145,66 +147,6 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"# Impact Report\n",
|
||||
"## 2019\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"TESLA\n",
|
||||
"---\n",
|
||||
"# Introduction 03\n",
|
||||
"\n",
|
||||
"# Mission and Tesla Ecosystem 04\n",
|
||||
"\n",
|
||||
"# Environmental Impact 06\n",
|
||||
"- Lifecycle Analysis of Tesla Vehicles versus Average ICE\n",
|
||||
"- Battery Recycling\n",
|
||||
"- NOx, Particulates and Other Pollutants\n",
|
||||
"- Water Used per Vehicle Manufactured\n",
|
||||
"- Emissions Credits\n",
|
||||
"- Net Energy Impact of Our Products\n",
|
||||
"\n",
|
||||
"# Product Impact 20\n",
|
||||
"- Price Equivalency\n",
|
||||
"- Primary Driver\n",
|
||||
"- Long Distance Travel\n",
|
||||
"- Active Safety\n",
|
||||
"- Passive Safety\n",
|
||||
"- Tesla Safety Awards\n",
|
||||
"- Fire Safety\n",
|
||||
"- Cyber Security\n",
|
||||
"- Disaster Relief\n",
|
||||
"- Resilience of the Grid\n",
|
||||
"- Megapack\n",
|
||||
"- Solar Roof\n",
|
||||
"\n",
|
||||
"# Supply Chain 33\n",
|
||||
"- Responsible Material Sourcing\n",
|
||||
"- Cobalt Sourcing\n",
|
||||
"\n",
|
||||
"# People and Culture 37\n",
|
||||
"- Our Environmental, Health, and Safety Strategy\n",
|
||||
"- Safety Improvements\n",
|
||||
"- Case Study: Ergonomics and Model Y Design\n",
|
||||
"- Rewarding the Individual\n",
|
||||
"- Culture of Diversity and Inclusion\n",
|
||||
"- Workforce Development\n",
|
||||
"- Community Engagement\n",
|
||||
"- Employee Mobility and Transportation Programs\n",
|
||||
"- Corporate Governance\n",
|
||||
"\n",
|
||||
"# Appendix 52\n",
|
||||
"---\n",
|
||||
"# Introduction\n",
|
||||
"\n",
|
||||
"The very purpose of Tesla’s existence is to accelerate the world’s transition to sustainable energy. In furtherance of this mission, we are excited to publish our second annual Impact Report. Transparency and disclosure are important for our customers, employees, and shareholders, which is why we have expanded the Impact Report’s content this year.\n",
|
||||
"\n",
|
||||
"While many environmental reports focus on emissions generated by the manufacturing phase of products and future goals for energy consumption, we highlight the totality of the environmental impact of our products today. After all, the vast majority of emissions generated by vehicles today occur in the product-use phase—that is, when consumers are driving their vehicles. We believe that providing information on both sides of the manufacturing and consumer-use equation provides a clearer picture of the environmental impact of Tesla products, and we have done so this year largely through a lifecycle analysis detailed in this report.\n",
|
||||
"\n",
|
||||
"Tesla aims to continue to increase the proportion of renewable energy usage at our factories in an effort to minimize the carbon footprint for every mile traveled by our products and their components in our supply chain. All of the factories that we built from the ground-up, such as Gigafactory Nevada and Gigafactory Shanghai, and our forthcoming Gigafactories in Berlin and North America, are designed from the beginning to use energy from renewable sources.\n",
|
||||
"\n",
|
||||
"Making a significant and lasting impact on environmental sustainability is difficult to achieve without securing financial sustainability for the long term. We generated positive Free Cash Flow (operating cash flow less capex) of more than $1 billion for the first time in 2019. We believe the notion that a sustainable future is not economically feasible is no longer valid.\n",
|
||||
"---\n",
|
||||
"# Mission & Tesla Ecosystem\n",
|
||||
"\n",
|
||||
"Climate change is reaching alarming levels in large part due to emissions from burning fossil fuels for transportation and electricity generation. In 2016, carbon dioxide (CO2) concentration levels in the atmosphere exceeded the 400 parts per million threshold on a sustained basis - a level that climate scientists believe will have a catastrophic impact on the environment. Worse, annual global CO2 emissions continue to increase and have approximately doubled over the past 50 years to over 43 gigatons in 2019. The world’s current path is unwise and unsustainable.\n",
|
||||
@@ -213,7 +155,9 @@
|
||||
"\n",
|
||||
"Since the onset of shelter-in-place orders and travel restrictions due to COVID-19, we have seen dramatic increases in air quality across the planet, as well as projections for CO2 emissions to drop in excess of 4% in 2020 compared to pre-COVID-19 levels, according to researchers. Because these improvements in air quality and reductions in CO2 are a result of a global economic disruption and not due to systemic changes in how we produce and consume energy, they are not expected to be sustained absent intervention. However, these changes have shown us the positive impacts of reduced pollution in a very short period of time. At Tesla, we believe that we all have an unprecedented opportunity to learn from this disruption and accelerate the deployment of clean energy solutions as part of a recovery for all economies throughout the world, and we will actively continue to advocate for the realization of these long-term changes.\n",
|
||||
"\n",
|
||||
"## Global Greenhouse Gas (GHG) Emissions by Economic Sector\n",
|
||||
"| Global Greenhouse Gas (GHG) Emissions by Economic Sector |\n",
|
||||
"|----------------------------------------------------------|\n",
|
||||
"|  |\n",
|
||||
"\n",
|
||||
"| Sector | Percentage |\n",
|
||||
"|---------------------------------------------|------------|\n",
|
||||
@@ -226,281 +170,12 @@
|
||||
"\n",
|
||||
"*Tesla-related sectors. Source: World Resources Institute\n",
|
||||
"\n",
|
||||
"According to the Global Carbon project, when fully tallied, total carbon emissions from 2019 are expected to hit another record high of over 43 gigatons for the year. Energy use through electricity and heat production (31%) and transportation (16%) are significant drivers of these GHG emissions.\n",
|
||||
"---\n",
|
||||
"# Mission & Tesla Ecosystem\n",
|
||||
"\n",
|
||||
"To create an entire sustainable energy ecosystem, Tesla also manufactures a unique set of energy products that enable homeowners, businesses and utilities to produce and manage renewable energy generation, storage and consumption. Homeowners can install solar panels or Solar Roof to power their home using 100% renewable energy and then store that energy in Powerwall, which makes electricity available during peak energy-use periods and at night, while also providing power during grid outages. Meanwhile, depending on their particular requirements and the size of the project, utilities and businesses can purchase Megapack – an infinitely scalable energy storage system that provides greater control, efficiency, and reliability across the electric grid – for their energy storage needs.\n",
|
||||
"\n",
|
||||
"Renewable energy generation and storage are critical components of developing microgrids — an increasingly important means of delivering reliable and sustainable electricity around the world. As the deployment of Tesla’s products continues to accelerate, we can scale the adoption of renewable energy, cost-effectively modernize our aging infrastructure (while becoming less reliant on it), and improve the resilience of the electric grid to benefit everyone.\n",
|
||||
"---\n",
|
||||
"# Environmental Impact\n",
|
||||
"---\n",
|
||||
"# Introduction\n",
|
||||
"\n",
|
||||
"In this section of the Impact Report, we will go through the details and calculations of the lifetime environmental impact of our products.\n",
|
||||
"\n",
|
||||
"We are often asked if electric vehicles (EVs) are more sustainable than internal combustion engine (ICE) vehicles. The environmental impact of zero-emission transport and energy products, like the products that Tesla produces and sells, is undeniably more positive than the GHG-emitting alternatives. However, determining the lifetime impact of EVs versus ICE vehicles requires looking at the entire lifecycle - from raw materials to emissions to disposal and not just at the emissions resulting from vehicle usage.\n",
|
||||
"\n",
|
||||
"This is not a straightforward task and some of the most common omissions that we have seen in similar studies include the following:\n",
|
||||
"\n",
|
||||
"a) Using Worldwide Harmonized Light Vehicle Test Procedure (WLTP) or Environmental Protection Agency (EPA) fuel/energy consumption data (which overestimate fuel-economy and underestimate emissions), rather than real-world data;\n",
|
||||
"\n",
|
||||
"b) Not taking into account the higher energy efficiency of Tesla’s powertrains;\n",
|
||||
"\n",
|
||||
"c) Assuming that the average EV needs a battery replacement at some point in its life;\n",
|
||||
"\n",
|
||||
"d) Not accounting for emissions generated through oil refining and the transportation process; and\n",
|
||||
"\n",
|
||||
"e) Using outdated data for the carbon impact of cell manufacturing.\n",
|
||||
"\n",
|
||||
"We tried to address these considerations and complexities in deriving a more accurate calculation in the following lifecycle analysis.\n",
|
||||
"\n",
|
||||
"It is important to remember that environmental impact goes beyond just carbon footprint. According to the World Health Organization (WHO), more than four million people die of air pollution every year. The reduction of Nitrogen Oxides (NOx) and other particulates in the air makes our communities healthier places to live, work, and visit and is another core benefit of driving an EV.\n",
|
||||
"\n",
|
||||
"In addition, solar panels deployed by Tesla (including SolarCity prior to its 2016 acquisition by Tesla) over the years have generated vastly more electricity than what was required to run our factories and related facilities.\n",
|
||||
"---\n",
|
||||
"# Lifecycle Analysis of Tesla EVs versus Average ICE Vehicles\n",
|
||||
"\n",
|
||||
"## 69 tons\n",
|
||||
"Lifetime CO2 emitted by an average combustion engine vehicle (model year 2019) sold in the U.S. through its use phase, excluding CO2 emitted during the oil refining phase.\n",
|
||||
"\n",
|
||||
"---\n",
|
||||
"\n",
|
||||
"On the right and in the following pages we have laid out our lifecycle analysis, which includes the emissions per mile from:\n",
|
||||
"\n",
|
||||
"- A current Fremont-made Model 3 charged from a grid with the generation mix that reflects the geographic distribution of Model 3 deliveries in the U.S.\n",
|
||||
"- What emissions per mile could be if the Model 3 were used for ridesharing over one million miles using cell chemistry from our energy products.\n",
|
||||
"- What emissions per mile could be if a Model 3 were principally charged at home using a solar system and energy storage.\n",
|
||||
"- What emissions per mile could be if a Model 3 were used for ridesharing over one million miles using cell chemistry from our energy products and if it were only charged using a solar system and energy storage.\n",
|
||||
"- The reference ICE vehicle is based on the average mid-size premium sedan in the U.S.\n",
|
||||
"\n",
|
||||
"---\n",
|
||||
"\n",
|
||||
"The most important variable in a life cycle analysis is real-world fuel consumption or electricity consumption, which impacts the use phase of the lifecycle. Various efficiency testing cycles such as the New European Driving Cycle (NEDC), WLTP, or EPA don’t truly represent real-world fuel/energy consumption. This is why, for the purpose of this analysis, we used average energy consumption over the more than 4 billion miles Tesla Model 3s have travelled to date, including energy losses during the charging process. For ICE vehicles, we used real-world fuel consumption data provided by Consumer Reports, according to which mid-size premium sedans for model year 2019 on average achieve 23.6 MPG, and this translates to approximately 420 grams of CO2 per mile, once we account for emissions generated through extraction, refining, and shipment of oil.\n",
|
||||
"\n",
|
||||
"Even if we use the official EPA efficiency rating (instead of real-world data) for a Toyota Prius of 56 MPG, which translates to 177 grams of CO2 per mile (incl. refining & transport of oil), an EV would still emit fewer lifetime emissions than the Prius. Regarding mileage and lifespan, we estimate that an average vehicle in the U.S. is driven slightly less than 12,000 miles per year for about 17 years before it is scrapped. Furthermore, as an ICE vehicle ages, its fuel efficiency only remains stable if serviced properly. On the other hand, electricity generation to charge EVs has become “greener” over time with the addition of cleaner energy sources to the grid. Thus, emissions generated through EV charging should continue to decline over time.\n",
|
||||
"\n",
|
||||
"It is important to highlight that, for the purpose of this analysis, we assumed no additional renewable energy capacity on the grid during the life of the vehicle given the shape of the renewable energy adoption curve in the U.S. is still very much up for debate. That said, in the following slide we show that a Tesla Model 3 charged in locations with “greener” grids like New York state, for example, have much lower lifecycle emissions than the U.S. average. We believe that cities, states, and countries alike will strive to reduce grid emissions in the future. This dynamic highlights how EVs on the road today will become cleaner as they age and how critical “greening” the grid will be to achieving reduced transportation emissions.\n",
|
||||
"\n",
|
||||
"---\n",
|
||||
"\n",
|
||||
"## Average Lifecycle Emissions in U.S. (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| | Manufacturing Phase | Use Phase |\n",
|
||||
"|--------------------|---------------------|-----------|\n",
|
||||
"| Model 3 Ridesharing Use (solar charged) | | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged) | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | |\n",
|
||||
"| Avg. Mid-Size Premium ICE | | |\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"---\n",
|
||||
"# Reducing Carbon Footprint Even Further\n",
|
||||
"## Increasing Proportion of Renewable Energy Sources\n",
|
||||
"\n",
|
||||
"Charging a Model 3 using solar panels and a Powerwall adds emissions to the manufacturing phase while reducing use phase emissions as low as zero when 100% of charging is done using that system. The personal use scenario below assumes 18% of charging is done using the public fast-charging network, based on observed fleet behavior.\n",
|
||||
"\n",
|
||||
"### Average Lifecycle Emissions in U.S. (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| | Manufacturing Phase | Use Phase |\n",
|
||||
"|--------------------|---------------------|-----------|\n",
|
||||
"| Avg. Mid-Size Premium ICE | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged) | | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | |\n",
|
||||
"| Model 3 Ridesharing Use (solar charged) | | |\n",
|
||||
"\n",
|
||||
"While the electricity grid varies from region to region, charging EVs is becoming less carbon intensive every year. In the U.S., coal has historically been the dominant energy source for generating electricity. But in the last decade, coal power has declined significantly as regions turn to cleaner energy sources. Energy generated by renewable sources has grown rapidly, accounting for an estimated 43% of new electricity generation capacity in 2018. Many U.S. states (such as New York referenced in the chart below) have been making significant investments in renewable energy as these sustainable options become more cost competitive compared to fossil fuel resources.\n",
|
||||
"\n",
|
||||
"To put this in perspective, average GHG emissions from charging one New York-based Tesla vehicle equates to the emissions from an ICE vehicle with a fuel economy of 144 MPG (no such vehicle is on the market). Even when charging a Tesla in Michigan, where approximately 64% of energy comes from coal and natural gas, the emissions from our vehicles still equates to the equivalent emissions of an ICE vehicle with 55 real-world MPG (considerably more in terms of EPA rated MPG). As more regions adopt sustainable energy solutions to generate power, emissions related to charging an EV from the grid will decrease even further.\n",
|
||||
"\n",
|
||||
"EV customers can accelerate the process of increasing their renewable energy mix by installing solar panels or a Solar Roof and an energy storage solution, such as Powerwall, in their homes. Such an effort dramatically reduces the lifetime carbon footprint of an EV, even when accounting for the carbon footprint of both the solar panel/Solar roof and Powerwall manufacturing. Remaining use-phase emissions from solar charged vehicles come from publicly available fast-charging, which too is becoming “greener” every year. Our goal is to strategically pair solar and battery storage at as many Tesla Supercharger stations as is feasible.\n",
|
||||
"\n",
|
||||
"### Average Lifecycle Emissions in New York State (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| | Manufacturing Phase | Use Phase |\n",
|
||||
"|--------------------|---------------------|-----------|\n",
|
||||
"| Model 3 Ridesharing Use (solar charged) | | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged) | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | |\n",
|
||||
"| Avg. Mid-Size Premium ICE | | |\n",
|
||||
"---\n",
|
||||
"# Reducing Carbon Footprint Even Further\n",
|
||||
"## Improving Powertrain Efficiency\n",
|
||||
"\n",
|
||||
"Tesla vehicles are known to have the highest energy efficiency of any EV built to date. In the early days of Model S production, we were able to achieve energy efficiency of 3.1 EPA miles / kWh. Today, our most efficient Model 3 Standard Range Plus (SR+) achieves an EPA range of 4.8 miles / kWh, more than any EV in production. Model Y all-wheel drive (AWD) achieves 4.1 EPA miles / kWh, which makes it the most efficient electric SUV produced to date.\n",
|
||||
"\n",
|
||||
"The energy efficiency of Tesla vehicles will continue to improve further over time as we continue to improve our technology and powertrain efficiency. It is also reasonable to assume that our high-mileage products, such as our future Tesla Robotaxis, will be designed for maximum energy efficiency as handling, acceleration, and top speed become less relevant. That way, we will minimize cost for our customers as well as reduce the carbon footprint per mile driven.\n",
|
||||
"\n",
|
||||
"### Average Lifecycle Emissions in U.S. (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| Vehicle Type | Manufacturing Phase | Use Phase | Total Emissions |\n",
|
||||
"|---------------------------------------|---------------------|-----------|-----------------|\n",
|
||||
"| Avg. Mid-Size Premium ICE | | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged)| | | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (solar charged)| | | |\n",
|
||||
"\n",
|
||||
"*Note: The exact values for the manufacturing and use phases are not provided in the image.*\n",
|
||||
"\n",
|
||||
"### Energy Efficiency EPA range in miles/kWh\n",
|
||||
"\n",
|
||||
"| Vehicle Model | EPA Range (miles/kWh) |\n",
|
||||
"|---------------------|-----------------------|\n",
|
||||
"| Model 3 SR+ | 5 |\n",
|
||||
"| Model 3 AWD | 4.5 |\n",
|
||||
"| Model Y AWD | 4.5 |\n",
|
||||
"| Hyundai Kona | 4 |\n",
|
||||
"| Chevy Bolt | 4 |\n",
|
||||
"| Model S LR+ | 4 |\n",
|
||||
"| Nissan Leaf | 3.5 |\n",
|
||||
"| Model X LR+ | 3.5 |\n",
|
||||
"| Jaguar iPace | 3 |\n",
|
||||
"| Mercedes EQC* | 3 |\n",
|
||||
"| Ford Mach E AWD | 3 |\n",
|
||||
"| Audi e-tron | 3 |\n",
|
||||
"| Porsche Taycan | 3 |\n",
|
||||
"\n",
|
||||
"*Tesla estimate. Source: OEM websites*\n",
|
||||
"---\n",
|
||||
"# Reducing Carbon Footprint Even Further\n",
|
||||
"## Reducing Emissions at our Factories\n",
|
||||
"\n",
|
||||
"While emissions from the manufacturing phase can account for a relatively minor portion of lifetime vehicle emissions when compared to the use-phase, it is still an important part of lifecycle emissions. Thus, we strive to source as much renewable energy where possible for our factories in an effort to reduce our manufacturing-phase emissions.\n",
|
||||
"\n",
|
||||
"As we continue to ramp production of Tesla products, we are committed to making significant progress towards our goal of operating global Tesla manufacturing, vehicle charging, and other operations using 100% renewable energy.\n",
|
||||
"\n",
|
||||
"Predominantly due to lack of reliable data, various third-party studies tend to overstate the actual energy requirement, and therefore the associated emissions, for battery manufacturing. In fact, in 2019, the emissions from producing a full EV were nearly comparable to than the emissions from producing an average ICE vehicle. That said, battery manufacturing technology continues to improve rapidly, and we expect the EV manufacturing energy requirement and associated emissions to drop significantly in the near future.\n",
|
||||
"\n",
|
||||
"In the second half of 2018, Tesla launched an Operations Energy Efficiency Program (OEEP) aimed at reducing energy usage across our factories in Fremont, Nevada, and Buffalo. In 2019, the OEEP helped us to achieve energy consumption reductions while we simultaneously ramped new lines and products across the three facilities. Our goal is to install as many solar panels as is practically feasible on the roofs of all of our manufacturing facilities.\n",
|
||||
"\n",
|
||||
"### Average Lifecycle Emissions in U.S. (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| Vehicle Type | Manufacturing Phase | Use Phase | Total Emissions |\n",
|
||||
"|---------------------------------------|---------------------|-----------|-----------------|\n",
|
||||
"| Avg. Mid-Size Premium ICE | | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged)| | | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (solar charged)| | | |\n",
|
||||
"\n",
|
||||
"### gCO2e/mi for Model 3 Battery Pack versus Rest of Vehicle\n",
|
||||
"\n",
|
||||
"| Year | Battery Pack | Rest of Vehicle |\n",
|
||||
"|------|--------------|-----------------|\n",
|
||||
"| 2017 | 60 | |\n",
|
||||
"| 2019 | 30 | |\n",
|
||||
"---\n",
|
||||
"# Reducing Carbon Footprint Even Further\n",
|
||||
"## Reducing Emissions at our Factories - Gigafactory Shanghai\n",
|
||||
"\n",
|
||||
"Underpinning our strategy for regional manufacturing is a reduction of carbon emissions that result from shipping parts and finished products. From a sustainability standpoint, having vertically integrated Tesla factories in each region helps to reduce the carbon footprint for our operations.\n",
|
||||
"\n",
|
||||
"As highlighted in Tesla’s fourth quarter earnings call for 2019, reductions in shipping costs as well as the strain on the environment from avoided trans-oceanic shipping also makes good business sense. A simplified factory design and localized supply chain near the factory saves time and creates efficiencies, and localized delivery saves outbound logistics costs.\n",
|
||||
"\n",
|
||||
"Our newly opened Gigafactory outside of Shanghai, China has provided us the opportunity to set up and implement the most simplified flows based on what we have learned from the operation of our U.S. factories. The design simplification and operational efficiencies result in time and monetary savings for Gigafactory Shanghai and less carbon emissions per vehicle produced.\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"### Average Lifecycle Emissions in U.S. (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| Vehicle Type | Manufacturing Phase | Use Phase | Total Emissions |\n",
|
||||
"|---------------------------------------|---------------------|-----------|-----------------|\n",
|
||||
"| Avg. Mid-Size Premium ICE | | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged)| | | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (solar charged)| | | |\n",
|
||||
"\n",
|
||||
"- **Avg. Mid-Size Premium ICE**: ~450 gCO2e/mi\n",
|
||||
"- **Model 3 Personal Use (grid charged)**: ~200 gCO2e/mi\n",
|
||||
"- **Model 3 Ridesharing Use (grid charged)**: ~150 gCO2e/mi\n",
|
||||
"- **Model 3 Personal Use (solar charged)**: ~100 gCO2e/mi\n",
|
||||
"- **Model 3 Ridesharing Use (solar charged)**: ~50 gCO2e/mi\n",
|
||||
"\n",
|
||||
"**Reducing Factory Emissions**\n",
|
||||
"\n",
|
||||
"- **Manufacturing Phase**: Blue\n",
|
||||
"- **Use Phase**: Light Blue\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"---\n",
|
||||
"# Reducing Carbon Footprint Even Further\n",
|
||||
"## Increasing Vehicle Utilization\n",
|
||||
"\n",
|
||||
"Tesla’s battery packs are designed to outlast the car. We estimate that a vehicle gets scrapped after approximately 200,000 miles of usage in the U.S. and roughly 130,000 miles in Europe. Creating a battery that could instead last for a 1,000,000 miles (4,000 to 5,000 charging cycles) would dramatically reduce emissions per vehicle produced.\n",
|
||||
"\n",
|
||||
"All vehicles in the world combined travel trillions of miles every year. A relatively small number of vehicles, such as taxis, delivery vans, trucks, or buses, account for a disproportionate amount of vehicle miles and as a result, a disproportionate amount of emissions.\n",
|
||||
"\n",
|
||||
"A single future Tesla vehicle with a million-mile battery could be utilized over five times more than an average vehicle in the U.S. (almost eight times more than an average vehicle sold in Europe). As a portion of the carbon footprint is emitted during the production phase of each vehicle, utilization of such vehicle over 1,000,000 miles dramatically reduces the lifetime carbon footprint per each mile travelled. Furthermore, battery recycling has the potential to further reduce emissions as components of a battery pack can be captured and reused, displacing much of the need for raw material mining and the associated emissions.\n",
|
||||
"\n",
|
||||
"### Average Lifecycle Emissions in U.S. (gCO2e/mi)\n",
|
||||
"\n",
|
||||
"| Vehicle Type | Manufacturing Phase | Use Phase |\n",
|
||||
"|---------------------------------------|---------------------|-----------|\n",
|
||||
"| Avg. Mid-Size Premium ICE | | |\n",
|
||||
"| Model 3 Personal Use (grid charged) | | |\n",
|
||||
"| Model 3 Ridesharing Use (grid charged)| | |\n",
|
||||
"| Model 3 Personal Use (solar charged) | | |\n",
|
||||
"| Model 3 Ridesharing Use (solar charged)| | |\n",
|
||||
"\n",
|
||||
"### Tesla Model S/X Battery Capacity Retention per Distance Traveled\n",
|
||||
"\n",
|
||||
"| Distance Traveled (thousands of miles) | Retention | Standard Deviation |\n",
|
||||
"|----------------------------------------|-----------|--------------------|\n",
|
||||
"| 0 | 100% | |\n",
|
||||
"| 25 | | |\n",
|
||||
"| 50 | | |\n",
|
||||
"| 75 | | |\n",
|
||||
"| 100 | | |\n",
|
||||
"| 125 | | |\n",
|
||||
"| 150 | | |\n",
|
||||
"| 175 | | |\n",
|
||||
"| 200 | | |\n",
|
||||
"---\n",
|
||||
"# Battery Recycling\n",
|
||||
"\n",
|
||||
"A common question we hear is, “What happens to Tesla vehicle battery packs once they reach their end of life?” An important distinction between fossil fuels and lithium-ion batteries as an energy source is that while fossil fuels are extracted and used once, the materials in a lithium-ion battery are recyclable. When petroleum is pumped out of the ground, chemically refined, and then burned, it releases harmful emissions into the atmosphere that are not recovered for reuse. Battery materials, in contrast, are refined and put into a cell, and will still remain in the cell at the end of their life, when they can be recycled to recover valuable materials for reuse over and over again.\n",
|
||||
"\n",
|
||||
"Extending the life of a battery pack is a superior option to recycling for both environmental and business reasons. For those reasons, before decommissioning a consumer battery pack and sending it for recycling, Tesla does everything it can to extend the useful life of each battery pack. Any battery that is no longer meeting a customer’s needs can be serviced by Tesla at one of our service centers around the world.\n",
|
||||
"\n",
|
||||
"Tesla’s current vehicle batteries are designed to outlast our cars. We estimate an average ICE vehicle in the U.S. is scrapped after 17 years of usage, by which time it will have ~200,000 miles on its odometer. Data from our fleet of over 1 million Tesla vehicles on the road shows that our vehicles that have been driven between 150,000 and 200,000 miles had battery packs that degraded by less than 15% on average.\n",
|
||||
"\n",
|
||||
"# Battery Materials Lifecycle\n",
|
||||
"\n",
|
||||
"| Step | Description |\n",
|
||||
"|-----------------------------|--------------------------------|\n",
|
||||
"| Raw material mining | |\n",
|
||||
"| Battery production | |\n",
|
||||
"| Lifetime usage in a vehicle | |\n",
|
||||
"| Battery recycling | Extracting raw materials |\n",
|
||||
"---\n",
|
||||
"# Battery Recycling at Gigafactory Nevada\n",
|
||||
"\n",
|
||||
"## Global annual amount of li-ion battery metals sent for recycling by Tesla in 2019\n",
|
||||
"\n",
|
||||
"- **1,000** Tons of Nickel\n",
|
||||
"- **320** Tons of Copper\n",
|
||||
"- **110** Tons of Cobalt\n",
|
||||
"\n",
|
||||
"A closed-loop battery recycling process presents a compelling solution to move energy supply away from the fossil-fuel based practice of take, make and burn, to a more circular model of recycling end-of-life batteries for reuse over and over again.\n",
|
||||
"\n",
|
||||
"Tesla battery packs are made to last many years and therefore we have only received a limited number of these batteries back from the field. Most batteries that Tesla recycles today are pre-consumer, coming to us through R&D and quality control. None of our scrapped lithium-ion batteries go to landfilling, and 100% are recycled. The small amount of post-consumer batteries that we receive are generated from our fleet of vehicles on the road, predominantly from taxi-like vehicles. Since we have only been producing Model S for approximately eight years, it will likely be some time before we start receiving back vehicle batteries in larger volumes.\n",
|
||||
"\n",
|
||||
"All materials contained in a battery remain in their original form at end-of-life and the vast majority of these materials are then captured in the recycling process. Presently, only high-value elements are recycled and re-introduced into the supply chain. However, as recycling technology improves, we strive to re-introduce more and more materials back into their original commodity markets. Over half of the materials in a battery cell are metals, which is great for sustainability given they are infinitely recyclable. The remaining materials are plastics, organics, and other difficult to re-use materials. Research is underway by organizations all over the world to improve the ability to recycle these remaining materials.\n",
|
||||
"\n",
|
||||
"Today, we work with third-party recyclers around the world to process all scrap and end-of-life batteries to recover valuable metals. Our recycling partners work with us to ensure that non-valuable or non-recoverable materials from the batteries are disposed of responsibly.\n",
|
||||
"\n",
|
||||
"Tesla is currently developing a unique battery recycling system at Gigafactory Nevada that will process both battery manufacturing scrap and end-of-life batteries. Through this system, the recovery of critical minerals will be maximized along with the recovery of all metals used in Tesla battery cells, such as copper, aluminum and steel. Our ultimate goal is to develop a recycling process that has high recovery rates, low costs, and a low environmental impact. From an economic perspective, we expect to recognize significant savings over the long term, as the costs associated with large-scale battery material recovery and recycling will be far lower than purchasing and transporting new materials to put into cells.\n"
|
||||
"According to the Global Carbon project, when fully tallied, total carbon emissions from 2019 are expected to hit another record high of over 43 gigatons for the year. Energy use through electricity and heat production (31%) and transportation (16%) are significant drivers of these GHG emissions.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"print(documents_gpt4o[0].get_content())"
|
||||
"print(documents_gpt4o[3].get_content())"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -515,44 +190,6 @@
|
||||
"We ask a question over the parsed markdown table and get back the right answer! We also ask a question over the text."
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "bb991e26-f9e5-404f-9d2c-73dbba12554b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from copy import deepcopy\n",
|
||||
"from llama_index.core.schema import TextNode\n",
|
||||
"from llama_index.core import VectorStoreIndex\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def get_nodes(docs):\n",
|
||||
" \"\"\"Split docs into nodes, by separator.\"\"\"\n",
|
||||
" nodes = []\n",
|
||||
" for doc in docs:\n",
|
||||
" doc_chunks = doc.text.split(\"\\n---\\n\")\n",
|
||||
" for doc_chunk in doc_chunks:\n",
|
||||
" node = TextNode(\n",
|
||||
" text=doc_chunk,\n",
|
||||
" metadata=deepcopy(doc.metadata),\n",
|
||||
" )\n",
|
||||
" nodes.append(node)\n",
|
||||
"\n",
|
||||
" return nodes"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"id": "de1b3606-259a-44cf-9892-3c31d6516c2b",
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# this will split into pages\n",
|
||||
"nodes = get_nodes(documents_gpt4o)"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
@@ -560,7 +197,9 @@
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"vector_index = VectorStoreIndex(nodes)"
|
||||
"from llama_index.core import VectorStoreIndex\n",
|
||||
"\n",
|
||||
"vector_index = VectorStoreIndex(documents_gpt4o)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -595,7 +234,7 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The greenhouse emissions for agriculture and transportation are 20% and 16% respectively.\n"
|
||||
"Agriculture accounts for 20% of global greenhouse gas emissions, while transportation contributes 16% of these emissions.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -633,7 +272,7 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"The EPA range of Tesla vehicles, such as the Model 3 Standard Range Plus achieving 4.8 miles/kWh and the Model Y all-wheel drive achieving 4.1 miles/kWh, surpasses that of other electric vehicles currently in production. For example, the Hyundai Kona, Chevy Bolt, Model S LR+, and Nissan Leaf have EPA ranges ranging from 3.5 to 4 miles/kWh, while the Jaguar iPace, Mercedes EQC, Ford Mach E AWD, Audi e-tron, and Porsche Taycan have EPA ranges of 3 miles/kWh. This indicates that Tesla vehicles generally have higher energy efficiency and longer EPA ranges compared to other electric vehicles available in the market.\n"
|
||||
"The EPA range of Tesla vehicles varies across different models. The Model 3 Standard Range Plus (SR+) achieves an EPA range of 4.8 miles/kWh, making it the most efficient electric vehicle in production. The Model Y all-wheel drive (AWD) achieves 4.1 miles/kWh, which positions it as the most efficient electric SUV produced to date. The energy efficiency of Tesla vehicles is highlighted by these EPA range figures, showcasing their advancements in powertrain efficiency compared to other electric vehicles on the market.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -668,25 +307,25 @@
|
||||
"| Model 3 Personal Use (solar charged) | | | |\n",
|
||||
"| Model 3 Ridesharing Use (solar charged)| | | |\n",
|
||||
"\n",
|
||||
"*Note: The exact values for the manufacturing and use phases are not provided in the image.*\n",
|
||||
"*Note: The chart shows that the emissions depend on powertrain efficiency.*\n",
|
||||
"\n",
|
||||
"### Energy Efficiency EPA range in miles/kWh\n",
|
||||
"\n",
|
||||
"| Vehicle Model | EPA Range (miles/kWh) |\n",
|
||||
"|---------------------|-----------------------|\n",
|
||||
"| Model 3 SR+ | 5 |\n",
|
||||
"| Model 3 AWD | 4.5 |\n",
|
||||
"| Model Y AWD | 4.5 |\n",
|
||||
"| Hyundai Kona | 4 |\n",
|
||||
"| Chevy Bolt | 4 |\n",
|
||||
"| Model S LR+ | 4 |\n",
|
||||
"| Nissan Leaf | 3.5 |\n",
|
||||
"| Model X LR+ | 3.5 |\n",
|
||||
"| Jaguar iPace | 3 |\n",
|
||||
"| Mercedes EQC* | 3 |\n",
|
||||
"| Ford Mach E AWD | 3 |\n",
|
||||
"| Audi e-tron | 3 |\n",
|
||||
"| Porsche Taycan | 3 |\n",
|
||||
"| Model 3 SR+ | 4.8 |\n",
|
||||
"| Model 3 AWD | |\n",
|
||||
"| Model Y AWD | |\n",
|
||||
"| Hyundai Kona | |\n",
|
||||
"| Chevy Bolt | |\n",
|
||||
"| Model S LR+ | |\n",
|
||||
"| Nissan Leaf | |\n",
|
||||
"| Model X LR+ | |\n",
|
||||
"| Jaguar iPace | |\n",
|
||||
"| Mercedes EQC* | |\n",
|
||||
"| Ford Mach E AWD | |\n",
|
||||
"| Audi e-tron | |\n",
|
||||
"| Porsche Taycan | |\n",
|
||||
"\n",
|
||||
"*Tesla estimate. Source: OEM websites*\n"
|
||||
]
|
||||
|
||||
+130
-34
@@ -5,6 +5,7 @@ import mimetypes
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import List, Optional, Union
|
||||
from io import BufferedIOBase
|
||||
|
||||
from llama_index.core.async_utils import run_jobs
|
||||
from llama_index.core.bridge.pydantic import Field, validator
|
||||
@@ -18,6 +19,26 @@ from llama_parse.utils import (
|
||||
Language,
|
||||
SUPPORTED_FILE_TYPES,
|
||||
)
|
||||
from copy import deepcopy
|
||||
|
||||
# can put in a path to the file or the file bytes itself
|
||||
# if passing as bytes or a buffer, must provide the file_name in extra_info
|
||||
FileInput = Union[str, bytes, BufferedIOBase]
|
||||
|
||||
|
||||
def _get_sub_docs(docs: List[Document]) -> List[Document]:
|
||||
"""Split docs into pages, by separator."""
|
||||
sub_docs = []
|
||||
for doc in docs:
|
||||
doc_chunks = doc.text.split("\n---\n")
|
||||
for doc_chunk in doc_chunks:
|
||||
sub_doc = Document(
|
||||
text=doc_chunk,
|
||||
metadata=deepcopy(doc.metadata),
|
||||
)
|
||||
sub_docs.append(sub_doc)
|
||||
|
||||
return sub_docs
|
||||
|
||||
|
||||
class LlamaParse(BasePydanticReader):
|
||||
@@ -63,7 +84,23 @@ class LlamaParse(BasePydanticReader):
|
||||
)
|
||||
invalidate_cache: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="If set to true, the cache will be ignored and the document re-processes. All document are kept in cache for 48hours after the job was completed to avoid processing 2 time the same document.",
|
||||
description="If set to true, the cache will be ignored and the document re-processes. All document are kept in cache for 48hours after the job was completed to avoid processing the same document twice.",
|
||||
)
|
||||
do_not_cache: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="If set to true, the document will not be cached. This mean that you will be re-charged it you reprocess them as they will not be cached.",
|
||||
)
|
||||
fast_mode: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="Note: Non compatible with gpt-4o. If set to true, the parser will use a faster mode to extract text from documents. This mode will skip OCR of images, and table/heading reconstruction.",
|
||||
)
|
||||
do_not_unroll_columns: Optional[bool] = Field(
|
||||
default=False,
|
||||
description="If set to true, the parser will keep column in the text according to document layout. Reduce reconstruction accuracy, and LLM's/embedings performances in most case.",
|
||||
)
|
||||
page_separator: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The page separator to use to split the text. Default is None, which means the parser will use the default separator '\\n---\\n'.",
|
||||
)
|
||||
gpt4o_mode: bool = Field(
|
||||
default=False,
|
||||
@@ -73,10 +110,34 @@ class LlamaParse(BasePydanticReader):
|
||||
default=None,
|
||||
description="The API key for the GPT-4o API. Lowers the cost of parsing.",
|
||||
)
|
||||
bounding_box: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The bounding box to use to extract text from documents describe as a string containing the bounding box margins",
|
||||
)
|
||||
target_pages: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The target pages to extract text from documents. Describe as a comma separated list of page numbers. The first page of the document is page 0",
|
||||
)
|
||||
ignore_errors: bool = Field(
|
||||
default=True,
|
||||
description="Whether or not to ignore and skip errors raised during parsing.",
|
||||
)
|
||||
split_by_page: bool = Field(
|
||||
default=True,
|
||||
description="Whether to split by page (NOTE: using a predefined separator `\n---\n`)",
|
||||
)
|
||||
vendor_multimodal_api_key: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The API key for the multimodal API.",
|
||||
)
|
||||
use_vendor_multimodal: bool = Field(
|
||||
default=False,
|
||||
description="Whether to use the vendor multimodal API.",
|
||||
)
|
||||
vendor_multimodal_model_name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The model name for the vendor multimodal API.",
|
||||
)
|
||||
|
||||
@validator("api_key", pre=True, always=True)
|
||||
def validate_api_key(cls, v: str) -> str:
|
||||
@@ -99,28 +160,39 @@ class LlamaParse(BasePydanticReader):
|
||||
|
||||
# upload a document and get back a job_id
|
||||
async def _create_job(
|
||||
self, file_path: str, extra_info: Optional[dict] = None
|
||||
self, file_input: FileInput, extra_info: Optional[dict] = None
|
||||
) -> str:
|
||||
file_path = str(file_path)
|
||||
file_ext = os.path.splitext(file_path)[1]
|
||||
if file_ext not in SUPPORTED_FILE_TYPES:
|
||||
raise Exception(
|
||||
f"Currently, only the following file types are supported: {SUPPORTED_FILE_TYPES}\n"
|
||||
f"Current file type: {file_ext}"
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
url = f"{self.base_url}/api/parsing/upload"
|
||||
files = None
|
||||
file_handle = None
|
||||
|
||||
if isinstance(file_input, (bytes, BufferedIOBase)):
|
||||
if not extra_info or "file_name" not in extra_info:
|
||||
raise ValueError(
|
||||
"file_name must be provided in extra_info when passing bytes"
|
||||
)
|
||||
file_name = extra_info["file_name"]
|
||||
mime_type = mimetypes.guess_type(file_name)[0]
|
||||
files = {"file": (file_name, file_input, mime_type)}
|
||||
elif isinstance(file_input, (str, Path)):
|
||||
file_path = str(file_input)
|
||||
file_ext = os.path.splitext(file_path)[1]
|
||||
if file_ext not in SUPPORTED_FILE_TYPES:
|
||||
raise Exception(
|
||||
f"Currently, only the following file types are supported: {SUPPORTED_FILE_TYPES}\n"
|
||||
f"Current file type: {file_ext}"
|
||||
)
|
||||
mime_type = mimetypes.guess_type(file_path)[0]
|
||||
# Open the file here for the duration of the async context
|
||||
file_handle = open(file_path, "rb")
|
||||
files = {"file": (os.path.basename(file_path), file_handle, mime_type)}
|
||||
else:
|
||||
raise ValueError(
|
||||
"file_input must be either a file path string, file bytes, or buffer object"
|
||||
)
|
||||
|
||||
extra_info = extra_info or {}
|
||||
extra_info["file_path"] = file_path
|
||||
|
||||
headers = {"Authorization": f"Bearer {self.api_key}"}
|
||||
|
||||
# load data, set the mime type
|
||||
with open(file_path, "rb") as f:
|
||||
mime_type = mimetypes.guess_type(file_path)[0]
|
||||
files = {"file": (f.name, f, mime_type)}
|
||||
|
||||
# send the request, start job
|
||||
url = f"{self.base_url}/api/parsing/upload"
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.max_timeout) as client:
|
||||
response = await client.post(
|
||||
url,
|
||||
@@ -131,16 +203,23 @@ class LlamaParse(BasePydanticReader):
|
||||
"parsing_instruction": self.parsing_instruction,
|
||||
"invalidate_cache": self.invalidate_cache,
|
||||
"skip_diagonal_text": self.skip_diagonal_text,
|
||||
"do_not_cache": self.do_not_cache,
|
||||
"fast_mode": self.fast_mode,
|
||||
"do_not_unroll_columns": self.do_not_unroll_columns,
|
||||
"page_separator": self.page_separator,
|
||||
"gpt4o_mode": self.gpt4o_mode,
|
||||
"gpt4o_api_key": self.gpt4o_api_key,
|
||||
"bounding_box": self.bounding_box,
|
||||
"target_pages": self.target_pages,
|
||||
},
|
||||
)
|
||||
if not response.is_success:
|
||||
raise Exception(f"Failed to parse the file: {response.text}")
|
||||
|
||||
# check the status of the job, return when done
|
||||
job_id = response.json()["id"]
|
||||
return job_id
|
||||
job_id = response.json()["id"]
|
||||
return job_id
|
||||
finally:
|
||||
if file_handle is not None:
|
||||
file_handle.close()
|
||||
|
||||
async def _get_job_result(
|
||||
self, job_id: str, result_type: str, verbose: bool = False
|
||||
@@ -190,7 +269,10 @@ class LlamaParse(BasePydanticReader):
|
||||
)
|
||||
|
||||
async def _aload_data(
|
||||
self, file_path: str, extra_info: Optional[dict] = None, verbose: bool = False
|
||||
self,
|
||||
file_path: FileInput,
|
||||
extra_info: Optional[dict] = None,
|
||||
verbose: bool = False,
|
||||
) -> List[Document]:
|
||||
"""Load data from the input path."""
|
||||
try:
|
||||
@@ -202,25 +284,32 @@ class LlamaParse(BasePydanticReader):
|
||||
job_id, self.result_type.value, verbose=verbose
|
||||
)
|
||||
|
||||
return [
|
||||
docs = [
|
||||
Document(
|
||||
text=result[self.result_type.value],
|
||||
metadata=extra_info or {},
|
||||
)
|
||||
]
|
||||
if self.split_by_page:
|
||||
return _get_sub_docs(docs)
|
||||
else:
|
||||
return docs
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error while parsing the file '{file_path}':", e)
|
||||
file_repr = file_path if isinstance(file_path, str) else "<bytes/buffer>"
|
||||
print(f"Error while parsing the file '{file_repr}':", e)
|
||||
if self.ignore_errors:
|
||||
return []
|
||||
else:
|
||||
raise e
|
||||
|
||||
async def aload_data(
|
||||
self, file_path: Union[List[str], str], extra_info: Optional[dict] = None
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[Document]:
|
||||
"""Load data from the input path."""
|
||||
if isinstance(file_path, (str, Path)):
|
||||
if isinstance(file_path, (str, Path, bytes, BufferedIOBase)):
|
||||
return await self._aload_data(
|
||||
file_path, extra_info=extra_info, verbose=self.verbose
|
||||
)
|
||||
@@ -254,7 +343,9 @@ class LlamaParse(BasePydanticReader):
|
||||
)
|
||||
|
||||
def load_data(
|
||||
self, file_path: Union[List[str], str], extra_info: Optional[dict] = None
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[Document]:
|
||||
"""Load data from the input path."""
|
||||
try:
|
||||
@@ -266,7 +357,7 @@ class LlamaParse(BasePydanticReader):
|
||||
raise e
|
||||
|
||||
async def _aget_json(
|
||||
self, file_path: str, extra_info: Optional[dict] = None
|
||||
self, file_path: FileInput, extra_info: Optional[dict] = None
|
||||
) -> List[dict]:
|
||||
"""Load data from the input path."""
|
||||
try:
|
||||
@@ -280,14 +371,17 @@ class LlamaParse(BasePydanticReader):
|
||||
return [result]
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error while parsing the file '{file_path}':", e)
|
||||
file_repr = file_path if isinstance(file_path, str) else "<bytes/buffer>"
|
||||
print(f"Error while parsing the file '{file_repr}':", e)
|
||||
if self.ignore_errors:
|
||||
return []
|
||||
else:
|
||||
raise e
|
||||
|
||||
async def aget_json(
|
||||
self, file_path: Union[List[str], str], extra_info: Optional[dict] = None
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[dict]:
|
||||
"""Load data from the input path."""
|
||||
if isinstance(file_path, (str, Path)):
|
||||
@@ -315,7 +409,9 @@ class LlamaParse(BasePydanticReader):
|
||||
)
|
||||
|
||||
def get_json_result(
|
||||
self, file_path: Union[List[str], str], extra_info: Optional[dict] = None
|
||||
self,
|
||||
file_path: Union[List[FileInput], FileInput],
|
||||
extra_info: Optional[dict] = None,
|
||||
) -> List[dict]:
|
||||
"""Parse the input path."""
|
||||
try:
|
||||
|
||||
+72
-38
@@ -101,59 +101,93 @@ class Language(str, Enum):
|
||||
|
||||
SUPPORTED_FILE_TYPES = [
|
||||
".pdf",
|
||||
# Microsoft word - all versions
|
||||
# document and presentations
|
||||
".602",
|
||||
".abw",
|
||||
".cgm",
|
||||
".cwk",
|
||||
".doc",
|
||||
".docx",
|
||||
".docm",
|
||||
".dot",
|
||||
".dotx",
|
||||
".dotm",
|
||||
# Rich text format
|
||||
".hwp",
|
||||
".key",
|
||||
".lwp",
|
||||
".mw",
|
||||
".mcw",
|
||||
".pages",
|
||||
".pbd",
|
||||
".ppt",
|
||||
".pptm",
|
||||
".pptx",
|
||||
".pot",
|
||||
".potm",
|
||||
".potx",
|
||||
".rtf",
|
||||
# Microsoft Works
|
||||
".wps",
|
||||
# Word Perfect
|
||||
".wpd",
|
||||
# Open Office
|
||||
".sda",
|
||||
".sdd",
|
||||
".sdp",
|
||||
".sdw",
|
||||
".sgl",
|
||||
".sti",
|
||||
".sxi",
|
||||
".sxw",
|
||||
".stw",
|
||||
".sxg",
|
||||
# Apple
|
||||
".pages",
|
||||
# Mac Write
|
||||
".mw",
|
||||
".mcw",
|
||||
# Unified Office Format text
|
||||
".uot",
|
||||
".txt",
|
||||
".uof",
|
||||
".uos",
|
||||
".uop",
|
||||
# Microsoft powerpoints
|
||||
".ppt",
|
||||
".pptx",
|
||||
".pot",
|
||||
".pptm",
|
||||
".potx",
|
||||
".potm",
|
||||
# Apple keynote
|
||||
".key",
|
||||
# Open Office Presentations
|
||||
".odp",
|
||||
".odg",
|
||||
".otp",
|
||||
".fopd",
|
||||
".sxi",
|
||||
".sti",
|
||||
# ebook
|
||||
".uot",
|
||||
".vor",
|
||||
".wpd",
|
||||
".wps",
|
||||
".xml",
|
||||
".zabw",
|
||||
".epub",
|
||||
# html
|
||||
".html",
|
||||
".htm",
|
||||
# media,
|
||||
# images
|
||||
".jpg",
|
||||
".jpeg",
|
||||
".png",
|
||||
".tiff",
|
||||
".gif",
|
||||
".bmp",
|
||||
".svg",
|
||||
".tiff",
|
||||
".webp",
|
||||
# web
|
||||
".htm",
|
||||
".html",
|
||||
# spreadsheets
|
||||
".xlsx",
|
||||
".xls",
|
||||
".xlsm",
|
||||
".xlsb",
|
||||
".xlw",
|
||||
".csv",
|
||||
".dif",
|
||||
".sylk",
|
||||
".slk",
|
||||
".prn",
|
||||
".numbers",
|
||||
".et",
|
||||
".ods",
|
||||
".fods",
|
||||
".uos1",
|
||||
".uos2",
|
||||
".dbf",
|
||||
".wk1",
|
||||
".wk2",
|
||||
".wk3",
|
||||
".wk4",
|
||||
".wks",
|
||||
".123",
|
||||
".wq1",
|
||||
".wq2",
|
||||
".wb1",
|
||||
".wb2",
|
||||
".wb3",
|
||||
".qpw",
|
||||
".xlr",
|
||||
".eth",
|
||||
".tsv",
|
||||
]
|
||||
|
||||
Generated
+695
-693
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -4,7 +4,7 @@ build-backend = "poetry.core.masonry.api"
|
||||
|
||||
[tool.poetry]
|
||||
name = "llama-parse"
|
||||
version = "0.4.4"
|
||||
version = "0.4.6"
|
||||
description = "Parse files into RAG-Optimized formats."
|
||||
authors = ["Logan Markewich <logan@llamaindex.ai>"]
|
||||
license = "MIT"
|
||||
|
||||
+43
-7
@@ -18,21 +18,57 @@ def test_simple_page_text() -> None:
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("LLAMA_CLOUD_API_KEY", "") == "",
|
||||
reason="LLAMA_CLOUD_API_KEY not set",
|
||||
)
|
||||
def test_simple_page_markdown() -> None:
|
||||
parser = LlamaParse(result_type="markdown")
|
||||
@pytest.fixture
|
||||
def markdown_parser() -> LlamaParse:
|
||||
if os.environ.get("LLAMA_CLOUD_API_KEY", "") == "":
|
||||
pytest.skip("LLAMA_CLOUD_API_KEY not set")
|
||||
return LlamaParse(result_type="markdown", ignore_errors=False)
|
||||
|
||||
|
||||
def test_simple_page_markdown(markdown_parser: LlamaParse) -> None:
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
result = markdown_parser.load_data(filepath)
|
||||
assert len(result) == 1
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
|
||||
def test_simple_page_markdown_bytes(markdown_parser: LlamaParse) -> None:
|
||||
markdown_parser = LlamaParse(result_type="markdown", ignore_errors=False)
|
||||
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
result = parser.load_data(filepath)
|
||||
with open(filepath, "rb") as f:
|
||||
file_bytes = f.read()
|
||||
# client must provide extra_info with file_name
|
||||
with pytest.raises(ValueError):
|
||||
result = markdown_parser.load_data(file_bytes)
|
||||
result = markdown_parser.load_data(
|
||||
file_bytes, extra_info={"file_name": "attention_is_all_you_need.pdf"}
|
||||
)
|
||||
assert len(result) == 1
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
|
||||
def test_simple_page_markdown_buffer(markdown_parser: LlamaParse) -> None:
|
||||
markdown_parser = LlamaParse(result_type="markdown", ignore_errors=False)
|
||||
|
||||
filepath = os.path.join(
|
||||
os.path.dirname(__file__), "test_files/attention_is_all_you_need.pdf"
|
||||
)
|
||||
with open(filepath, "rb") as f:
|
||||
# client must provide extra_info with file_name
|
||||
with pytest.raises(ValueError):
|
||||
result = markdown_parser.load_data(f)
|
||||
result = markdown_parser.load_data(
|
||||
f, extra_info={"file_name": "attention_is_all_you_need.pdf"}
|
||||
)
|
||||
assert len(result) == 1
|
||||
assert len(result[0].text) > 0
|
||||
|
||||
|
||||
@pytest.mark.skipif(
|
||||
os.environ.get("LLAMA_CLOUD_API_KEY", "") == "",
|
||||
reason="LLAMA_CLOUD_API_KEY not set",
|
||||
|
||||
Reference in New Issue
Block a user