service.py 21.8 KB
Newer Older
gaclove's avatar
gaclove committed
1
2
import asyncio
import threading
PengGao's avatar
PengGao committed
3
4
5
6
7
8
9
10
11
12
13
import time
import uuid
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse

import httpx
import torch.multiprocessing as mp
from loguru import logger

from ..infer import init_runner
PengGao's avatar
PengGao committed
14
from ..utils.set_config import set_config
15
from .audio_utils import is_base64_audio, save_base64_audio
gaclove's avatar
gaclove committed
16
from .config import server_config
PengGao's avatar
PengGao committed
17
from .distributed_utils import create_distributed_worker
gaclove's avatar
gaclove committed
18
from .image_utils import is_base64_image, save_base64_image
PengGao's avatar
PengGao committed
19
from .schema import TaskRequest, TaskResponse
PengGao's avatar
PengGao committed
20
21
22
23
24
25
26
27
28
29
30

mp.set_start_method("spawn", force=True)


class FileService:
    def __init__(self, cache_dir: Path):
        self.cache_dir = cache_dir
        self.input_image_dir = cache_dir / "inputs" / "imgs"
        self.input_audio_dir = cache_dir / "inputs" / "audios"
        self.output_video_dir = cache_dir / "outputs"

gaclove's avatar
gaclove committed
31
32
33
34
35
36
37
        self._http_client = None
        self._client_lock = asyncio.Lock()

        self.max_retries = 3
        self.retry_delay = 1.0
        self.max_retry_delay = 10.0

PengGao's avatar
PengGao committed
38
39
40
41
42
43
44
        for directory in [
            self.input_image_dir,
            self.output_video_dir,
            self.input_audio_dir,
        ]:
            directory.mkdir(parents=True, exist_ok=True)

gaclove's avatar
gaclove committed
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
    async def _get_http_client(self) -> httpx.AsyncClient:
        """Get or create a persistent HTTP client with connection pooling."""
        async with self._client_lock:
            if self._http_client is None or self._http_client.is_closed:
                timeout = httpx.Timeout(
                    connect=10.0,
                    read=30.0,
                    write=10.0,
                    pool=5.0,
                )
                limits = httpx.Limits(max_keepalive_connections=5, max_connections=10, keepalive_expiry=30.0)
                self._http_client = httpx.AsyncClient(verify=False, timeout=timeout, limits=limits, follow_redirects=True)
            return self._http_client

    async def _download_with_retry(self, url: str, max_retries: Optional[int] = None) -> httpx.Response:
        """Download with exponential backoff retry logic."""
        if max_retries is None:
            max_retries = self.max_retries

        last_exception = None

        retry_delay = self.retry_delay

        for attempt in range(max_retries):
            try:
                client = await self._get_http_client()
                response = await client.get(url)

                if response.status_code == 200:
                    return response
                elif response.status_code >= 500:
                    logger.warning(f"Server error {response.status_code} for {url}, attempt {attempt + 1}/{max_retries}")
                    last_exception = httpx.HTTPStatusError(f"Server returned {response.status_code}", request=response.request, response=response)
                else:
                    raise httpx.HTTPStatusError(f"Client error {response.status_code}", request=response.request, response=response)

            except (httpx.ConnectError, httpx.TimeoutException, httpx.NetworkError) as e:
                logger.warning(f"Connection error for {url}, attempt {attempt + 1}/{max_retries}: {str(e)}")
                last_exception = e
            except httpx.HTTPStatusError as e:
                if e.response and e.response.status_code < 500:
                    raise
                last_exception = e
            except Exception as e:
                logger.error(f"Unexpected error downloading {url}: {str(e)}")
                last_exception = e

            if attempt < max_retries - 1:
                await asyncio.sleep(retry_delay)
                retry_delay = min(retry_delay * 2, self.max_retry_delay)

        error_msg = f"All {max_retries} connection attempts failed for {url}"
        if last_exception:
            error_msg += f": {str(last_exception)}"
        raise httpx.ConnectError(error_msg)

