File size: 14,931 Bytes
86698c3
362ac98
 
d7e086e
362ac98
 
0529778
 
362ac98
86698c3
362ac98
 
 
 
 
 
 
 
86698c3
 
 
 
 
 
 
 
 
362ac98
 
 
 
 
 
 
 
 
 
 
 
 
d7e086e
362ac98
 
 
 
 
d7e086e
362ac98
 
 
 
 
 
86698c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
362ac98
 
 
 
 
 
86698c3
 
362ac98
 
 
 
 
 
 
86698c3
 
362ac98
 
 
 
 
86698c3
 
362ac98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86698c3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0529778
 
c3de2e0
 
 
0529778
c3de2e0
0529778
 
 
 
 
 
c3de2e0
 
 
 
 
 
 
 
 
 
 
 
 
 
0529778
c3de2e0
 
0529778
c3de2e0
 
 
 
 
 
 
 
 
 
0529778
 
 
c3de2e0
86698c3
c3de2e0
 
86698c3
362ac98
86698c3
 
 
 
0529778
 
 
c3de2e0
 
 
 
 
 
 
 
 
0529778
 
86698c3
 
 
 
 
 
c3de2e0
86698c3
 
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import os, re, json, queue, threading, subprocess, multiprocessing, sys, gradio as gr

from collections.abc import Callable
from lib.lang import legends

