Spaces:
Sleeping
Sleeping
Download client.py from Vignesh5656/transformation-api: direct link, hf CLI and curl.
- Browser
- Download file 14.3 kB
-
https://huggingface.co/spaces/Vignesh5656/transformation-api/resolve/main/client.py
- Command line
-
hf download hf://spaces/Vignesh5656/transformation-api/client.py
-
curl -L -o client.py https://huggingface.co/spaces/Vignesh5656/transformation-api/resolve/main/client.py
14.3 kB
| #!/usr/bin/env python3 | |
| """ | |
| WebSocket Client for FastAPI Processing Simulator | |
| This client provides both interactive and automated testing capabilities | |
| for the FastAPI WebSocket endpoint and download functionality. | |
| """ | |
| import asyncio | |
| import websockets | |
| import json | |
| import argparse | |
| import sys | |
| import requests | |
| import os | |
| from datetime import datetime | |
| from typing import Optional, Dict, Any | |
| class ProcessingClient: | |
| def __init__(self, url: str = "ws://10.170.2.156:8000/ws"): | |
| self.url = url | |
| self.websocket = None | |
| # Extract base URL for HTTP requests (download endpoint) | |
| self.base_url = url.replace("ws://", "http://").replace("/ws", "") | |
| async def connect(self) -> bool: | |
| """Connect to the WebSocket server""" | |
| try: | |
| self.websocket = await websockets.connect(self.url) | |
| print(f"β Connected to {self.url}") | |
| return True | |
| except Exception as e: | |
| print(f"β Failed to connect to {self.url}: {e}") | |
| return False | |
| async def disconnect(self): | |
| """Disconnect from the WebSocket server""" | |
| if self.websocket: | |
| await self.websocket.close() | |
| print("π Disconnected from server") | |
| async def send_processing_request(self, foldername: str, environment: str) -> Optional[str]: | |
| """ | |
| Send a processing request and return the request ID | |
| Args: | |
| foldername: Name of the folder to process | |
| environment: Environment name (dev, staging, production, etc.) | |
| Returns: | |
| Request ID if successful, None otherwise | |
| """ | |
| if not self.websocket: | |
| print("β Not connected to server") | |
| return None | |
| request = { | |
| "foldername": foldername, | |
| "environment": environment | |
| } | |
| try: | |
| await self.websocket.send(json.dumps(request)) | |
| print(f"π€ Sent request: {request}") | |
| return await self._listen_for_messages() | |
| except Exception as e: | |
| print(f"β Error sending request: {e}") | |
| return None | |
| async def _listen_for_messages(self) -> Optional[str]: | |
| """Listen for messages from the server and display them""" | |
| request_id = None | |
| try: | |
| async for message in self.websocket: | |
| data = json.loads(message) | |
| timestamp = datetime.now().strftime("%H:%M:%S") | |
| # Handle different message types | |
| if "error" in data: | |
| print(f"β [{timestamp}] Error: {data['error']}") | |
| if "expected_format" in data: | |
| print(f" Expected format: {data['expected_format']}") | |
| elif data.get("type") == "progress": | |
| progress = data.get("progress_percentage", 0) | |
| message = data.get("message", "") | |
| print(f"β³ [{timestamp}] Progress {progress}%: {message}") | |
| request_id = data.get("request_id", request_id) | |
| elif data.get("type") == "completion": | |
| print(f"β [{timestamp}] {data.get('message', 'Completed')}") | |
| stats = data.get("stats", {}) | |
| print("\nπ Final Statistics:") | |
| print(f" Status: {stats.get('status')}") | |
| print(f" Number of Records: {stats.get('number_of_records'):,}") | |
| print(f" Request ID: {stats.get('request_id')}") | |
| print(f" Record Count: {stats.get('record_count'):,}") | |
| request_id = stats.get("request_id", request_id) | |
| break | |
| else: | |
| # Handle acknowledgment and other messages | |
| message = data.get("message", "") | |
| if message: | |
| print(f"π [{timestamp}] {message}") | |
| request_id = data.get("request_id", request_id) | |
| except websockets.exceptions.ConnectionClosed: | |
| print("π Connection closed by server") | |
| except Exception as e: | |
| print(f"β Error receiving messages: {e}") | |
| return request_id | |
| def download_file(self, request_id: str, save_path: str = None) -> bool: | |
| """ | |
| Download the TEST.pdf file using the request ID | |
| Args: | |
| request_id: The request ID to use for the download | |
| save_path: Optional path to save the file (default: current directory) | |
| Returns: | |
| True if download successful, False otherwise | |
| """ | |
| try: | |
| download_url = f"{self.base_url}/{request_id}/download" | |
| print(f"π₯ Downloading from: {download_url}") | |
| response = requests.get(download_url) | |
| if response.status_code == 200: | |
| # Determine save path | |
| if save_path is None: | |
| save_path = f"downloaded_TEST_{request_id[:8]}.pdf" | |
| # Save the file | |
| with open(save_path, 'wb') as f: | |
| f.write(response.content) | |
| file_size = len(response.content) | |
| print(f"β File downloaded successfully!") | |
| print(f" π Saved as: {save_path}") | |
| print(f" π Size: {file_size:,} bytes") | |
| print(f" π Request ID: {response.headers.get('X-Request-ID', 'N/A')}") | |
| return True | |
| else: | |
| print(f"β Download failed with status {response.status_code}") | |
| print(f" Response: {response.text}") | |
| return False | |
| except Exception as e: | |
| print(f"β Error downloading file: {e}") | |
| return False | |
| async def interactive_mode(): | |
| """Run the client in interactive mode""" | |
| print("π FastAPI Processing Simulator - Interactive Client") | |
| print("=" * 60) | |
| # Get server URL | |
| url = input("Enter WebSocket URL (default: ws://10.170.2.156:8000/ws): ").strip() | |
| if not url: | |
| url = "ws://10.170.2.156:8000/ws" | |
| client = ProcessingClient(url) | |
| # Connect to server | |
| if not await client.connect(): | |
| return | |
| try: | |
| while True: | |
| print("\n" + "=" * 60) | |
| print("Options:") | |
| print("1. Send processing request") | |
| print("2. Download file with request ID") | |
| print("3. Send request and download file") | |
| print("4. Change server URL") | |
| print("5. Quit") | |
| choice = input("\nSelect option (1-5): ").strip() | |
| if choice == "1": | |
| foldername = input("Enter folder name: ").strip() | |
| if not foldername: | |
| print("β Folder name cannot be empty") | |
| continue | |
| environment = input("Enter environment (dev/staging/production): ").strip() | |
| if not environment: | |
| print("β Environment cannot be empty") | |
| continue | |
| print(f"\nπ Processing request for '{foldername}' in '{environment}'...") | |
| request_id = await client.send_processing_request(foldername, environment) | |
| if request_id: | |
| print(f"\nβ Request completed with ID: {request_id}") | |
| else: | |
| print("\nβ Request failed") | |
| elif choice == "2": | |
| request_id = input("Enter request ID for download: ").strip() | |
| if not request_id: | |
| print("β Request ID cannot be empty") | |
| continue | |
| save_path = input("Enter save path (or press Enter for default): ").strip() | |
| if not save_path: | |
| save_path = None | |
| print(f"\nπ₯ Downloading file for request ID: {request_id}") | |
| success = client.download_file(request_id, save_path) | |
| if success: | |
| print("β Download completed successfully!") | |
| else: | |
| print("β Download failed!") | |
| elif choice == "3": | |
| foldername = input("Enter folder name: ").strip() | |
| if not foldername: | |
| print("β Folder name cannot be empty") | |
| continue | |
| environment = input("Enter environment (dev/staging/production): ").strip() | |
| if not environment: | |
| print("β Environment cannot be empty") | |
| continue | |
| print(f"\nπ Processing request for '{foldername}' in '{environment}'...") | |
| request_id = await client.send_processing_request(foldername, environment) | |
| if request_id: | |
| print(f"\nβ Request completed with ID: {request_id}") | |
| # Ask if user wants to download | |
| download_choice = input("\nDownload the file now? (y/n): ").strip().lower() | |
| if download_choice in ['y', 'yes']: | |
| save_path = input("Enter save path (or press Enter for default): ").strip() | |
| if not save_path: | |
| save_path = None | |
| print(f"\nπ₯ Downloading file...") | |
| success = client.download_file(request_id, save_path) | |
| if success: | |
| print("β Download completed successfully!") | |
| else: | |
| print("β Download failed!") | |
| else: | |
| print("\nβ Request failed") | |
| elif choice == "4": | |
| await client.disconnect() | |
| url = input("Enter new WebSocket URL: ").strip() | |
| client = ProcessingClient(url) | |
| if not await client.connect(): | |
| break | |
| elif choice == "5": | |
| break | |
| else: | |
| print("β Invalid option. Please select 1-5.") | |
| except KeyboardInterrupt: | |
| print("\n\nπ Goodbye!") | |
| finally: | |
| await client.disconnect() | |
| async def automated_test(url: str, foldername: str, environment: str): | |
| """Run automated test with specified parameters""" | |
| print(f"π€ Running automated test...") | |
| print(f" URL: {url}") | |
| print(f" Folder: {foldername}") | |
| print(f" Environment: {environment}") | |
| print("=" * 60) | |
| client = ProcessingClient(url) | |
| if await client.connect(): | |
| request_id = await client.send_processing_request(foldername, environment) | |
| await client.disconnect() | |
| if request_id: | |
| print(f"\nβ Test completed successfully! Request ID: {request_id}") | |
| return True | |
| else: | |
| print("\nβ Test failed!") | |
| return False | |
| return False | |
| async def stress_test(url: str, num_requests: int = 5): | |
| """Run multiple concurrent requests to test server performance""" | |
| print(f"β‘ Running stress test with {num_requests} concurrent requests...") | |
| print("=" * 60) | |
| async def single_request(request_num: int): | |
| client = ProcessingClient(url) | |
| if await client.connect(): | |
| foldername = f"test-folder-{request_num}" | |
| environment = f"test-env-{request_num}" | |
| print(f"π Starting request {request_num}") | |
| request_id = await client.send_processing_request(foldername, environment) | |
| await client.disconnect() | |
| if request_id: | |
| print(f"β Request {request_num} completed: {request_id}") | |
| return True | |
| else: | |
| print(f"β Request {request_num} failed") | |
| return False | |
| return False | |
| # Run concurrent requests | |
| tasks = [single_request(i + 1) for i in range(num_requests)] | |
| results = await asyncio.gather(*tasks, return_exceptions=True) | |
| successful = sum(1 for r in results if r is True) | |
| print(f"\nπ Stress test results: {successful}/{num_requests} requests successful") | |
| return successful == num_requests | |
| def main(): | |
| """Main entry point""" | |
| parser = argparse.ArgumentParser(description="WebSocket Client for FastAPI Processing Simulator") | |
| parser.add_argument("--url", default="ws://10.170.2.156:8000/ws", help="WebSocket server URL") | |
| parser.add_argument("--folder", help="Folder name for automated test") | |
| parser.add_argument("--env", help="Environment for automated test") | |
| parser.add_argument("--stress", type=int, metavar="N", help="Run stress test with N concurrent requests") | |
| parser.add_argument("--download", help="Download file using request ID") | |
| parser.add_argument("--save-path", help="Path to save downloaded file") | |
| parser.add_argument("--interactive", action="store_true", help="Run in interactive mode (default)") | |
| args = parser.parse_args() | |
| # Determine mode | |
| if args.download: | |
| # Download mode | |
| client = ProcessingClient(args.url) | |
| success = client.download_file(args.download, args.save_path) | |
| sys.exit(0 if success else 1) | |
| elif args.stress: | |
| # Stress test mode | |
| success = asyncio.run(stress_test(args.url, args.stress)) | |
| sys.exit(0 if success else 1) | |
| elif args.folder and args.env: | |
| # Automated test mode | |
| success = asyncio.run(automated_test(args.url, args.folder, args.env)) | |
| sys.exit(0 if success else 1) | |
| else: | |
| # Interactive mode (default) | |
| asyncio.run(interactive_mode()) | |
| if __name__ == "__main__": | |
| main() |