|
| 1 | +from zai import ZaiClient |
| 2 | +import time |
| 3 | +import traceback |
| 4 | + |
| 5 | +client = ZaiClient( |
| 6 | + base_url="", |
| 7 | + api_key="" |
| 8 | +) |
| 9 | + |
| 10 | + |
| 11 | +def file_parser_create_example(file_path, tool_type, file_type): |
| 12 | + """ |
| 13 | + Example: Create a file parsing task |
| 14 | + """ |
| 15 | + print("=== File Parser Create Example ===") |
| 16 | + with open(file_path, 'rb') as f: |
| 17 | + print("Submitting file parsing task ...") |
| 18 | + response = client.file_parser.create( |
| 19 | + file=f, |
| 20 | + file_type=file_type, |
| 21 | + tool_type=tool_type, |
| 22 | + ) |
| 23 | + print("Task created successfully. Response:") |
| 24 | + print(response) |
| 25 | + # Usually you can get task_id |
| 26 | + task_id = getattr(response, "task_id", None) |
| 27 | + return task_id |
| 28 | + |
| 29 | + |
| 30 | +def file_parser_content_example(task_id, format_type="download_link"): |
| 31 | + """ |
| 32 | + Example: Get file parsing result |
| 33 | + """ |
| 34 | + print("=== File Parser Content Example ===") |
| 35 | + try: |
| 36 | + print(f"Querying parsing result for task_id: {task_id}") |
| 37 | + response = client.file_parser.content( |
| 38 | + task_id=task_id, |
| 39 | + format_type=format_type |
| 40 | + ) |
| 41 | + return response |
| 42 | + except Exception as err: |
| 43 | + print("Failed to get parsing result:", traceback.format_exc()) |
| 44 | + return None |
| 45 | + |
| 46 | + |
| 47 | +def file_parser_complete_example(): |
| 48 | + """ |
| 49 | + Full Example: Submit file for parsing, then poll until result is ready |
| 50 | + """ |
| 51 | + # 1. Create parsing task |
| 52 | + # Please modify the local file path |
| 53 | + file_path = 'your file path' |
| 54 | + task_id = file_parser_create_example(file_path=file_path, tool_type="lite", file_type="pdf") |
| 55 | + if not task_id: |
| 56 | + print("Could not submit file for parsing.") |
| 57 | + return |
| 58 | + |
| 59 | + # 2. Poll to get the result |
| 60 | + max_wait = 60 # Wait up to 1 minute |
| 61 | + wait_time = 0 |
| 62 | + while wait_time < max_wait: |
| 63 | + print(f"Waiting {wait_time}/{max_wait} seconds before querying result...") |
| 64 | + # format_type = text / download_link |
| 65 | + response = file_parser_content_example(task_id=task_id, format_type="download_link") |
| 66 | + |
| 67 | + result = response.json() |
| 68 | + if result.get("status") == "processing": |
| 69 | + print(result) |
| 70 | + |
| 71 | + time.sleep(5) |
| 72 | + wait_time += 5 |
| 73 | + else: |
| 74 | + print(result) |
| 75 | + break |
| 76 | + print("File parser demo completed.") |
| 77 | + |
| 78 | + |
| 79 | +if __name__ == "__main__": |
| 80 | + print("=== File Parsing Quick Demo ===\n") |
| 81 | + file_parser_complete_example() |
0 commit comments