Petition Decisions Example — pyUSPTO 0.2.3.dev1+g2c5d89b38.d20251125 documentation

# Petition Decisions Example

      1"""
      2Example usage of the pyUSPTO module for Final Petition Decisions
      3
      4This example demonstrates how to use the FinalPetitionDecisionsClient to interact with the
      5USPTO Final Petition Decisions API. It shows how to search for petition decisions, retrieve
      6specific decisions by ID, download decision data, and access detailed information about
      7petitions and their associated documents.
      8"""
      9
     10import os
     11
     12from pyUSPTO.clients import FinalPetitionDecisionsClient
     13from pyUSPTO.config import USPTOConfig
     14
     15# --- Initialization ---
     16# Choose one method to initialize the client.
     17# For this example, Method 1 is active. Replace "YOUR_API_KEY_HERE" with your actual key.
     18
     19# Method 1: Initialize the client with direct API key
     20print("Method 1: Initialize with direct API key")
     21api_key = os.environ.get("USPTO_API_KEY", "YOUR_API_KEY_HERE")
     22if api_key == "YOUR_API_KEY_HERE":
     23    raise ValueError(
     24        "WARNING: API key is not set. Please replace 'YOUR_API_KEY_HERE' or set USPTO_API_KEY environment variable."
     25    )
     26client = FinalPetitionDecisionsClient(api_key=api_key)
     27
     28# Method 2: Initialize the client with USPTOConfig (alternative)
     29# print("\nMethod 2: Initialize with USPTOConfig")
     30# config_obj = USPTOConfig(
     31#     api_key="YOUR_API_KEY_HERE",  # Replace with your actual API key
     32#     petition_decisions_base_url="https://api.uspto.gov",  # Optional, uses default if not set
     33# )
     34# client = FinalPetitionDecisionsClient(config=config_obj)
     35
     36# Method 3: Initialize the client with environment variables (recommended for production)
     37# print("\nMethod 3: Initialize with environment variables")
     38# # Ensure USPTO_API_KEY is set in your environment
     39# config_from_env = USPTOConfig.from_env()
     40# client = FinalPetitionDecisionsClient(config=config_from_env)
     41
     42print("\nBeginning API requests with configured client:")
     43
     44# Basic search for petition decisions
     45try:
     46    print("\n" + "=" * 60)
     47    print("Example 1: Basic Search for Petition Decisions")
     48    print("=" * 60)
     49
     50    response = client.search_decisions(limit=5)
     51    print(f"Found {response.count} total petition decisions.")
     52    print(f"Displaying first {len(response.petition_decision_data_bag)} decisions:")
     53
     54    for decision in response.petition_decision_data_bag:
     55        print(f"\n  Decision ID: {decision.petition_decision_record_identifier}")
     56        print(f"  Application Number: {decision.application_number_text}")
     57        print(f"  Decision Type: {decision.decision_type_code}")
     58        print(f"  Decision Date: {decision.decision_date}")
     59        print(f"  Technology Center: {decision.technology_center_number}")
     60
     61        if decision.applicant_name:
     62            print(f"  Applicant: {decision.applicant_name}")
     63
     64        if decision.patent_number:
     65            print(f"  Patent Number: {decision.patent_number}")
     66
     67        if decision.inventor_bag:
     68            print(f"  Inventors ({len(decision.inventor_bag)}):")
     69            for inventor in decision.inventor_bag[:3]:  # Show first 3
     70                name_parts = [
     71                    part for part in [inventor.first_name, inventor.last_name] if part
     72                ]
     73                print(f"    - {' '.join(name_parts).strip()}")
     74
     75        if decision.document_bag:
     76            print(f"  Documents: {len(decision.document_bag)}")
     77
     78        print("-" * 40)
     79
     80except Exception as e:
     81    print(f"Error in basic search: {e}")
     82
     83# Search with query parameter
     84try:
     85    print("\n" + "=" * 60)
     86    print("Example 2: Search with Custom Query")
     87    print("=" * 60)
     88
     89    # Search for decisions mentioning specific terms
     90    response = client.search_decisions(
     91        query="decisionTypeCode:GRANT",
     92        limit=3
     93    )
     94    print(f"Found {response.count} decisions with GRANT type.")
     95    print(f"Showing {len(response.petition_decision_data_bag)} results:")
     96
     97    for decision in response.petition_decision_data_bag:
     98        print(f"  - {decision.petition_decision_record_identifier}: {decision.decision_type_code}")
     99
    100except Exception as e:
    101    print(f"Error searching with query: {e}")
    102
    103# Search using convenience parameters
    104try:
    105    print("\n" + "=" * 60)
    106    print("Example 3: Search Using Convenience Parameters")
    107    print("=" * 60)
    108
    109    # Search by application number (if you have a specific one)
    110    print("\nSearching by date range...")
    111    response = client.search_decisions(
    112        decision_date_from_q="2023-01-01",
    113        decision_date_to_q="2023-12-31",
    114        limit=5
    115    )
    116    print(f"Found {response.count} decisions from 2023.")
    117
    118    # Search by technology center
    119    print("\nSearching by technology center...")
    120    response = client.search_decisions(
    121        technology_center_q="2600",
    122        limit=3
    123    )
    124    print(f"Found {response.count} decisions from Technology Center 2600.")
    125
    126except Exception as e:
    127    print(f"Error with convenience parameters: {e}")
    128
    129# Get a specific decision by ID
    130try:
    131    print("\n" + "=" * 60)
    132    print("Example 4: Get Specific Decision by ID")
    133    print("=" * 60)
    134
    135    # First, get a decision ID from search results
    136    response = client.search_decisions(limit=1)
    137    if response.count > 0:
    138        decision_id = response.petition_decision_data_bag[0].petition_decision_record_identifier
    139
    140        print(f"Retrieving decision: {decision_id}")
    141        decision = client.get_decision_by_id(decision_id)
    142
    143        print(f"\nDecision Details:")
    144        print(f"  ID: {decision.petition_decision_record_identifier}")
    145        print(f"  Application: {decision.application_number_text}")
    146        print(f"  Patent: {decision.patent_number}")
    147        print(f"  Decision Type: {decision.decision_type_code}")
    148        print(f"  Decision Date: {decision.decision_date}")
    149        print(f"  Technology Center: {decision.technology_center_number}")
    150        print(f"  Group Art Unit: {decision.group_art_unit_number}")
    151        print(f"  Examiner: {decision.examiner_name_text}")
    152
    153        if decision.rule_bag:
    154            print(f"\n  Rules Cited ({len(decision.rule_bag)}):")
    155            for rule in decision.rule_bag[:5]:  # Show first 5
    156                print(f"    - {rule}")
    157
    158        if decision.statute_bag:
    159            print(f"\n  Statutes Cited ({len(decision.statute_bag)}):")
    160            for statute in decision.statute_bag[:5]:  # Show first 5
    161                print(f"    - {statute}")
    162
    163        if decision.document_bag:
    164            print(f"\n  Associated Documents ({len(decision.document_bag)}):")
    165            for doc in decision.document_bag[:3]:  # Show first 3
    166                print(f"    - Doc ID: {doc.document_identifier}")
    167                print(f"      Date: {doc.official_date}")
    168                print(f"      Direction: {doc.document_direction_category}")
    169                if doc.page_total_quantity:
    170                    print(f"      Pages: {doc.page_total_quantity}")
    171                if doc.download_option_bag:
    172                    print(f"      Download Options: {len(doc.download_option_bag)}")
    173
    174except Exception as e:
    175    print(f"Error retrieving decision by ID: {e}")
    176
    177# Download petition decisions data
    178try:
    179    print("\n" + "=" * 60)
    180    print("Example 5: Download Petition Decisions Data")
    181    print("=" * 60)
    182
    183    # Download as JSON (returns response object)
    184    print("\nDownloading decisions as JSON...")
    185    response = client.download_decisions(
    186        format="json",
    187        decision_date_from_q="2023-01-01",
    188        limit=5
    189    )
    190    print(f"Downloaded JSON with {len(response.petition_decision_data)} decision records")
    191
    192    # Download as CSV (automatically saves to file)
    193    print("\nDownloading decisions as CSV...")
    194    csv_path = client.download_decisions(
    195        format="csv",
    196        decision_date_from_q="2023-01-01",
    197        limit=10,
    198        destination_path="./downloads"
    199    )
    200    print(f"Downloaded CSV to: {csv_path}")
    201
    202except Exception as e:
    203    print(f"Error downloading decisions: {e}")
    204
    205# Pagination example
    206try:
    207    print("\n" + "=" * 60)
    208    print("Example 6: Paginating Through Results")
    209    print("=" * 60)
    210
    211    page_size = 10
    212    max_pages = 3  # Limit to 3 pages for example
    213
    214    print(f"Paginating through results ({page_size} per page, max {max_pages} pages)...")
    215
    216    page_count = 0
    217    total_decisions = 0
    218
    219    for page_response in client.paginate_decisions(
    220        limit=page_size,
    221        query="decisionDate:[2023-01-01 TO 2023-12-31]"
    222    ):
    223        page_count += 1
    224        decisions_in_page = len(page_response.petition_decision_data_bag)
    225        total_decisions += decisions_in_page
    226
    227        print(f"  Page {page_count}: {decisions_in_page} decisions")
    228
    229        if page_count >= max_pages:
    230            print(f"  (Stopping after {max_pages} pages for example)")
    231            break
    232
    233    print(f"\nTotal decisions retrieved: {total_decisions} across {page_count} pages")
    234
    235except Exception as e:
    236    print(f"Error during pagination: {e}")
    237
    238# Download a petition document
    239try:
    240    print("\n" + "=" * 60)
    241    print("Example 7: Download Petition Decision Document")
    242    print("=" * 60)
    243
    244    # Find a decision with downloadable documents
    245    response = client.search_decisions(limit=20)
    246
    247    document_found = False
    248    for decision in response.petition_decision_data_bag:
    249        if decision.document_bag:
    250            for doc in decision.document_bag:
    251                if doc.download_option_bag and len(doc.download_option_bag) > 0:
    252                    download_option = doc.download_option_bag[0]
    253
    254                    print(f"Found downloadable document:")
    255                    print(f"  Document ID: {doc.document_identifier}")
    256                    print(f"  MIME Type: {download_option.mime_type_identifier}")
    257                    print(f"  Pages: {download_option.page_total_quantity}")
    258                    print(f"  URL: {download_option.download_url}")
    259
    260                    print(f"\nDownloading document...")
    261                    file_path = client.download_petition_document(
    262                        download_option,
    263                        file_path="./downloads"
    264                    )
    265                    print(f"Downloaded to: {file_path}")
    266
    267                    document_found = True
    268                    break
    269
    270        if document_found:
    271            break
    272
    273    if not document_found:
    274        print("No downloadable documents found in the first 20 results")
    275
    276except Exception as e:
    277    print(f"Error downloading document: {e}")
    278
    279# Advanced search example
    280try:
    281    print("\n" + "=" * 60)
    282    print("Example 8: Advanced Search with Multiple Criteria")
    283    print("=" * 60)
    284
    285    # Search with multiple parameters
    286    response = client.search_decisions(
    287        application_number_q="16*",  # Applications starting with 16
    288        decision_date_from_q="2020-01-01",
    289        technology_center_q="2600",
    290        limit=10
    291    )
    292
    293    print(f"Search criteria:")
    294    print(f"  - Application numbers starting with '16'")
    295    print(f"  - Decision date from 2020-01-01")
    296    print(f"  - Technology Center 2600")
    297    print(f"\nFound {response.count} matching decisions")
    298
    299    if response.count > 0:
    300        print(f"Showing first {len(response.petition_decision_data_bag)} results:")
    301        for decision in response.petition_decision_data_bag:
    302            print(f"  - App: {decision.application_number_text}, "
    303                  f"TC: {decision.technology_center_number}, "
    304                  f"Date: {decision.decision_date}")
    305
    306except Exception as e:
    307    print(f"Error in advanced search: {e}")
    308
    309print("\n" + "=" * 60)
    310print("Examples completed!")
    311print("=" * 60)