PengGao's avatar
PengGao committed
101
    async def download_image(self, image_url: str) -> Path:
gaclove's avatar
gaclove committed
102
        """Download image with retry logic and proper error handling."""
PengGao's avatar
PengGao committed
103
        try:
gaclove's avatar
gaclove committed
104
105
106
            parsed_url = urlparse(image_url)
            if not parsed_url.scheme or not parsed_url.netloc:
                raise ValueError(f"Invalid URL format: {image_url}")
PengGao's avatar
PengGao committed
107

gaclove's avatar
gaclove committed
108
            response = await self._download_with_retry(image_url)
PengGao's avatar
PengGao committed
109

gaclove's avatar
gaclove committed
110
            image_name = Path(parsed_url.path).name
PengGao's avatar
PengGao committed
111
            if not image_name:
gaclove's avatar
gaclove committed
112
                image_name = f"{uuid.uuid4()}.jpg"
PengGao's avatar
PengGao committed
113
114
115
116
117
118
119

            image_path = self.input_image_dir / image_name
            image_path.parent.mkdir(parents=True, exist_ok=True)

            with open(image_path, "wb") as f:
                f.write(response.content)

gaclove's avatar
gaclove committed
120
            logger.info(f"Successfully downloaded image from {image_url} to {image_path}")
PengGao's avatar
PengGao committed
121
            return image_path
gaclove's avatar
gaclove committed
122
123
124
125
126
127
128
129
130
131
132

        except httpx.ConnectError as e:
            logger.error(f"Connection error downloading image from {image_url}: {str(e)}")
            raise ValueError(f"Failed to connect to {image_url}: {str(e)}")
        except httpx.TimeoutException as e:
            logger.error(f"Timeout downloading image from {image_url}: {str(e)}")
            raise ValueError(f"Download timeout for {image_url}: {str(e)}")
        except httpx.HTTPStatusError as e:
            logger.error(f"HTTP error downloading image from {image_url}: {str(e)}")
            raise ValueError(f"HTTP error for {image_url}: {str(e)}")
        except ValueError as e:
PengGao's avatar
PengGao committed
133
            raise
gaclove's avatar
gaclove committed
134
135
136
        except Exception as e:
            logger.error(f"Unexpected error downloading image from {image_url}: {str(e)}")
            raise ValueError(f"Failed to download image from {image_url}: {str(e)}")
PengGao's avatar
PengGao committed
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
    async def download_audio(self, audio_url: str) -> Path:
        """Download audio with retry logic and proper error handling."""
        try:
            parsed_url = urlparse(audio_url)
            if not parsed_url.scheme or not parsed_url.netloc:
                raise ValueError(f"Invalid URL format: {audio_url}")

            response = await self._download_with_retry(audio_url)

            audio_name = Path(parsed_url.path).name
            if not audio_name:
                audio_name = f"{uuid.uuid4()}.mp3"

            audio_path = self.input_audio_dir / audio_name
            audio_path.parent.mkdir(parents=True, exist_ok=True)

            with open(audio_path, "wb") as f:
                f.write(response.content)

            logger.info(f"Successfully downloaded audio from {audio_url} to {audio_path}")
            return audio_path

        except httpx.ConnectError as e:
            logger.error(f"Connection error downloading audio from {audio_url}: {str(e)}")
            raise ValueError(f"Failed to connect to {audio_url}: {str(e)}")
        except httpx.TimeoutException as e:
            logger.error(f"Timeout downloading audio from {audio_url}: {str(e)}")
            raise ValueError(f"Download timeout for {audio_url}: {str(e)}")
        except httpx.HTTPStatusError as e:
            logger.error(f"HTTP error downloading audio from {audio_url}: {str(e)}")
            raise ValueError(f"HTTP error for {audio_url}: {str(e)}")
        except ValueError as e:
            raise
        except Exception as e:
            logger.error(f"Unexpected error downloading audio from {audio_url}: {str(e)}")
            raise ValueError(f"Failed to download audio from {audio_url}: {str(e)}")

