code: from llama_index import SimpleDirectoryReader, VectorStoreIndex, load_index_from_storage
  from llama_index.storage.storage_context import StorageContext
  from llama_index.indices.service_context import ServiceContext
  from llama_index.llms import OpenAI
  from llama_index.node_parser import SimpleNodeParser
  from llama_index.node_parser.extractors import (
      MetadataExtractor,
      SummaryExtractor,
      QuestionsAnsweredExtractor,
      TitleExtractor,
      KeywordExtractor,
  )
  from llama_index.text_splitter import TokenTextSplitter
  from dotenv import load_dotenv
  import openai
  import gradio as gr
  import sys, os
  import logging
  import json
  
  #loads dotenv lib to retrieve API keys from .env file
  load_dotenv()
  
  openai.api_key = os.getenv("OPENAI_API_KEY")
  
  # enable INFO level logging
  logging.basicConfig(stream=sys.stdout, level=logging.INFO)
  logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))
  
  #define LLM service
  llm = OpenAI(temperature=0.1, model_name="gpt-3.5-turbo", max_tokens=512)
  service_context = ServiceContext.from_defaults(llm=llm)
  
  #construct text splitter to split texts into chunks for processing
  text_splitter = TokenTextSplitter(separator=" ", chunk_size=512, chunk_overlap=128)
  
  #set the global service context object, avoiding passing service_context when building the index 
  from llama_index import set_global_service_context
  set_global_service_context(service_context)
  
  #create metadata extractor
  metadata_extractor = MetadataExtractor(
      extractors=[
          TitleExtractor(nodes=1, llm=llm),
          QuestionsAnsweredExtractor(questions=3, llm=llm),
          SummaryExtractor(summaries=["prev", "self"], llm=llm),
          KeywordExtractor(keywords=10, llm=llm)
      ],
  )
  
  #create node parser to parse nodes from document
  node_parser = SimpleNodeParser(
      text_splitter=text_splitter,
      metadata_extractor=metadata_extractor,
  )
  
  #loading documents
  documents_2022 = SimpleDirectoryReader(input_files=["data/executive-summary-2022.pdf"], filename_as_id=True).load_data()
  print(f"loaded documents_2022 with {len(documents_2022)} pages")
  documents_2021 = SimpleDirectoryReader(input_files=["data/executive-summary-2021.pdf"], filename_as_id=True).load_data()
  print(f"loaded documents_2021 with {len(documents_2021)} pages")
  
  def load_index():
       
      try:
          #load storage context
          storage_context = StorageContext.from_defaults(persist_dir="./storage")
          #try to load the index from storage
          index = load_index_from_storage(storage_context)
          logging.info("Index loaded from storage.")
          
      except FileNotFoundError:
          #if index not found, create a new one
          logging.info("Index not found. Creating a new one...")
  
          nodes_2022 = node_parser.get_nodes_from_documents(documents_2022)
          nodes_2021 = node_parser.get_nodes_from_documents(documents_2021)
          print(f"loaded nodes_2022 with {len(nodes_2022)} nodes")
          print(f"loaded nodes_2021 with {len(nodes_2021)} nodes")
  
          #print metadata in json format
          for node in nodes_2022:
              metadata_json = json.dumps(node.metadata, indent=4)  # Convert metadata to formatted JSON
              print(metadata_json)
  
          for node in nodes_2021:
              metadata_json = json.dumps(node.metadata, indent=4)  # Convert metadata to formatted JSON
              print(metadata_json)
  
          #based on the nodes and service_context, create index
          index = VectorStoreIndex(nodes=nodes_2022 + nodes_2021, service_context=service_context)
          # Persist index to disk
          index.storage_context.persist()
          logging.info("New index created and persisted to storage.")
  
      return index
  
  def data_querying(input_text):
  
      # Load index
      index = load_index()
  
      #queries the index with the input text
      response = index.as_query_engine().query(input_text)
      
      return response.response
  
  iface = gr.Interface(fn=data_querying,
                       inputs=gr.components.Textbox(lines=3, label="Enter your question"),
                       outputs="text",
                       title="Analyzing the U.S. Government's Financial Reports for 2022")
  
  iface.launch(share=False)
