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