PengGao's avatar
PengGao committed
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
    def save_uploaded_file(self, file_content: bytes, filename: str) -> Path:
        file_extension = Path(filename).suffix
        unique_filename = f"{uuid.uuid4()}{file_extension}"
        file_path = self.input_image_dir / unique_filename

        with open(file_path, "wb") as f:
            f.write(file_content)

        return file_path

    def get_output_path(self, save_video_path: str) -> Path:
        video_path = Path(save_video_path)
        if not video_path.is_absolute():
            return self.output_video_dir / save_video_path
        return video_path

gaclove's avatar
gaclove committed
191
192
193
194
195
196
197
    async def cleanup(self):
        """Cleanup resources including HTTP client."""
        async with self._client_lock:
            if self._http_client and not self._http_client.is_closed:
                await self._http_client.aclose()
                self._http_client = None

PengGao's avatar
PengGao committed
198

gaclove's avatar
gaclove committed
199
def _distributed_inference_worker(rank, world_size, master_addr, master_port, args, shared_data, task_event, result_event):
PengGao's avatar
PengGao committed
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
    task_data = None
    worker = None

    try:
        logger.info(f"Process {rank}/{world_size - 1} initializing distributed inference service...")

        worker = create_distributed_worker(rank, world_size, master_addr, master_port)
        if not worker.init():
            raise RuntimeError(f"Rank {rank} distributed environment initialization failed")

        config = set_config(args)
        logger.info(f"Rank {rank} config: {config}")

        runner = init_runner(config)
        logger.info(f"Process {rank}/{world_size - 1} distributed inference service initialization completed")

        while True:
217
218
            if not task_event.wait(timeout=1.0):
                continue
gaclove's avatar
gaclove committed
219

PengGao's avatar
PengGao committed
220
            if rank == 0:
gaclove's avatar
gaclove committed
221
222
223
224
225
226
227
                if shared_data.get("stop", False):
                    logger.info(f"Process {rank} received stop signal, exiting inference service")
                    worker.dist_manager.broadcast_task_data(None)
                    break

                task_data = shared_data.get("current_task")
                if task_data:
PengGao's avatar
PengGao committed
228
                    worker.dist_manager.broadcast_task_data(task_data)
229
230
231
232
233
                    shared_data["current_task"] = None
                    try:
                        task_event.clear()
                    except Exception:
                        pass
gaclove's avatar
gaclove committed
234
                else:
PengGao's avatar
PengGao committed
235
236
237
                    continue
            else:
                task_data = worker.dist_manager.broadcast_task_data()
gaclove's avatar
gaclove committed
238
                if task_data is None:
PengGao's avatar
PengGao committed
239
240
241
242
243
244
245
246
                    logger.info(f"Process {rank} received stop signal, exiting inference service")
                    break

            if task_data is not None:
                logger.info(f"Process {rank} received inference task: {task_data['task_id']}")

                try:
                    runner.set_inputs(task_data)  # type: ignore
247
                    runner.run_pipeline()
PengGao's avatar
PengGao committed
248

gaclove's avatar
gaclove committed
249
250
251
252
253
254
255
256
257
258
259
260
261
                    worker.dist_manager.barrier()

                    if rank == 0:
                        # Only rank 0 updates the result
                        shared_data["result"] = {
                            "task_id": task_data["task_id"],
                            "status": "success",
                            "save_video_path": task_data.get("video_path", task_data["save_video_path"]),  # Return original path for API
                            "message": "Inference completed",
                        }
                        result_event.set()
                        logger.info(f"Task {task_data['task_id']} success")

PengGao's avatar
PengGao committed
262
                except Exception as e:
263
                    logger.exception(f"Process {rank} error occurred while processing task: {str(e)}")
