Repository navigation
Expand file tree
/
Copy pathtest_api.py
More file actions
executable file
·210 lines (171 loc) · 6.01 KB
/
Copy pathtest_api.py
File metadata and controls
executable file
·210 lines (171 loc) · 6.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#!/usr/bin/env python3
"""Simple test client for ML-Sharp SBS API."""
import argparse
import time
import sys
from pathlib import Path
import requests
def create_job(url: str, video_path: str, **kwargs) -> str:
"""Create a new video conversion job."""
print(f"Creating job for: {video_path}")
with open(video_path, "rb") as f:
files = {"video": f}
response = requests.post(f"{url}/jobs/create", files=files, data=kwargs)
if response.status_code != 202:
print(f"Error creating job: {response.status_code}")
print(response.text)
sys.exit(1)
data = response.json()
job_id = data["job_id"]
print(f"Job created: {job_id}")
print(f"Status: {data['status']}")
return job_id
def poll_status(url: str, job_id: str, interval: int = 5):
"""Poll job status until completion."""
print(f"\nPolling job status (every {interval}s)...")
print("-" * 60)
while True:
response = requests.get(f"{url}/jobs/{job_id}")
if response.status_code != 200:
print(f"Error getting status: {response.status_code}")
break
data = response.json()
status = data["status"]
progress = data["progress"] * 100
stage = data["stage"]
frames = data["processed_frames"]
total = data["total_frames"]
print(f"\r[{stage}] {progress:.1f}% - Frame {frames}/{total}", end="", flush=True)
if status == "completed":
print(f"\n\nJob completed successfully!")
print(f"Output files: {data['output_files']}")
return data["output_files"]
elif status == "failed":
print(f"\n\nJob failed: {data.get('error_message', 'Unknown error')}")
return None
elif status == "cancelled":
print(f"\n\nJob was cancelled")
return None
time.sleep(interval)
def download_file(url: str, filename: str, output_dir: Path = None):
"""Download an output file."""
output_path = (output_dir or Path(".")) / filename
print(f"\nDownloading to: {output_path}")
response = requests.get(f"{url}/download/{filename}", stream=True)
if response.status_code != 200:
print(f"Error downloading: {response.status_code}")
return False
with open(output_path, "wb") as f:
for chunk in response.iter_content(chunk_size=8192):
f.write(chunk)
print(f"Downloaded: {output_path} ({output_path.stat().st_size / 1024 / 1024:.1f} MB)")
return True
def list_jobs(url: str):
"""List all jobs."""
response = requests.get(f"{url}/jobs")
if response.status_code != 200:
print(f"Error: {response.status_code}")
return
data = response.json()
print(f"\nJobs (total: {data['total']})")
print("-" * 60)
print(f"Queued: {data['queued']} | Running: {data['running']} | Completed: {data['completed']} | Failed: {data['failed']}")
for job in data["jobs"][:10]: # Show first 10
print(f"\n[{job['status']}] {job['job_id'][:8]}... | {job['input_filename']}")
if job['status'] == 'running':
print(f" Progress: {job['progress']:.1%} | Stage: {job['stage']}")
def get_status(url: str):
"""Get server status."""
response = requests.get(f"{url}/status")
if response.status_code != 200:
print(f"Error: {response.status_code}")
return
data = response.json()
print("\nServer Status:")
print("-" * 60)
print(f"Status: {data['status']}")
print(f"Device: {data['device']}")
print(f"Model Loaded: {data['model_loaded']}")
print(f"CUDA Available: {data['cuda_available']}")
print(f"Active Jobs: {data['active_jobs']}")
print(f"Total Processed: {data['total_jobs_processed']}")
def main():
parser = argparse.ArgumentParser(
description="Test client for ML-Sharp SBS API"
)
parser.add_argument(
"--url",
default="http://localhost:8000",
help="API server URL"
)
parser.add_argument(
"action",
choices=["status", "jobs", "convert", "download"],
help="Action to perform"
)
parser.add_argument(
"--video",
help="Video file path (for convert action)"
)
parser.add_argument(
"--output",
type=Path,
default=Path("."),
help="Output directory (for download action)"
)
parser.add_argument(
"--poll-interval",
type=int,
default=5,
help="Status poll interval in seconds"
)
parser.add_argument(
"--precision",
choices=["float16", "float32"],
default="float32",
help="Computation precision"
)
parser.add_argument(
"--batch-size",
type=int,
default=1,
help="Batch size (1-8)"
)
parser.add_argument(
"--frame-skip",
type=int,
default=1,
help="Process every Nth frame"
)
args = parser.parse_args()
# Health check
try:
requests.get(f"{args.url}/health", timeout=2)
except requests.exceptions.RequestException:
print(f"Cannot connect to {args.url}")
sys.exit(1)
if args.action == "status":
get_status(args.url)
elif args.action == "jobs":
list_jobs(args.url)
elif args.action == "convert":
if not args.video or not Path(args.video).exists():
print(f"Video file not found: {args.video}")
sys.exit(1)
job_id = create_job(
args.url,
args.video,
precision=args.precision,
batch_size=args.batch_size,
frame_skip=args.frame_skip
)
output_files = poll_status(args.url, job_id, args.poll_interval)
if output_files:
print(f"\nTo download, run: python test_api.py download --url {args.url} {output_files[0]}")
elif args.action == "download":
if not args.video:
print("Please specify filename to download with --video")
sys.exit(1)
download_file(args.url, args.video, args.output)
if __name__ == "__main__":
main()