apis: llama_index.node_parser.extractors.KeywordExtractor llama_index.text_splitter.TokenTextSplitter llama_index.node_parser.SimpleNodeParser llama_index.SimpleDirectoryReader llama_index.storage.storage_context.StorageContext.from_defaults llama_index.node_parser.extractors.QuestionsAnsweredExtractor llama_index.node_parser.extractors.SummaryExtractor llama_index.llms.OpenAI llama_index.VectorStoreIndex llama_index.node_parser.extractors.TitleExtractor llama_index.load_index_from_storage llama_index.indices.service_context.ServiceContext.from_defaults llama_index.set_global_service_context
extract_api: [((692, 705), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (703, 705), False, 'from dotenv import load_dotenv\n'), ((724, 751), 'os.getenv', 'os.getenv', (['"""OPENAI_API_KEY"""'], {}), "('OPENAI_API_KEY')\n", (733, 751), False, 'import sys, os\n'), ((781, 839), 'logging.basicConfig', 'logging.basicConfig', ([], {'stream': 'sys.stdout', 'level': 'logging.INFO'}), '(stream=sys.stdout, level=logging.INFO)\n', (800, 839), False, 'import logging\n'), ((940, 1007), 'llama_index.llms.OpenAI', 'OpenAI', ([], {'temperature': '(0.1)', 'model_name': '"""gpt-3.5-turbo"""', 'max_tokens': '(512)'}), "(temperature=0.1, model_name='gpt-3.5-turbo', max_tokens=512)\n", (946, 1007), False, 'from llama_index.llms import OpenAI\n'), ((1026, 1063), 'llama_index.indices.service_context.ServiceContext.from_defaults', 'ServiceContext.from_defaults', ([], {'llm': 'llm'}), '(llm=llm)\n', (1054, 1063), False, 'from llama_index.indices.service_context import ServiceContext\n'), ((1148, 1215), 'llama_index.text_splitter.TokenTextSplitter', 'TokenTextSplitter', ([], {'separator': '""" """', 'chunk_size': '(512)', 'chunk_overlap': '(128)'}), "(separator=' ', chunk_size=512, chunk_overlap=128)\n", (1165, 1215), False, 'from llama_index.text_splitter import TokenTextSplitter\n'), ((1366, 1409), 'llama_index.set_global_service_context', 'set_global_service_context', (['service_context'], {}), '(service_context)\n', (1392, 1409), False, 'from llama_index import set_global_service_context\n'), ((1778, 1867), 'llama_index.node_parser.SimpleNodeParser', 'SimpleNodeParser', ([], {'text_splitter': 'text_splitter', 'metadata_extractor': 'metadata_extractor'}), '(text_splitter=text_splitter, metadata_extractor=\n    metadata_extractor)\n', (1794, 1867), False, 'from llama_index.node_parser import SimpleNodeParser\n'), ((871, 911), 'logging.StreamHandler', 'logging.StreamHandler', ([], {'stream': 'sys.stdout'}), '(stream=sys.stdout)\n', (892, 911), False, 'import logging\n'), ((840, 859), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (857, 859), False, 'import logging\n'), ((1911, 2006), 'llama_index.SimpleDirectoryReader', 'SimpleDirectoryReader', ([], {'input_files': "['data/executive-summary-2022.pdf']", 'filename_as_id': '(True)'}), "(input_files=['data/executive-summary-2022.pdf'],\n    filename_as_id=True)\n", (1932, 2006), False, 'from llama_index import SimpleDirectoryReader, VectorStoreIndex, load_index_from_storage\n'), ((2097, 2192), 'llama_index.SimpleDirectoryReader', 'SimpleDirectoryReader', ([], {'input_files': "['data/executive-summary-2021.pdf']", 'filename_as_id': '(True)'}), "(input_files=['data/executive-summary-2021.pdf'],\n    filename_as_id=True)\n", (2118, 2192), False, 'from llama_index import SimpleDirectoryReader, VectorStoreIndex, load_index_from_storage\n'), ((2356, 2409), 'llama_index.storage.storage_context.StorageContext.from_defaults', 'StorageContext.from_defaults', ([], {'persist_dir': '"""./storage"""'}), "(persist_dir='./storage')\n", (2384, 2409), False, 'from llama_index.storage.storage_context import StorageContext\n'), ((2470, 2510), 'llama_index.load_index_from_storage', 'load_index_from_storage', (['storage_context'], {}), '(storage_context)\n', (2493, 2510), False, 'from llama_index import SimpleDirectoryReader, VectorStoreIndex, load_index_from_storage\n'), ((2519, 2561), 'logging.info', 'logging.info', (['"""Index loaded from storage."""'], {}), "('Index loaded from storage.')\n", (2531, 2561), False, 'import logging\n'), ((3960, 4019), 'gradio.components.Textbox', 'gr.components.Textbox', ([], {'lines': '(3)', 'label': '"""Enter your question"""'}), "(lines=3, label='Enter your question')\n", (3981, 4019), True, 'import gradio as gr\n'), ((1503, 1535), 'llama_index.node_parser.extractors.TitleExtractor', 'TitleExtractor', ([], {'nodes': '(1)', 'llm': 'llm'}), '(nodes=1, llm=llm)\n', (1517, 1535), False, 'from llama_index.node_parser.extractors import MetadataExtractor, SummaryExtractor, QuestionsAnsweredExtractor, TitleExtractor, KeywordExtractor\n'), ((1545, 1593), 'llama_index.node_parser.extractors.QuestionsAnsweredExtractor', 'QuestionsAnsweredExtractor', ([], {'questions': '(3)', 'llm': 'llm'}), '(questions=3, llm=llm)\n', (1571, 1593), False, 'from llama_index.node_parser.extractors import MetadataExtractor, SummaryExtractor, QuestionsAnsweredExtractor, TitleExtractor, KeywordExtractor\n'), ((1603, 1656), 'llama_index.node_parser.extractors.SummaryExtractor', 'SummaryExtractor', ([], {'summaries': "['prev', 'self']", 'llm': 'llm'}), "(summaries=['prev', 'self'], llm=llm)\n", (1619, 1656), False, 'from llama_index.node_parser.extractors import MetadataExtractor, SummaryExtractor, QuestionsAnsweredExtractor, TitleExtractor, KeywordExtractor\n'), ((1666, 1704), 'llama_index.node_parser.extractors.KeywordExtractor', 'KeywordExtractor', ([], {'keywords': '(10)', 'llm': 'llm'}), '(keywords=10, llm=llm)\n', (1682, 1704), False, 'from llama_index.node_parser.extractors import MetadataExtractor, SummaryExtractor, QuestionsAnsweredExtractor, TitleExtractor, KeywordExtractor\n'), ((2655, 2709), 'logging.info', 'logging.info', (['"""Index not found. Creating a new one..."""'], {}), "('Index not found. Creating a new one...')\n", (2667, 2709), False, 'import logging\n'), ((3443, 3528), 'llama_index.VectorStoreIndex', 'VectorStoreIndex', ([], {'nodes': '(nodes_2022 + nodes_2021)', 'service_context': 'service_context'}), '(nodes=nodes_2022 + nodes_2021, service_context=service_context\n    )\n', (3459, 3528), False, 'from llama_index import SimpleDirectoryReader, VectorStoreIndex, load_index_from_storage\n'), ((3604, 3663), 'logging.info', 'logging.info', (['"""New index created and persisted to storage."""'], {}), "('New index created and persisted to storage.')\n", (3616, 3663), False, 'import logging\n'), ((3089, 3124), 'json.dumps', 'json.dumps', (['node.metadata'], {'indent': '(4)'}), '(node.metadata, indent=4)\n', (3099, 3124), False, 'import json\n'), ((3257, 3292), 'json.dumps', 'json.dumps', (['node.metadata'], {'indent': '(4)'}), '(node.metadata, indent=4)\n', (3267, 3292), False, 'import json\n')]