PengGao's avatar
PengGao committed
264

gaclove's avatar
gaclove committed
265
266
267
268
269
270
271
272
273
274
275
276
                    worker.dist_manager.barrier()

                    if rank == 0:
                        # Only rank 0 updates the result
                        shared_data["result"] = {
                            "task_id": task_data.get("task_id", "unknown"),
                            "status": "failed",
                            "error": str(e),
                            "message": f"Inference failed: {str(e)}",
                        }
                        result_event.set()
                        logger.info(f"Task {task_data.get('task_id', 'unknown')} failed")
PengGao's avatar
PengGao committed
277
278
279
280

    except KeyboardInterrupt:
        logger.info(f"Process {rank} received KeyboardInterrupt, gracefully exiting")
    except Exception as e:
gaclove's avatar
gaclove committed
281
        logger.exception(f"Distributed inference service process {rank} startup failed: {str(e)}")
PengGao's avatar
PengGao committed
282
        if rank == 0:
gaclove's avatar
gaclove committed
283
            shared_data["result"] = {
PengGao's avatar
PengGao committed
284
285
286
287
288
                "task_id": "startup",
                "status": "startup_failed",
                "error": str(e),
                "message": f"Inference service startup failed: {str(e)}",
            }
gaclove's avatar
gaclove committed
289
            result_event.set()
PengGao's avatar
PengGao committed
290
291
292
293
    finally:
        try:
            if worker:
                worker.cleanup()
gaclove's avatar
gaclove committed
294
295
        except Exception as e:
            logger.debug(f"Error cleaning up worker for rank {rank}: {e}")
PengGao's avatar
PengGao committed
296
297
298
299


class DistributedInferenceService:
    def __init__(self):
gaclove's avatar
gaclove committed
300
301
302
303
        self.manager = None
        self.shared_data = None
        self.task_event = None
        self.result_event = None
PengGao's avatar
PengGao committed
304
305
306
307
        self.processes = []
        self.is_running = False

    def start_distributed_inference(self, args) -> bool:
308
309
310
311
312
313
        if hasattr(args, "lora_path") and args.lora_path:
            args.lora_configs = [{"path": args.lora_path, "strength": getattr(args, "lora_strength", 1.0)}]
            delattr(args, "lora_path")
            if hasattr(args, "lora_strength"):
                delattr(args, "lora_strength")

314
        self.args = args
PengGao's avatar
PengGao committed
315
316
317
318
319
320
321
322
323
324
        if self.is_running:
            logger.warning("Distributed inference service is already running")
            return True

        nproc_per_node = args.nproc_per_node
        if nproc_per_node <= 0:
            logger.error("nproc_per_node must be greater than 0")
            return False

        try:
gaclove's avatar
gaclove committed
325
326
            master_addr = server_config.master_addr
            master_port = server_config.find_free_master_port()
PengGao's avatar
PengGao committed
327
328
            logger.info(f"Distributed inference service Master Addr: {master_addr}, Master Port: {master_port}")

gaclove's avatar
gaclove committed
329
330
331
332
333
334
335
336
337
338
            # Create shared data structures
            self.manager = mp.Manager()
            self.shared_data = self.manager.dict()
            self.task_event = self.manager.Event()
            self.result_event = self.manager.Event()

            # Initialize shared data
            self.shared_data["current_task"] = None
            self.shared_data["result"] = None
            self.shared_data["stop"] = False
PengGao's avatar
PengGao committed
339
340
341
342
343
344
345
346
347
348

            for rank in range(nproc_per_node):
                p = mp.Process(
                    target=_distributed_inference_worker,
                    args=(
                        rank,
                        nproc_per_node,
                        master_addr,
                        master_port,
                        args,
gaclove's avatar
gaclove committed
349
350
351
                        self.shared_data,
                        self.task_event,
                        self.result_event,
PengGao's avatar
PengGao committed
352
                    ),
gaclove's avatar
gaclove committed
353
                    daemon=False,  # Changed to False for proper cleanup
PengGao's avatar
PengGao committed
354
355
356
357
358
359
360
361
362
363
364
365
366
367
                )
                p.start()
                self.processes.append(p)

            self.is_running = True
            logger.info(f"Distributed inference service started successfully with {nproc_per_node} processes")
            return True

        except Exception as e:
            logger.exception(f"Error occurred while starting distributed inference service: {str(e)}")
            self.stop_distributed_inference()
            return False

    def stop_distributed_inference(self):
