client.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137
  1. import requests
  2. import argparse
  3. import os
  4. import sys
  5. import time
  6. import numpy as np
  7. # Define the server URL
  8. SERVER_URL = "http://192.168.9.51:8888"
  9. def save_results(results: dict, output_dir: str):
  10. """Saves the numpy arrays received from the server."""
  11. if not results or "segment" not in results or "pred" not in results:
  12. print("Error: The server response did not contain the expected 'segment' or 'pred' arrays.", file=sys.stderr)
  13. return
  14. if not os.path.exists(output_dir):
  15. os.makedirs(output_dir)
  16. print(f"Created output directory: {output_dir}")
  17. try:
  18. # Convert lists back to numpy arrays
  19. segment_array = np.array(results['segment'])
  20. pred_array = np.array(results['pred'])
  21. # Save the .npy files
  22. segment_path = os.path.join(output_dir, 'segment.npy')
  23. pred_path = os.path.join(output_dir, 'pred.npy')
  24. np.save(segment_path, segment_array)
  25. print(f"Successfully saved: {segment_path}")
  26. np.save(pred_path, pred_array)
  27. print(f"Successfully saved: {pred_path}")
  28. except Exception as e:
  29. print(f"An error occurred while saving the result arrays: {e}", file=sys.stderr)
  30. def poll_status(task_id: str, output_dir: str):
  31. """Polls the server for the task status and retrieves the results."""
  32. status_url = f"{SERVER_URL}/status/{task_id}"
  33. print(f"\nPolling for status updates...")
  34. while True:
  35. try:
  36. response = requests.get(status_url, timeout=10)
  37. response.raise_for_status()
  38. data = response.json()
  39. status = data.get("status")
  40. progress = data.get("progress")
  41. # Display progress on a single line
  42. sys.stdout.write(f"\rStatus: {status} | Progress: {progress} ")
  43. sys.stdout.flush()
  44. if status == "completed":
  45. print("\n\nTask complete. Retrieving results...")
  46. save_results(data.get("results"), output_dir)
  47. break
  48. elif status == "error":
  49. print(f"\n\nTask failed on the server with an error: {progress}", file=sys.stderr)
  50. break
  51. time.sleep(3)
  52. except requests.exceptions.RequestException as e:
  53. print(f"\nAn error occurred while polling for status: {e}", file=sys.stderr)
  54. break
  55. except KeyboardInterrupt:
  56. print("\nPolling stopped by user.")
  57. break
  58. def upload_and_start_task(zip_path: str):
  59. """Uploads the scene zip file to the server to start the processing task."""
  60. start_url = f"{SERVER_URL}/run_test/"
  61. if not os.path.exists(zip_path) or not zip_path.endswith('.zip'):
  62. print(f"Error: The specified file does not exist or is not a .zip file: '{zip_path}'", file=sys.stderr)
  63. return None
  64. print(f"Uploading {os.path.basename(zip_path)} to the server to start processing...")
  65. try:
  66. with open(zip_path, 'rb') as f:
  67. files = {'file': (os.path.basename(zip_path), f, 'application/zip')}
  68. response = requests.post(start_url, files=files, timeout=60) # Increased timeout for upload
  69. response.raise_for_status()
  70. task_id = response.json().get("task_id")
  71. if task_id:
  72. print(f"File uploaded successfully. Task started with ID: {task_id}")
  73. return task_id
  74. else:
  75. print("Error: The server did not return a valid task ID.", file=sys.stderr)
  76. return None
  77. except requests.exceptions.ConnectionError:
  78. print(f"\nConnection Error: Could not connect to the server at {SERVER_URL}.", file=sys.stderr)
  79. print("Please ensure 'server.py' is running and accessible.", file=sys.stderr)
  80. return None
  81. except requests.exceptions.RequestException as e:
  82. print(f"\nAn error occurred during file upload: {e}", file=sys.stderr)
  83. return None
  84. if __name__ == "__main__":
  85. parser = argparse.ArgumentParser(
  86. description="输入单个场景文件夹用于向服务器传输数据",
  87. formatter_class=argparse.RawTextHelpFormatter
  88. )
  89. parser.add_argument(
  90. '-i',
  91. '--input_folder',
  92. type=str,
  93. required=True,
  94. help='指定输入场景的路径。'
  95. )
  96. args = parser.parse_args()
  97. scene_folder = args.input_folder
  98. DEBUG_ZIP_FILE = os.path.join(scene_folder, "scene.zip")
  99. DEBUG_OUTPUT_DIR = os.path.join(scene_folder, "output")
  100. if not os.path.exists(DEBUG_OUTPUT_DIR):
  101. os.makedirs(DEBUG_OUTPUT_DIR)
  102. zip_file_path = DEBUG_ZIP_FILE
  103. output_directory = DEBUG_OUTPUT_DIR
  104. print(f"DEBUG模式启用: 使用 ZIP文件: {zip_file_path}, 输出目录: {output_directory}")
  105. task_id = upload_and_start_task(zip_file_path)
  106. if task_id:
  107. poll_status(task_id, output_directory)