class SubprocessPipe:
    # seconds between the lines send() prints while a worker reply is still due
    busy_notice_seconds = 60

    def __init__(self, cmd:list[str], is_gui_process:bool, total_duration:float, msg:str=legends['msg_processing'], on_progress:Callable[[float], None]|None=None, keep_alive:bool=False, env:dict|None=None)->None:
        self.cmd = cmd
        self.is_gui_process = is_gui_process
        self.total_duration = total_duration
        self.msg = msg
        self.process = None
        self._stop_requested = False
        self.on_progress = on_progress
        self.progress_bar = False
        # keep_alive: the child is a persistent worker speaking one JSON object per
        # line (requests on its stdin, replies on its stdout, logs on its stderr).
        # result is True once the worker announced {"ready": true}, then send() is
        # the request/reply channel until stop(). Without it nothing changes.
        self.keep_alive = keep_alive
        self.env = env
        self.ready_info = {}
        self._ready = False
        self._lock = threading.Lock()
        if self.is_gui_process:
            self.progress_bar = gr.Progress(track_tqdm=False)
        self.result = self._run_process()
        
    def _emit_progress(self, percent:float)->None:
        if self.on_progress is not None:
            self.on_progress(percent)
        elif self.progress_bar:
            self.progress_bar(percent / 100.0, desc=self.msg)
        sys.stdout.write(f"\r{self.msg} - {percent:.1f}%")
        sys.stdout.flush()

    def _on_complete(self)->None:
        msg = '\n' + legends['msg_step_completed'].format(step=self.msg)
        print(msg)
        if self.progress_bar:
            self.progress_bar(1.0, desc=msg)

    def _on_error(self, err:Exception)->None:
        error = legends['error_step_failed'].format(step=self.msg, e=err)
        print(error)
        if self.progress_bar:
            self.progress_bar(0.0, desc=error)

    def _run_process(self)->bool:
        try:
            if self.keep_alive:
                self.process = subprocess.Popen(
                    self.cmd,
                    stdin=subprocess.PIPE,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    env=self.env
                )
                tqdm_re = re.compile(rb'(\d{1,3})%\|')
                progress_queue = queue.Queue()
                ready_queue = queue.Queue()

                def read_stderr():
                    # lives as long as the worker: its logs always reach the terminal,
                    # tqdm percents (model downloads) only feed the bar until ready.
                    buffer = b''
                    try:
                        while True:
                            chunk = self.process.stderr.read1(4096)
                            if not chunk:
                                break
                            try:
                                sys.stderr.write(chunk.decode('utf-8', errors='replace'))
                                sys.stderr.flush()
                            except Exception:
                                pass
                            if self._ready:
                                buffer = b''
                                continue
                            buffer += chunk
                            parts = re.split(rb'[\r\n]', buffer)
                            buffer = parts[-1]
                            for part in parts[:-1]:
                                match = tqdm_re.search(part)
                                if match:
                                    progress_queue.put(min(float(match.group(1)), 100.0))
                    except Exception:
                        pass

                def read_ready():
                    try:
                        ready_queue.put(self.process.stdout.readline())
                    except Exception:
                        ready_queue.put(b'')

                threading.Thread(target=read_stderr, daemon=True).start()
                threading.Thread(target=read_ready, daemon=True).start()
                last_percent = 0.0
                line = None
                while line is None:
                    try:
                        line = ready_queue.get(timeout=0.1)
                    except queue.Empty:
                        pass
                    while not progress_queue.empty():
                        percent = progress_queue.get_nowait()
                        if abs(percent - last_percent) >= 0.5:
                            self._emit_progress(percent)
                            last_percent = percent
                    if line is None and self._stop_requested:
                        return False
                self._ready = True
                try:
                    self.ready_info = json.loads(line) if line else {}
                except Exception:
                    self.ready_info = {'error': line.decode('utf-8', errors='replace').strip()}
                if self.ready_info.get('ready'):
                    self._on_complete()
                    return True
                if not line:
                    try:
                        self.process.wait(timeout=10)
                    except Exception:
                        pass
                    self.ready_info['error'] = legends['error_worker_exited'].format(code=self.process.poll())
                self._on_error(self.ready_info.get('error'))
                self.stop()
                return False
            is_ffmpeg = "ffmpeg" in os.path.basename(self.cmd[0])
            if is_ffmpeg:
                self.process = subprocess.Popen(
                    self.cmd,
                    stdout=subprocess.DEVNULL,
                    stderr=subprocess.PIPE,
                    bufsize=0,
                    env=self.env
                )
            else:
                if self.progress_bar:
                    self.process = subprocess.Popen(
                        self.cmd,
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT,
                        bufsize=0,
                        env=self.env
                    )
                else:
                    self.process = subprocess.Popen(
                        self.cmd,
                        stdout=None,
                        stderr=None,
                        env=self.env
                    )
            if is_ffmpeg:
                time_pattern = re.compile(rb'out_time_ms=(\d+)')
                last_percent = 0.0
                stderr_queue = queue.Queue()

                def read_stderr():
                    try:
                        buffer = b''
                        while True:
                            chunk = self.process.stderr.read(4096)
                            if not chunk:
                                break
                            buffer += chunk
                            while b'\n' in buffer:
                                line, buffer = buffer.split(b'\n', 1)
                                stderr_queue.put(line)
                    except Exception:
                        pass
                    finally:
                        stderr_queue.put(None)

                stderr_thread = threading.Thread(target=read_stderr, daemon=True)
                stderr_thread.start()

                while True:
                    try:
                        line = stderr_queue.get(timeout=0.1)
                    except queue.Empty:
                        if self.process.poll() is not None:
                            break
                        continue

                    if line is None:  # sentinel = stderr closed
                        break
                    match = time_pattern.search(line)
                    if match and self.total_duration > 0:
                        current_time = int(match.group(1)) / 1_000_000
                        percent = min((current_time / self.total_duration) * 100, 100)
                        if abs(percent - last_percent) >= 0.5:
                            self._emit_progress(percent)
                            last_percent = percent
                    elif b'progress=end' in line:
                        self._emit_progress(100.0)
                stderr_thread.join()
            else:
                if self.progress_bar:
                    tqdm_re = re.compile(rb'(\d{1,3})%\|')
                    buffer = b''
                    last_percent = 0.0
                    while True:
                        chunk = self.process.stdout.read(1024)
                        if not chunk:
                            break
                        buffer += chunk
                        if b'\r' in buffer:
                            parts = buffer.split(b'\r')
                            buffer = parts[-1]
                            for part in parts[:-1]:
                                match = tqdm_re.search(part)
                                if match:
                                    percent = min(float(match.group(1)), 100.0)
                                    if percent - last_percent >= 0.5:
                                        self._emit_progress(percent)
                                        last_percent = percent
            self.process.wait()
            if self._stop_requested:
                return False
            elif self.process.returncode==0:
                self._on_complete()
                return True
            else:
                self._on_error(self.process.returncode)
                return False
        except Exception as e:
            self._on_error(e)
            return False

    def stop(self)->bool:
        self._stop_requested=True
        if self.process and self.process.poll() is None:
            if self.keep_alive:
                # EOF on stdin is the worker's exit signal: it returns from its loop
                # and the OS reclaims its VRAM. terminate/kill only if it hangs.
                try:
                    self.process.stdin.close()
                except Exception:
                    pass
                try:
                    self.process.wait(timeout=15)
                except Exception:
                    pass
            if self.process.poll() is None:
                try:
                    self.process.terminate()
                except Exception:
                    pass
                if self.keep_alive:
                    try:
                        self.process.wait(timeout=5)
                    except Exception:
                        try:
                            self.process.kill()
                            self.process.wait(timeout=5)
                        except Exception:
                            pass
        return False

    def _busy_notices(self, done:threading.Event)->None:
        # a reply can take minutes (a long sentence on CPU): every busy_notice_seconds tell the user the worker is still
        # on it and how many cores it keeps busy, so a slow worker (cores busy) and a stuck one (idle) read apart in a log.
        # The cores of its whole process tree: the audio.cpp worker only waits on HTTP while its audiocpp_server child
        # does the work, so the worker alone always read 0.0
        import time
        procs = {}
        try:
            import psutil
            worker = psutil.Process(self.process.pid)
            total = psutil.cpu_count() or '?'
        except Exception:
            worker, total = None, '?'

        def tree_cores()->str:
            # cpu_percent(None) is the share since the previous call on the same Process object: one object per pid,
            # kept from one notice to the next (a child seen for the first time reads 0.0, then its real share)
            nonlocal worker
            try:
                members = [worker] + worker.children(recursive=True)
            except Exception:
                worker = None
                return '?'
            usage = 0.0
            alive = set()
            for member in members:
                proc = procs.setdefault(member.pid, member)
                try:
                    usage += proc.cpu_percent(None)
                    alive.add(member.pid)
                except Exception:
                    pass
            for pid in set(procs) - alive:
                del procs[pid]
            return f'{usage / 100:.1f}'

        if worker is not None:
            tree_cores()
        start = time.monotonic()
        while not done.wait(self.busy_notice_seconds):
            cores = tree_cores() if worker is not None else '?'
            msg = legends['msg_worker_busy'].format(seconds=int(time.monotonic() - start), cores=cores, total=total)
            print(msg)

    def send(self, request:dict, on_progress:Callable[[float], None]|None=None)->dict:
        # one request line out, one reply line back. The lock serializes callers
        # (one worker = one model in memory), so threads take turns. A long request may
        # be preceded by {"progress": 0..1} lines (no "ok"): to on_progress, else the bar.
        with self._lock:
            try:
                if not self.keep_alive or self.process is None or self.process.poll() is not None:
                    return {'ok': False, 'error': legends['error_worker_exited'].format(code=self.process.poll() if self.process else None)}
                self.process.stdin.write((json.dumps(request) + '\n').encode('utf-8'))
                self.process.stdin.flush()
                done = threading.Event()
                threading.Thread(target=self._busy_notices, args=(done,), daemon=True).start()
                try:
                    while True:
                        line = self.process.stdout.readline()
                        reply = json.loads(line) if line else None
                        if not (isinstance(reply, dict) and 'progress' in reply and 'ok' not in reply):
                            break
                        if on_progress is not None:
                            on_progress(float(reply['progress']))
                        else:
                            self._emit_progress(float(reply['progress']) * 100.0)
                finally:
                    done.set()
                if not line:
                    try:
                        self.process.wait(timeout=10)
                    except Exception:
                        pass
                    return {'ok': False, 'error': legends['error_worker_exited'].format(code=self.process.poll())}
                return reply
            except Exception as e:
                return {'ok': False, 'error': legends['error_subprocess'].format(e=e)}