gaclove's avatar
gaclove committed
368
369
370
        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

PengGao's avatar
PengGao committed
371
372
373
374
375
376
        if not self.is_running:
            return

        try:
            logger.info(f"Stopping {len(self.processes)} distributed inference service processes...")

gaclove's avatar
gaclove committed
377
378
379
            if self.shared_data is not None:
                self.shared_data["stop"] = True
                self.task_event.set()
PengGao's avatar
PengGao committed
380
381
382
383
384
385
386
387

            for p in self.processes:
                try:
                    p.join(timeout=10)
                    if p.is_alive():
                        logger.warning(f"Process {p.pid} did not end within the specified time, forcing termination...")
                        p.terminate()
                        p.join(timeout=5)
gaclove's avatar
gaclove committed
388
389
                except Exception as e:
                    logger.warning(f"Error terminating process {p.pid}: {e}")
PengGao's avatar
PengGao committed
390
391
392
393
394
395
396
397

            logger.info("All distributed inference service processes have stopped")

        except Exception as e:
            logger.error(f"Error occurred while stopping distributed inference service: {str(e)}")
        finally:
            # Clean up resources
            self.processes = []
gaclove's avatar
gaclove committed
398
399
400
401
            self.manager = None
            self.shared_data = None
            self.task_event = None
            self.result_event = None
PengGao's avatar
PengGao committed
402
403
404
            self.is_running = False

    def submit_task(self, task_data: dict) -> bool:
gaclove's avatar
gaclove committed
405
406
407
408
        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

        if not self.is_running or not self.shared_data:
PengGao's avatar
PengGao committed
409
410
411
412
            logger.error("Distributed inference service is not started")
            return False

        try:
gaclove's avatar
gaclove committed
413
414
415
416
417
418
            self.result_event.clear()
            self.shared_data["result"] = None

            self.shared_data["current_task"] = task_data
            self.task_event.set()  # Signal workers

PengGao's avatar
PengGao committed
419
420
421
422
423
            return True
        except Exception as e:
            logger.error(f"Failed to submit task: {str(e)}")
            return False

gaclove's avatar
gaclove committed
424
425
426
427
428
429
430
    def wait_for_result(self, task_id: str, timeout: Optional[int] = None) -> Optional[dict]:
        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

        if timeout is None:
            timeout = server_config.task_timeout
        if not self.is_running or not self.shared_data:
PengGao's avatar
PengGao committed
431
432
            return None

gaclove's avatar
gaclove committed
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
        if self.result_event.wait(timeout=timeout):
            result = self.shared_data.get("result")
            if result and result.get("task_id") == task_id:
                self.shared_data["current_task"] = None
                self.task_event.clear()
                return result

        return None

    def wait_for_result_with_stop(self, task_id: str, stop_event: threading.Event, timeout: Optional[int] = None) -> Optional[dict]:
        if timeout is None:
            timeout = server_config.task_timeout

        if not self.is_running or not self.shared_data:
            return None

        assert self.task_event, "Task event is not initialized"
        assert self.result_event, "Result event is not initialized"

PengGao's avatar
PengGao committed
452
453
454
        start_time = time.time()

        while time.time() - start_time < timeout:
gaclove's avatar
gaclove committed
455
456
457
458
459
460
461
462
463
464
465
            if stop_event.is_set():
                logger.info(f"Task {task_id} stop event triggered during wait")
                self.shared_data["current_task"] = None
                self.task_event.clear()
                return None

            if self.result_event.wait(timeout=0.5):
                result = self.shared_data.get("result")
                if result and result.get("task_id") == task_id:
                    self.shared_data["current_task"] = None
                    self.task_event.clear()
PengGao's avatar
PengGao committed
466
467
468
469
                    return result

        return None

470
471
472
473
    def server_metadata(self):
        assert hasattr(self, "args"), "Distributed inference service has not been started. Call start_distributed_inference() first."
        return {"nproc_per_node": self.args.nproc_per_node, "model_cls": self.args.model_cls, "model_path": self.args.model_path}

PengGao's avatar
PengGao committed
474
475
476
477
478
479

class VideoGenerationService:
    def __init__(self, file_service: FileService, inference_service: DistributedInferenceService):
        self.file_service = file_service
        self.inference_service = inference_service

gaclove's avatar
gaclove committed
480
    async def generate_video_with_stop_event(self, message: TaskRequest, stop_event) -> Optional[TaskResponse]:
PengGao's avatar
PengGao committed
481
        try:
482
483
            task_data = {field: getattr(message, field) for field in message.model_fields_set if field != "task_id"}
            task_data["task_id"] = message.task_id
PengGao's avatar
PengGao committed
484

gaclove's avatar
gaclove committed
485
486
487
488
489
490
491
492
493
494
495
496
497
            if stop_event.is_set():
                logger.info(f"Task {message.task_id} cancelled before processing")
                return None

            if "image_path" in message.model_fields_set and message.image_path:
                if message.image_path.startswith("http"):
                    image_path = await self.file_service.download_image(message.image_path)
                    task_data["image_path"] = str(image_path)
                elif is_base64_image(message.image_path):
                    image_path = save_base64_image(message.image_path, str(self.file_service.input_image_dir))
                    task_data["image_path"] = str(image_path)
                else:
                    task_data["image_path"] = message.image_path
PengGao's avatar
PengGao committed
498

499
500
501
502
503
504
505
506
507
508
            if "audio_path" in message.model_fields_set and message.audio_path:
                if message.audio_path.startswith("http"):
                    audio_path = await self.file_service.download_audio(message.audio_path)
                    task_data["audio_path"] = str(audio_path)
                elif is_base64_audio(message.audio_path):
                    audio_path = save_base64_audio(message.audio_path, str(self.file_service.input_audio_dir))
                    task_data["audio_path"] = str(audio_path)
                else:
                    task_data["audio_path"] = message.audio_path

gaclove's avatar
gaclove committed
509
510
511
            actual_save_path = self.file_service.get_output_path(message.save_video_path)
            task_data["save_video_path"] = str(actual_save_path)
            task_data["video_path"] = message.save_video_path
PengGao's avatar
PengGao committed
512
513
514
515

            if not self.inference_service.submit_task(task_data):
                raise RuntimeError("Distributed inference service is not started")

gaclove's avatar
gaclove committed
516
            result = self.inference_service.wait_for_result_with_stop(message.task_id, stop_event, timeout=300)
PengGao's avatar
PengGao committed
517
518

            if result is None:
gaclove's avatar
gaclove committed
519
520
521
                if stop_event.is_set():
                    logger.info(f"Task {message.task_id} cancelled during processing")
                    return None
PengGao's avatar
PengGao committed
522
523
524
525
526
527
                raise RuntimeError("Task processing timeout")

            if result.get("status") == "success":
                return TaskResponse(
                    task_id=message.task_id,
                    task_status="completed",
gaclove's avatar
gaclove committed
528
                    save_video_path=message.save_video_path,  # Return original path
PengGao's avatar
PengGao committed
529
530
531
532
533
534
535
536
                )
            else:
                error_msg = result.get("error", "Inference failed")
                raise RuntimeError(error_msg)

        except Exception as e:
            logger.error(f"Task {message.task_id} processing failed: {str(e)}")
            raise