before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
source_wav=source_wav, target_wav=target_wav ) self.engine_zs.to(devices['CPU']['proc']) else: error...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
audio_part = self.engine_zs.voice_conversion( source_wav=source_wav, target_wav=target_wav ) self.engine_zs.to(devices['CPU']['proc'...
@@ -191,6 +192,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: ) else: with torch.autocast( + device_type=device,
lib/classes/tts_engines/tacotron.py
26
Python
1
suggestion
605
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
source_wav=source_wav, target_wav=target_wav ) self.engine_zs.to(devices['CPU']['proc']) else: error...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
audio_part = self.engine_zs.voice_conversion( source_wav=source_wav, target_wav=target_wav ) self.engine_zs.to(devices['CPU']['proc'...
@@ -163,6 +164,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: ) else: with torch.autocast( + device_type=device,
lib/classes/tts_engines/fairseq.py
26
Python
1
suggestion
1,115
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"bark_waveform_temp":float }.items() if self.session.get(key) is not None } with torch.no_grad(): result = self.engine.synthesize( default_text, ...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
"bark_waveform_temp":float }.items() if self.session.get(key) is not None } with torch.no_grad(): result = self.engine.synthesize( default_text, ...
@@ -99,6 +99,7 @@ def _check_bark_npz(self, voice_path:str, bark_dir:str, speaker:str)->bool: ) else: with torch.autocast( + device_type=device,
lib/classes/tts_engines/bark.py
26
Python
1
suggestion
559
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(report) if status: msg = 'Background noise or music detected. Proceeding voice extraction...' else: msg = 'No background noise or music detected. Skipping separation...' return True,status,msg except Exception as e: ...
Typo in success message: "exctracted" should be "extracted". ```suggestion msg = 'Voice extracted!' ```
msg = 'Background detected...' else: msg = 'No background detected' return True, status, msg except Exception as e: error = f'_detect_background() error: {e}' print(error) return False, False, error def _demucs_voic...
@@ -38,160 +34,89 @@ def _validate_format(self)->tuple[bool,str]: if file_extension in voice_formats: msg = 'Input file is valid' return True,msg - error = f'Unsupported file format: {file_extension}. Supported formats are: {", ".join(voice_formats)}' + error = f'Unsuppo...
lib/classes/voice_extractor.py
26
Python
0.786
refactor
119
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
fine_tuned_params = { key.removeprefix("xtts_"): cast_type(self.session[key]) for key, cast_type in { "xtts_temperature": float, #"xtts_codec_temperature": float, ...
This torch.no_grad() block moves the engine to device and immediately back to CPU without performing any operations in between. This appears to be dead code that serves no purpose and should be removed. ```suggestion ```
gpt_cond_latent, speaker_embedding = engine.get_conditioning_latents(audio_path=[voice_path], librosa_trim_db=30, load_sr=24000, sound_norm_refs=True) fine_tuned_params = { key.removeprefix("xtts_"): cast_type(self.session[key]) ...
@@ -290,16 +291,33 @@ def _check_xtts_builtin_speakers(self, voice_path:str, speaker:str)->str|bool: if self.session.get(key) is not None } with torch.no_grad(): - device = devices['CUDA']['proc'] if self.session['...
lib/classes/tts_engines/common/utils.py
26
Python
0.857
suggestion
221
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
return False else: trim_audio_buffer = 0.002 if part.endswith("'"): part = part[:-1] speaker_argument = {} not_supported_punc_pattern = re.compile(r...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
return False else: trim_audio_buffer = 0.002 if part.endswith("'"): part = part[:-1] speaker_argument = {} not_supported_punc_pattern = re.compile(r...
@@ -90,6 +90,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: ) else: with torch.autocast( + device_type=device,
lib/classes/tts_engines/yourtts.py
26
Python
1
suggestion
682
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
source_wav=source_wav, target_wav=target_wav ) self.engine_zs.to(devices['CPU']['proc']) else: error...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
audio_part = self.engine_zs.voice_conversion( source_wav=source_wav, target_wav=target_wav ) self.engine_zs.to(devices['CPU']['proc'...
@@ -175,6 +176,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: ) else: with torch.autocast( + device_type=device,
lib/classes/tts_engines/vits.py
26
Python
1
suggestion
695
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(error) return False else: trim_audio_buffer = 0.002 speaker_argument = {} if part.endswith("'"): part = part[:-1] ...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
print(error) return False else: trim_audio_buffer = 0.002 speaker_argument = {} if part.endswith("'"): part = part[:-1] ...
@@ -91,6 +91,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: ) else: with torch.autocast( + device_type=device,
lib/classes/tts_engines/fairseq.py
26
Python
1
suggestion
605
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
}.items() if self.session.get(key) is not None } with torch.no_grad(): """ result = self.engine.synthesize( ...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
"bark_waveform_temp": float }.items() if self.session.get(key) is not None } with torch.no_grad(): """ ...
@@ -199,6 +200,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: ) else: with torch.autocast( + device_type=device,
lib/classes/tts_engines/bark.py
26
Python
1
suggestion
722
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
min_required_duration = 20000 if self.session['tts_engine'] == TTS_ENGINES['BARK'] else 12000 msg = f"Removing long pauses..." print(msg) self._remove_silences(audio, silence_threshold) if total_duration <= min_required_duration: msg = f"Audio ...
The percent calculation will always return 0 or 1 because it uses integer division. It should be multiplied by 100 to get a proper percentage value, or use float division. ```suggestion percent = int(i * 100 / max(1, total - 1)) ```
DependencyError(e) return 0 except Exception as e: error = f"get_audio_duration() Error: Failed to process {filepath}: {e}" print(error) return 0 def _remove_silences(self, audio:AudioSegment, silence_threshold:int, min_silence_len:int=200, keep_s...
@@ -216,8 +141,96 @@ def _get_audio_duration(self, filepath:str)->float: print(error) return 0 + def _remove_silences(self, audio:AudioSegment, silence_threshold:int, min_silence_len:int=200, keep_silence:int=300)->AudioSegment: + msg = "Removing empty audio..." + print(msg)...
lib/classes/voice_extractor.py
26
Python
0.857
suggestion
248
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"xtts_speed": float, #"xtts_gpt_cond_len": int, #"xtts_gpt_batch_size": int, "xtts_enable_text_splitting": bool }.items() if self.sessio...
The device_type parameter passed to torch.autocast may be invalid. When self.session['device'] is 'rocm', it will be passed directly to torch.autocast, but 'rocm' is not a valid device_type for torch.autocast. PyTorch's autocast only accepts 'cpu', 'cuda', 'xpu', and optionally 'mps'. Consider mapping 'rocm' to 'cuda' ...
"xtts_top_p": float, "xtts_speed": float, #"xtts_gpt_cond_len": int, #"xtts_gpt_batch_size": int, "xtts_enable_text_splitting": bool ...
@@ -290,16 +291,33 @@ def _check_xtts_builtin_speakers(self, voice_path:str, speaker:str)->str|bool: if self.session.get(key) is not None } with torch.no_grad(): - device = devices['CUDA']['proc'] if self.session['...
lib/classes/tts_engines/common/utils.py
26
Python
1
suggestion
739
51
51
false
v26.1.12
1,515
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
def change_gr_restore_session(data:DictProxy|None, state:dict, req:gr.Request)->tuple: try: nonlocal models msg = 'Error while loading saved session. Please try to delete your cookies and refresh the page' if not data.get('id', Fals...
Inconsistent variable usage: checking if 'custom_model' is a string, but then validating the existence of 'custom_model_dir' path. This should likely check if 'custom_model_dir' exists in the dictionary before calling os.path.exists on it, or the validation should be performed on 'custom_model' itself. Consider using s...
def change_gr_restore_session(data:DictProxy|None, state:dict, req:gr.Request)->tuple: try: nonlocal models msg = 'Error while loading saved session. Please try to delete your cookies and refresh the page' if not data.get('id', Fals...
@@ -1700,25 +1700,25 @@ def change_gr_restore_session(data:DictProxy|None, state:dict, req:gr.Request)-> active_sessions.add(req.session_hash) session[req.session_hash] = req.session_hash session['cancellation_requested'] = False - ...
lib/gradio.py
26
Python
0.857
suggestion
638
51
51
false
v26.1.14
1,520
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
except (subprocess.CalledProcessError, Exception): mem=psutil.virtual_memory() info={ "os":self.system, "device_type":"jetson", "device_name":"NVIDIA Jetson (Unified Me...
The Docker memory detection logic checks if script_mode equals FULL_DOCKER and if running inside Docker, but doesn't continue to check the actual device type (cuda, jetson, etc.). This means that even if CUDA is available in a Docker container with FULL_DOCKER mode, it will report Docker container memory instead of GPU...
def _fmt(b:int)->float: if not b: return 0.0 return float(f"{b/(1024**3):.2f}") @staticmethod def _gb(b: int, decimals: int = 2) -> float: return round(b / (1024 ** 3), decimals) if b > 0 else 0.0 def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any: ...
@@ -1,21 +1,70 @@ import os, platform, json, psutil, subprocess, re + from typing import Any +from lib.conf import NATIVE, FULL_DOCKER class VRAMDetector: def __init__(self): self.system = platform.system().lower() + def _in_docker(self)->bool: + if os.path.exists("/.dockerenv"): + ...
lib/classes/vram_detector.py
26
Python
0.643
suggestion
451
51
51
false
v26.1.14
1,522
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import os, platform, json, psutil, subprocess, re from typing import Any class VRAMDetector: def __init__(self): self.system = platform.system().lower() @staticmethod def _fmt(b:int)->float: if not b: return 0.0 return float(f"{b/(1024**3):.2f}") def detect_vram(self, device:s...
The NATIVE import is unused in this file. Consider removing it or document why it's needed for future use. ```suggestion from lib.conf import FULL_DOCKER ```
import os, platform, json, psutil, subprocess, re from typing import Any from lib.conf import NATIVE, FULL_DOCKER class VRAMDetector: def __init__(self): self.system = platform.system().lower() def _in_docker(self)->bool: if os.path.exists("/.dockerenv"): return True try: ...
@@ -1,21 +1,70 @@ import os, platform, json, psutil, subprocess, re + from typing import Any +from lib.conf import NATIVE, FULL_DOCKER
lib/classes/vram_detector.py
4
Python
0.786
suggestion
157
29
29
false
v26.1.14
1,522
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
from typing import Any class VRAMDetector: def __init__(self): self.system = platform.system().lower() @staticmethod def _fmt(b:int)->float: if not b: return 0.0 return float(f"{b/(1024**3):.2f}") def detect_vram(self, device:str, as_json:bool=False)->Any: info = {} ...
The file opened here is not properly closed, which can lead to a resource leak. The file handle should be closed after reading by using a context manager. ```suggestion with open(p, "rt") as f: val = f.read().strip() ```
from typing import Any from lib.conf import NATIVE, FULL_DOCKER class VRAMDetector: def __init__(self): self.system = platform.system().lower() def _in_docker(self)->bool: if os.path.exists("/.dockerenv"): return True try: with open("/proc/1/cgroup", "rt", erro...
@@ -1,21 +1,70 @@ import os, platform, json, psutil, subprocess, re + from typing import Any +from lib.conf import NATIVE, FULL_DOCKER class VRAMDetector: def __init__(self): self.system = platform.system().lower() + def _in_docker(self)->bool: + if os.path.exists("/.dockerenv"): + ...
lib/classes/vram_detector.py
26
Python
1
suggestion
264
51
51
false
v26.1.14
1,522
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import os, platform, json, psutil, subprocess, re from typing import Any class VRAMDetector: def __init__(self): self.system = platform.system().lower() @staticmethod def _fmt(b:int)->float: if not b: return 0.0 return float(f"{b/(1024**3):.2f}") def detect_vram(self, device:s...
The NATIVE constant is imported but never used in this file. Consider removing it from the import statement to keep the code clean. ```suggestion from lib.conf import FULL_DOCKER ```
import os, platform, json, psutil, subprocess, re from typing import Any from lib.conf import NATIVE, FULL_DOCKER class VRAMDetector: def __init__(self): self.system = platform.system().lower() def _in_docker(self)->bool: if os.path.exists("/.dockerenv"): return True try: ...
@@ -1,21 +1,70 @@ import os, platform, json, psutil, subprocess, re + from typing import Any +from lib.conf import NATIVE, FULL_DOCKER
lib/classes/vram_detector.py
4
Python
0.786
suggestion
182
29
29
false
v25.12.33
1,523
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import os, platform, json, psutil, subprocess, re from typing import Any class VRAMDetector: def __init__(self): self.system = platform.system().lower() @staticmethod def _fmt(b:int)->float: if not b: return 0.0 return float(f"{b/(1024**3):.2f}") def detect_vram(self, device:s...
Inconsistent data types in return value: total_vram_gb is computed as an integer using int(round(...)), while free_vram_gb is computed as a float using self._gb() which returns a rounded float. This could cause issues for callers expecting consistent types. Consider making both the same type, either both integers or bo...
info['free_vram_gb'] = self._fmt(mem.available) info['total_vram_gb'] = self._fmt(mem.total) return json.dumps(info, indent=2) if as_json else info except Exception: pass if not info: # ─────────────────────────── CPU fallback ...
@@ -129,22 +178,25 @@ def detect_vram(self, device:str, as_json:bool=False)->Any: except Exception: pass - # ─────────────────────────── CPU fallback - mem = psutil.virtual_memory() - info = { - "os": self.system, - "device_type": "cpu", - "d...
lib/classes/vram_detector.py
26
Python
1
suggestion
399
150
29
false
v25.12.33
1,523
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
from typing import Any class VRAMDetector: def __init__(self): self.system = platform.system().lower() @staticmethod def _fmt(b:int)->float: if not b: return 0.0 return float(f"{b/(1024**3):.2f}") def detect_vram(self, device:str, as_json:bool=False)->Any: info = {} ...
The file handle opened here is not properly closed. Consider using a context manager (with statement) to ensure proper resource cleanup, or explicitly close the file after reading. ```suggestion with open(p, "r") as f: val = f.read().strip() ```
from typing import Any from lib.conf import NATIVE, FULL_DOCKER class VRAMDetector: def __init__(self): self.system = platform.system().lower() def _in_docker(self)->bool: if os.path.exists("/.dockerenv"): return True try: with open("/proc/1/cgroup", "rt", erro...
@@ -1,21 +1,70 @@ import os, platform, json, psutil, subprocess, re + from typing import Any +from lib.conf import NATIVE, FULL_DOCKER class VRAMDetector: def __init__(self): self.system = platform.system().lower() + def _in_docker(self)->bool: + if os.path.exists("/.dockerenv"): + ...
lib/classes/vram_detector.py
26
Python
1
suggestion
289
51
51
false
v25.12.33
1,523
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"allocated_human": self._fmt(alloc), "reserved_human": self._fmt(resv), } return json.dumps(info, indent=2) if as_json else info # ─────────────────────────── Apple MPS (Metal) elif hasattr(torch.backends, 'mps') and torch....
The Docker container detection logic has been moved from the beginning of the function (before device checks) to the fallback section at the end (after all device checks fail). This changes the behavior: in the old code, if running in Docker with FULL_DOCKER mode, it would immediately return Docker memory info. In the ...
"device_type": "mps", "device_name": "Apple GPU (Metal)", "free_bytes": mem.available, "total_bytes": mem.total, "free_vram_gb": self._ceil_gb(mem.available), "total_vram_gb": self._ceil_gb(mem.total)...
@@ -153,50 +143,65 @@ def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any: "total_bytes": total, "allocated_bytes": alloc, "reserved_bytes": resv, - "free_vram_gb": self._fmt(free), - "total_vram...
lib/classes/vram_detector.py
26
Python
0.643
bug
574
45
50
false
v26.1.14
1,524
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
resv = torch.xpu.memory_reserved() info = { "os": self.system, "device_type": "xpu", "device_name": torch.xpu.get_device_name(0), "free_bytes": free, "total_bytes": total, ...
The variable `in_docker` is used here but is defined inside the try block at line 53. If an exception occurs before line 53 (e.g., if importing torch fails), `in_docker` will be undefined and cause a NameError when this fallback logic is reached.
"total_vram_gb": self._ceil_gb(total), "allocated_vram_gb": self._ceil_gb(alloc), "reserved_vram_gb": self._ceil_gb(resv), } return json.dumps(info, indent=2) if as_json else info # ─────────────────────────── Apple...
@@ -153,50 +143,65 @@ def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any: "total_bytes": total, "allocated_bytes": alloc, "reserved_bytes": resv, - "free_vram_gb": self._fmt(free), - "total_vram...
lib/classes/vram_detector.py
26
Python
0.786
bug
246
51
51
false
v26.1.14
1,524
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"free_vram_gb":self._fmt(free), "total_vram_gb":self._fmt(total), "note":"Jetson uses unified system RAM as VRAM." } return json.dumps(info,indent=2) if as_json else in...
The field names `allocated_human` and `reserved_human` have been changed to `allocated_vram_gb` and `reserved_vram_gb`. This is a breaking API change that will affect any consumers of this API who expect the old field names.
"free_bytes": mem.available, "total_bytes": mem.total, "free_vram_gb": self._ceil_gb(mem.available), "total_vram_gb": self._ceil_gb(mem.total), "note": "tegrastats unavailable; rep...
@@ -113,10 +103,10 @@ def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any: "total_bytes": total, "allocated_bytes": alloc, "reserved_bytes": resv, - "free_vram_gb": self._fmt(free), - ...
lib/classes/vram_detector.py
26
Python
0.643
suggestion
224
51
51
false
v26.1.14
1,524
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if torch.cuda.is_available(): free, total = torch.cuda.mem_get_info() alloc = torch.cuda.memory_allocated() resv = torch.cuda.memory_reserved() info = { "os": self.system, "dev...
The field names `allocated_human` and `reserved_human` have been changed to `allocated_vram_gb` and `reserved_vram_gb`. This is a breaking API change that will affect any consumers of this API who expect the old field names.
"allocated_bytes": alloc, "reserved_bytes": resv, "free_vram_gb": self._ceil_gb(free), "total_vram_gb": self._ceil_gb(total), "allocated_vram_gb": self._ceil_gb(alloc), "reserv...
@@ -133,10 +123,10 @@ def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any: "total_bytes": total, "allocated_bytes": alloc, "reserved_bytes": resv, - "free_vram_gb": self._fmt(free), - "total_vram...
lib/classes/vram_detector.py
26
Python
0.643
suggestion
224
51
51
false
v26.1.14
1,524
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
elif hasattr(torch, 'hip') and torch.hip.is_available(): free, total = torch.hip.mem_get_info() alloc = torch.hip.memory_allocated() resv = torch.hip.memory_reserved() info = { "os": self.system, "device_...
The field names `allocated_human` and `reserved_human` have been changed to `allocated_vram_gb` and `reserved_vram_gb`. This is a breaking API change that will affect any consumers of this API who expect the old field names.
"allocated_bytes": alloc, "reserved_bytes": resv, "free_vram_gb": self._ceil_gb(free), "total_vram_gb": self._ceil_gb(total), "allocated_vram_gb": self._ceil_gb(alloc), "reserved_vram_gb": self._ceil_...
@@ -153,50 +143,65 @@ def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any: "total_bytes": total, "allocated_bytes": alloc, "reserved_bytes": resv, - "free_vram_gb": self._fmt(free), - "total_vram...
lib/classes/vram_detector.py
26
Python
0.643
suggestion
224
51
51
false
v26.1.14
1,524
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"/sys/fs/cgroup/memory/memory.limit_in_bytes" # cgroups v1 ] for p in paths: if os.path.exists(p): try: val = open(p).read().strip() if val.isdigit(): limit = int(val) if lim...
The return type has changed from float to int with `_ceil_gb` instead of `_fmt`. This changes the precision of VRAM reporting from 2 decimal places to rounded-up integers. For example, 1.5 GB would now be reported as 2 GB instead of 1.50 GB. This is a breaking API change that affects all consumers expecting float value...
"/sys/fs/cgroup/memory/memory.limit_in_bytes" # cgroups v1 ] for p in paths: if os.path.exists(p): try: with open(p, "rt") as f: val = f.read().strip() if val.isdigit(): ...
@@ -42,63 +43,52 @@ def _fmt(b:int)->float: return float(f"{b/(1024**3):.2f}") @staticmethod - def _gb(b: int, decimals: int = 2) -> float: - return round(b / (1024 ** 3), decimals) if b > 0 else 0.0 + def _ceil_gb(b: int) -> int: + return math.ceil(b / (1024 ** 3)) if b > 0 else 0
lib/classes/vram_detector.py
26
Python
0.786
suggestion
339
51
51
false
v26.1.14
1,524
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
resv = torch.xpu.memory_reserved() info = { "os": self.system, "device_type": "xpu", "device_name": torch.xpu.get_device_name(0), "free_bytes": free, "total_bytes": total, ...
The variable `in_docker` is defined inside the try block (line 53) but is referenced outside of it after the except block. If an exception occurs before line 53 executes (e.g., if torch import fails), `in_docker` will be undefined, causing a NameError. Move the `in_docker = self._in_docker()` call outside the try block...
"total_vram_gb": self._ceil_gb(total), "allocated_vram_gb": self._ceil_gb(alloc), "reserved_vram_gb": self._ceil_gb(resv), } return json.dumps(info, indent=2) if as_json else info # ─────────────────────────── Apple...
@@ -153,50 +143,65 @@ def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any: "total_bytes": total, "allocated_bytes": alloc, "reserved_bytes": resv, - "free_vram_gb": self._fmt(free), - "total_vram...
lib/classes/vram_detector.py
26
Python
0.786
bug
336
51
51
false
v25.12.33
1,525
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"/sys/fs/cgroup/memory/memory.limit_in_bytes" # cgroups v1 ] for p in paths: if os.path.exists(p): try: val = open(p).read().strip() if val.isdigit(): limit = int(val) if lim...
The return value behavior is inconsistent with typical ceiling semantics. When `b` is 0, the function returns 0, but `math.ceil(0 / (1024 ** 3))` would also return 0. The conditional check `if b > 0` appears unnecessary and could mask edge cases where negative values are passed. Consider simplifying to `return math.cei...
"/sys/fs/cgroup/memory/memory.limit_in_bytes" # cgroups v1 ] for p in paths: if os.path.exists(p): try: with open(p, "rt") as f: val = f.read().strip() if val.isdigit(): ...
@@ -42,63 +43,52 @@ def _fmt(b:int)->float: return float(f"{b/(1024**3):.2f}") @staticmethod - def _gb(b: int, decimals: int = 2) -> float: - return round(b / (1024 ** 3), decimals) if b > 0 else 0.0 + def _ceil_gb(b: int) -> int: + return math.ceil(b / (1024 ** 3)) if b > 0 else 0
lib/classes/vram_detector.py
26
Python
1
bug
469
51
51
false
v25.12.33
1,525
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import os, subprocess, re, sys, gradio as gr class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): self.cmd = cmd self.is_gui_process = is_gui_process self.total_duration = total_duration self.msg = msg self.proce...
The on_progress parameter is accepted in __init__ but never stored as an instance variable (self.on_progress = on_progress is missing). This causes line 21 in _emit_progress to fail with an AttributeError when trying to access self.on_progress.
import os, subprocess, multiprocessing, re, sys, gradio as gr from collections.abc import Callable class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing', on_progress:Callable[[float], None]|None=None)->None: self.cmd = cmd self.is_gui_pro...
@@ -1,17 +1,27 @@ -import os, subprocess, re, sys, gradio as gr +import os, subprocess, multiprocessing, re, sys, gradio as gr + +from collections.abc import Callable class SubprocessPipe: - def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): + def __init__(self, cmd:s...
lib/classes/subprocess_pipe.py
16
Python
0.643
bug
244
41
41
false
v26.1.14
1,526
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(f'final_list: {final_list}') with open(final_list, 'w') as f: for _, chunk_path, _ in chunk_list: f.write(f"file '{chunk_path.replace(os.sep, '/')}'\n") if assemble_chunks(final_list, chapter_audio_file, is_gui_process): ...
Calling assemble_audio_chunks_worker without the required progress_queue and job_id parameters that were added to the function signature. These should be passed as None if not needed, but Python will use the default values. However, for consistency and clarity, all calls should explicitly pass these parameters.
if is_gui_process: progress_bar( min(overall / 100, 1.0), desc="Combining audio sentences" ) except queue.Em...
@@ -1933,9 +1953,10 @@ def combine_audio_sentences(file:str, start:int, end:int, session_id:str)->bool: final_list = os.path.join(temp_dir, 'sentences_final.txt') print(f'final_list: {final_list}') with open(final_list, 'w') as f: - for _, chunk_path...
lib/core.py
26
Python
0.5
suggestion
312
51
51
false
v26.1.14
1,526
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
for file in chapter_files: if session['cancellation_requested']: msg = 'Cancel requested' print(msg) return None path = os.path.join(session['ch...
Calling assemble_audio_chunks_worker without the required progress_queue and job_id parameters. These should be passed explicitly as None to match the function signature and avoid confusion.
try: job_id, percent = progress_queue.get(timeout=0.1) progress_state[job_id] = percent overall = sum(progress_state.values()) / total_jobs if i...
@@ -2183,23 +2203,45 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin for file in batch: path = Path(session['chapters_dir']) / file f.write(f"file '{path.as_posix()}'\n") - ...
lib/core.py
26
Python
0.429
suggestion
190
51
51
false
v26.1.14
1,526
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
total_duration = 0.0 try: with open(txt_file, 'r') as f: for line in f: if line.strip().startswith("file"): file_path = line.strip().split("file ")[1].strip().strip("'").strip('"') if os.path.exists(file_path...
Calling assemble_audio_chunks_worker without the required progress_queue and job_id parameters. These should be passed explicitly as None to match the function signature and avoid confusion.
f.write(f"file '{Path(chunk_path).as_posix()}'\n") if not assemble_audio_chunks_worker(str(final_list), str(combined_chapters_file), session['is_gui_process']): error = f'assemble_audio_chunks_worker() Final merge failed for part {part_...
@@ -2222,8 +2264,8 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin return None path = os.path.join(session['chapters_dir'], file).replace("\\", "/") f.write(f"file '{path}'\n") - ...
lib/core.py
26
Python
0.429
suggestion
190
51
51
false
v26.1.14
1,526
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import os, subprocess, re, sys, gradio as gr class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): self.cmd = cmd self.is_gui_process = is_gui_process self.total_duration = total_duration self.msg = msg self.proce...
The new _emit_progress method is defined but never called anywhere in the code. The existing _on_progress method (line 26) continues to be used instead. Either _emit_progress should replace _on_progress, or this new method should be removed to avoid confusion about which method is the correct one to use.
import os, subprocess, multiprocessing, re, sys, gradio as gr from collections.abc import Callable class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing', on_progress:Callable[[float], None]|None=None)->None: self.cmd = cmd self.is_gui_pro...
@@ -1,17 +1,27 @@ -import os, subprocess, re, sys, gradio as gr +import os, subprocess, multiprocessing, re, sys, gradio as gr + +from collections.abc import Callable class SubprocessPipe: - def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): + def __init__(self, cmd:s...
lib/classes/subprocess_pipe.py
24
Python
0.5
suggestion
305
49
49
false
v26.1.14
1,526
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if convert_chapters2audio(session_id): msg = 'Conversion successful. Combining sentences and chapters…' show_alert({"type": "info", "msg": msg}) exported_files = combine_audio_chapters(session['id']) if exported_files is not None...
The error message references session['chapters'] but the original code referenced session['toc']. This change may display incorrect or missing data in the error message if the 'chapters' key contains different information than 'toc', or if it doesn't exist at all.
if lang_dict: session['metadata']['language'] = lang_dict.pt3 except Exception as e: pass ...
@@ -2594,7 +2648,7 @@ def convert_ebook(args:dict)->tuple: progress_status, passed = finalize_audiobook(session_id) return progress_status, passed else: ...
lib/core.py
26
Python
0.643
bug
264
51
51
false
v26.1.14
1,526
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"/sys/fs/cgroup/memory/memory.limit_in_bytes" # cgroups v1 ] for p in paths: if os.path.exists(p): try: with open(p, "rt") as f: val = f.read().strip() if val.isdigit(): ...
Removed the conditional check 'if b > 0 else 0'. If b is 0 or negative, math.ceil(0 / (1024 ** 3)) will return 0, but if b is negative, this will return an incorrect negative result instead of 0. The original guard was safer.
"/sys/fs/cgroup/memory/memory.limit_in_bytes" # cgroups v1 ] for p in paths: if os.path.exists(p): try: with open(p, "rt") as f: val = f.read().strip() if val.isdigit(): ...
@@ -44,14 +44,13 @@ def _fmt(b:int)->float: @staticmethod def _ceil_gb(b: int) -> int: - return math.ceil(b / (1024 ** 3)) if b > 0 else 0 + return math.ceil(b / (1024 ** 3))
lib/classes/vram_detector.py
26
Python
0.5
bug
225
51
51
false
v26.1.14
1,526
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import os, subprocess, re, sys, gradio as gr class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): self.cmd = cmd self.is_gui_process = is_gui_process self.total_duration = total_duration self.msg = msg self.proce...
The `on_progress` parameter is added to the constructor but is not stored as an instance variable. The code at line 21 references `self.on_progress`, which will cause an AttributeError since `on_progress` is never assigned to `self.on_progress`.
import os, subprocess, multiprocessing, re, sys, gradio as gr from collections.abc import Callable class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing', on_progress:Callable[[float], None]|None=None)->None: self.cmd = cmd self.is_gui_pro...
@@ -1,17 +1,27 @@ -import os, subprocess, re, sys, gradio as gr +import os, subprocess, multiprocessing, re, sys, gradio as gr + +from collections.abc import Callable class SubprocessPipe: - def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): + def __init__(self, cmd:s...
lib/classes/subprocess_pipe.py
6
Python
0.786
suggestion
245
31
31
false
v25.12.33
1,527
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import os, subprocess, re, sys, gradio as gr class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): self.cmd = cmd self.is_gui_process = is_gui_process self.total_duration = total_duration self.msg = msg self.proce...
The `_emit_progress` method is defined but never called anywhere in the code. The existing `_on_progress` method is still being used instead. This new method should either replace `_on_progress` or be removed if it's not needed.
import os, subprocess, multiprocessing, re, sys, gradio as gr from collections.abc import Callable class SubprocessPipe: def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing', on_progress:Callable[[float], None]|None=None)->None: self.cmd = cmd self.is_gui_pro...
@@ -1,17 +1,27 @@ -import os, subprocess, re, sys, gradio as gr +import os, subprocess, multiprocessing, re, sys, gradio as gr + +from collections.abc import Callable class SubprocessPipe: - def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='Processing'): + def __init__(self, cmd:s...
lib/classes/subprocess_pipe.py
24
Python
0.643
suggestion
228
49
49
false
v25.12.33
1,527
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
msg = 'Cancel requested' print(msg) return False batch = selected_files[i:i + batch_size] txt = os.path.join(temp_dir, f'chunk_{i:04d}.txt') out = os.path.join(temp_dir, f'chunk_{i:04d}.{d...
The variable `is_gui_process` is referenced but not defined in this scope. It should be `session['is_gui_process']` to match the pattern used elsewhere in this function (lines 1919, 1850, etc.).
print(msg) return False batch = selected_files[i:i + batch_size] txt = os.path.join(temp_dir, f'chunk_{i:04d}.txt') out = os.path.join(temp_dir, f'chunk_{i:04d}.{default_audio_proc_format}') w...
@@ -1915,13 +1914,34 @@ def combine_audio_sentences(file:str, start:int, end:int, session_id:str)->bool: with open(txt, 'w') as f: for file in batch: f.write(f"file '{file.replace(os.sep, '/')}'\n") - chunk_list.append((txt, o...
lib/core.py
26
Python
0.571
suggestion
194
51
51
false
v25.12.33
1,527
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
final_list = temp_dir / f'part_{part_idx+1:02d}_final.txt' with open(final_list, 'w') as f: for _, chunk_path, _ in chunk_list: f.write(f"file '{Path(chunk_path).as_posix()}'\n") if not as...
The variable `is_gui_process` is referenced but not defined in this scope. It should be `session['is_gui_process']` to match the pattern used elsewhere in this function (line 2207).
print(msg) return None batch = part_file_list[i:i + batch_size] txt = temp_dir / f'chunk_{i:04d}.txt' out = temp_dir / f'chunk_{i:04d}.{default_audio_proc_format}' ...
@@ -2183,23 +2203,45 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin for file in batch: path = Path(session['chapters_dir']) / file f.write(f"file '{path.as_posix()}'\n") - ...
lib/core.py
26
Python
0.571
suggestion
181
51
51
false
v25.12.33
1,527
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if not assemble_audio_chunks_worker(str(final_list), str(combined_chapters_file), session['is_gui_process']): error = f'assemble_audio_chunks_worker() Final merge failed for part {part_idx+1}.' print(error) retur...
The variable `progress_queue` is undefined in this code block. In the `if session['output_split']` branch above (line 2160), `progress_queue` is initialized at line 2192. However, in this `else` block, `progress_queue` is never initialized but is used in the function call at line 2268. This will cause a NameError at ru...
f.write(f"file '{Path(chunk_path).as_posix()}'\n") if not assemble_audio_chunks_worker(str(final_list), str(combined_chapters_file), is_gui_process, progress_queue, 1): error = f'assemble_audio_chunks_worker() Final merge failed for par...
@@ -2264,7 +2265,7 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin return None path = os.path.join(session['chapters_dir'], file).replace("\\", "/") f.write(f"file '{path}'\n") - ...
lib/core.py
26
Python
0.786
suggestion
469
51
51
false
v26.1.14
1,528
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if not assemble_audio_chunks_worker(str(final_list), str(combined_chapters_file), session['is_gui_process']): error = f'assemble_audio_chunks_worker() Final merge failed for part {part_idx+1}.' print(error) retur...
The variable `progress_queue` is used but never initialized in the `else` block starting at line 2254. This will cause a `NameError` at runtime. You need to initialize `progress_queue` (and likely a `manager`) before line 2268, similar to how it's done in the `if session['output_split']:` branch at lines 2191-2192.
f.write(f"file '{Path(chunk_path).as_posix()}'\n") if not assemble_audio_chunks_worker(str(final_list), str(combined_chapters_file), is_gui_process, progress_queue, 1): error = f'assemble_audio_chunks_worker() Final merge failed for par...
@@ -2264,7 +2265,7 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin return None path = os.path.join(session['chapters_dir'], file).replace("\\", "/") f.write(f"file '{path}'\n") - ...
lib/core.py
26
Python
0.786
suggestion
316
51
51
false
v25.12.33
1,529
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
shutil.which('ffmpeg'), '-hide_banner', '-y', '-safe', '0', '-f', 'concat', '-i', txt_file, '-c:a', default_audio_proc_format, '-map_metadata', '-1', '-threads', '0', '-progress', 'pipe:2', ...
The variable `msg` is assigned but only used once immediately after. This adds unnecessary complexity without providing clear benefit. Consider either removing the intermediate variable or using it for logging/error handling if that's the intended purpose. ```suggestion print(f'Completed → {out_file}') ```
shutil.which('ffmpeg'), '-hide_banner', '-y', '-safe', '0', '-f', 'concat', '-i', txt_file, '-c:a', default_audio_proc_format, '-map_metadata', '-1', '-threads', '0', '-progress', 'pipe:2', ...
@@ -2324,10 +2324,12 @@ def assemble_audio_chunks_worker(txt_file:str, out_file:str, is_gui_process:bool on_progress=on_progress, ) if proc_pipe: - print(f'Completed → {out_file}') + msg = f'Completed → {out_file}' + print(msg)
lib/core.py
26
Python
1
performance
319
51
51
false
v25.12.33
1,536
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
'-f', 'concat', '-i', txt_file, '-c:a', default_audio_proc_format, '-map_metadata', '-1', '-threads', '0', '-progress', 'pipe:2', '-nostats', out_file, ] on_progress = None if progress_queue is not No...
The variable `error` is assigned but only used once immediately after. This adds unnecessary complexity without providing clear benefit. Consider either removing the intermediate variable or using it for logging/error handling if that's the intended purpose. ```suggestion print(f'Failed (proc_pipe) → {out_f...
'-f', 'concat', '-i', txt_file, '-c:a', default_audio_proc_format, '-map_metadata', '-1', '-threads', '0', '-progress', 'pipe:2', '-nostats', out_file, ] on_progress = None if progress_queue is not No...
@@ -2324,10 +2324,12 @@ def assemble_audio_chunks_worker(txt_file:str, out_file:str, is_gui_process:bool on_progress=on_progress, ) if proc_pipe: - print(f'Completed → {out_file}') + msg = f'Completed → {out_file}' + print(msg) return True ...
lib/core.py
26
Python
1
bug
330
51
51
false
v25.12.33
1,536
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
error = f'Failed (proc_pipe) → {out_file}' print(error) return False except subprocess.CalledProcessError as e: DependencyError(e) return False except Exception as e: print(f'assemble_audio_chunks_worker() Error: Failed to process {txt_file} → {out_fil...
The function uses tabs for indentation while the rest of the file uses spaces (4 spaces). This inconsistency violates PEP 8 and can cause issues in Python. All indentation in the file should use the same style (4 spaces based on surrounding code). ```suggestion for name in os.listdir(folder_path): path = os...
return s if len(e) >= max_bytes: # return as many bytes of the ellipsis as fit return e[:max_bytes].decode('utf-8', errors='ignore') budget = max_bytes - len(e) out = bytearray() for ch in s: b = ch.encode('utf-8') if len(out) + len(b) > budget: break ...
@@ -2364,6 +2347,14 @@ def sanitize_meta_chapter_title(title:str, max_bytes:int=140)->str: title = title.replace(TTS_SML['pause']['token'], '') return ellipsize_utf8_bytes(title, max_bytes=max_bytes, ellipsis='…') +def clear_folder(folder_path:str)->None: + for name in os.listdir(folder_path): + path = os....
lib/core.py
26
Python
0.857
suggestion
484
51
51
false
v25.12.33
1,538
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
for k, v in protected.items(): out = out.replace(k, v) return out def filter_sml(text:str)->str: text = TTS_SML['###']['match'].sub(' ‡pause‡ ', text) text = TTS_SML['break']['match'].sub(' ‡break‡ ', text) text = TTS_SML['pause']['match'].sub( lambda m: f' ‡pause:{m.group(1)}‡ ' if...
The function uses tabs for indentation while the rest of the file uses spaces (4 spaces). This inconsistency violates PEP 8 and can cause issues in Python. All indentation in the file should use the same style (4 spaces based on surrounding code). ```suggestion text = TTS_SML['###']['match'].sub(' ‡pause‡ ', text) ...
for i, t in enumerate(buf): if i == 0: out += t else: if re.match(r"^\w+$", buf[i-1]) and re.match(r"^\w+$", t): out += ' ' + t else: out += t for k, v in protected.items(): out = out.replace(k, v) return out def fi...
@@ -1681,18 +1689,20 @@ def romanize(word): out = out.replace(k, v) return out -def filter_sml(text:str)->str: - text = TTS_SML['###']['match'].sub(' ‡pause‡ ', text) - text = TTS_SML['break']['match'].sub(' ‡break‡ ', text) - text = TTS_SML['pause']['match'].sub( - lambda m: f' ‡pause:{...
lib/core.py
26
Python
0.857
suggestion
757
51
51
false
v25.12.33
1,538
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"knnvc": {"path": "voice_conversion_models/multilingual/multi-dataset/knnvc", "samplerate": 16000}, "openvoice_v1": {"path": "voice_conversion_models/multilingual/multi-dataset/openvoice_v1", "samplerate": 22050}, "openvoice_v2": {"path": "voice_conversion_models/multilingual/multi-dataset/openvoice_v2", ...
The TTS_SML dictionary uses tabs for indentation while the rest of the file uses spaces. This inconsistency violates PEP 8 and can cause issues in Python. All indentation in the file should use the same style (spaces based on surrounding code).
"knnvc": {"path": "voice_conversion_models/multilingual/multi-dataset/knnvc", "samplerate": 16000}, "openvoice_v1": {"path": "voice_conversion_models/multilingual/multi-dataset/openvoice_v1", "samplerate": 22050}, "openvoice_v2": {"path": "voice_conversion_models/multilingual/multi-dataset/openvoice_v2", ...
@@ -22,21 +22,25 @@ TTS_SML = { "break": { - "match": re.compile(r'(?:‡|\[)break(?:‡|\])'), - "token": "‡break‡" - }, + "match": re.compile(r'(?:‡|\[)break(?:‡|\])'), + "close_match": None, + "token": "‡break‡" + }, "pause": { - "match": re.compile(r'(?:‡|\[)pause(?::(\d+(?...
lib/conf_models.py
26
Python
0.5
style
244
51
51
false
v25.12.33
1,538
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
from unidecode import unidecode from phonemizer import phonemize from lib.classes.subprocess_pipe import SubprocessPipe from lib.classes.vram_detector import VRAMDetector from lib.classes.voice_extractor import VoiceExtractor from lib.classes.tts_manager import TTSManager #from lib.classes.redirect_console import Redi...
The global `progress_queue` variable is initialized at module level but is reassigned in multiple functions using `global progress_queue`. This pattern can lead to confusion and potential race conditions in multi-threaded contexts. Consider removing this module-level global and relying solely on `context.progress_queue...
from unidecode import unidecode from phonemizer import phonemize from lib.classes.subprocess_pipe import SubprocessPipe from lib.classes.vram_detector import VRAMDetector from lib.classes.voice_extractor import VoiceExtractor from lib.classes.tts_manager import TTSManager #from lib.classes.redirect_console import Redi...
@@ -60,6 +60,7 @@ ProgressEvent:TypeAlias = tuple[int, float] ProgressQueue:TypeAlias = queue.Queue[ProgressEvent] +progress_queue = None
lib/core.py
26
Python
0.786
bug
362
51
51
false
v25.12.33
1,538
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
elif isinstance(data, list): proxy_list = manager.list() for item in data: proxy_list.append(self._recursive_proxy(item, manager)) return proxy_list elif isinstance(data, (str, int, float, bool, type(None))): return data else: ...
The `progress_queue` field in the session dictionary is set to None and never used. Since line 204 creates the actual queue in `context.progress_queues[session_id]`, this field appears redundant and should be removed to avoid confusion. ```suggestion ```
proxy_dict[key] = self._recursive_proxy(value, manager) return proxy_dict elif isinstance(data, list): proxy_list = manager.list() for item in data: proxy_list.append(self._recursive_proxy(item, manager)) return proxy_list e...
@@ -128,7 +130,8 @@ def set_session(self, session_id:str)->Any: "process_id": None, "status": None, "event": None, - "progress": 0, + "ticker": 0, + "progress_queue": None,
lib/core.py
26
Python
0.857
suggestion
255
51
51
false
v25.12.33
1,538
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
for k, v in protected.items(): out = out.replace(k, v) return out def filter_sml(text:str)->str: text = TTS_SML['###']['match'].sub(' ‡pause‡ ', text) text = TTS_SML['break']['match'].sub(' ‡break‡ ', text) text = TTS_SML['pause']['match'].sub( lambda m: f' ‡pause:{m.group(1)}‡ ' if...
The filter_sml function uses tab characters for indentation while the rest of the codebase uses spaces. This is inconsistent with Python's PEP 8 style guide and the surrounding code. Replace tabs with spaces (4 spaces per indentation level) for consistency. ```suggestion text = TTS_SML['###']['match'].sub(' ‡pause‡...
for i, t in enumerate(buf): if i == 0: out += t else: if re.match(r"^\w+$", buf[i-1]) and re.match(r"^\w+$", t): out += ' ' + t else: out += t for k, v in protected.items(): out = out.replace(k, v) return out def fi...
@@ -1681,18 +1689,20 @@ def romanize(word): out = out.replace(k, v) return out -def filter_sml(text:str)->str: - text = TTS_SML['###']['match'].sub(' ‡pause‡ ', text) - text = TTS_SML['break']['match'].sub(' ‡break‡ ', text) - text = TTS_SML['pause']['match'].sub( - lambda m: f' ‡pause:{...
lib/core.py
26
Python
0.857
suggestion
767
51
51
false
v26.1.14
1,539
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
error = f'Failed (proc_pipe) → {out_file}' print(error) return False except subprocess.CalledProcessError as e: DependencyError(e) return False except Exception as e: print(f'assemble_audio_chunks_worker() Error: Failed to process {txt_file} → {out_fil...
The clear_folder function uses tab characters for indentation while the rest of the codebase uses spaces. This is inconsistent with Python's PEP 8 style guide and the surrounding code. Replace tabs with spaces (4 spaces per indentation level) for consistency. ```suggestion for name in os.listdir(folder_path): ...
return s if len(e) >= max_bytes: # return as many bytes of the ellipsis as fit return e[:max_bytes].decode('utf-8', errors='ignore') budget = max_bytes - len(e) out = bytearray() for ch in s: b = ch.encode('utf-8') if len(out) + len(b) > budget: break ...
@@ -2364,6 +2347,14 @@ def sanitize_meta_chapter_title(title:str, max_bytes:int=140)->str: title = title.replace(TTS_SML['pause']['token'], '') return ellipsize_utf8_bytes(title, max_bytes=max_bytes, ellipsis='…') +def clear_folder(folder_path:str)->None: + for name in os.listdir(folder_path): + path = os....
lib/core.py
26
Python
0.857
suggestion
496
51
51
false
v26.1.14
1,539
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
) selected_files = [ os.path.join(sentences_dir, f) for f in sentences_ordered if int(start) <= int(os.path.splitext(f)[0]) <= int(end) ] if not selected_files: print('No audio files found in the specified ra...
The chunk_list tuple structure has changed from 5 elements (txt, out, is_gui_process, progress_queue, idx) to 4 elements (txt, out, False, idx), but the assemble_audio_chunks_worker function still expects up to 4 parameters (txt_file, out_file, is_gui_process, job_id). The third element 'False' appears to be the is_gui...
start = int(start) end = int(end) is_gui_process = session.get('is_gui_process') progress_queue = context.progress_queues.get(session_id) sentence_files = [f for f in os.listdir(sentences_dir) if f.endswith(f'.{default_audio_proc_format}')] sentenc...
@@ -1875,95 +1885,79 @@ def combine_audio_sentences(file:str, start:int, end:int, session_id:str)->bool: try: session = context.get_session(session_id) if session: + global progress_queue chapter_audio_file = os.path.join(session['chapters_dir'], file) sentenc...
lib/core.py
26
Python
0.857
suggestion
585
51
51
false
v26.1.14
1,539
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(msg) return None if cur_part and (cur_duration + dur > max_part_duration): part_files.append(cur_part) part_chapter_indices.append(cur_indices) cur_part = [] ...
The chunk_list tuple structure has changed from 5 elements (txt, out, is_gui_process, progress_queue, idx) to 4 elements (txt, out, False, idx), but the assemble_audio_chunks_worker function still expects up to 4 parameters (txt_file, out_file, is_gui_process, job_id). The third element 'False' appears to be the is_gui...
cur_part = [] cur_indices = [] cur_duration = 0 cur_part.append(file) cur_indices.append(idx) cur_duration += dur if cur_part: part_files.append(cur_par...
@@ -2184,104 +2179,92 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin if cur_part: part_files.append(cur_part) part_chapter_indices.append(cur_indices) - temp_export = os.path.join(session['process_dir'], 'expo...
lib/core.py
26
Python
0.857
suggestion
593
51
51
false
v26.1.14
1,539
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
msg = f"{self.session['tts_engine']} custom model not implemented yet!" print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'] engine = self._load_api(self.tts_key, model_path) if engine an...
The condition `(part and sum(c.isalnum() for c in part) < 2)` is redundant because if `not part` is false, then `part` is already truthy. The condition can be simplified to `if not part or sum(c.isalnum() for c in part) < 2:` ```suggestion if not part or sum(c.isalnum() for c in part) < 2: ```
msg = f"{self.session['tts_engine']} custom model not implemented yet!" print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'] engine = self._load_api(self.tts_key, model_path) if engine an...
@@ -59,7 +59,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: self.audio_segments = [] for part in sentence_parts: part = part.strip() - if not part or (part and sum(c.isalnum() for c in part) < 3): + if not part...
lib/classes/tts_engines/yourtts.py
26
Python
0.857
suggestion
314
51
51
false
v26.1.14
1,541
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
hf_sub = '' if self.speakers_path is None: self.speakers_path = hf_hub_download(repo_id=hf_repo, filename='speakers_xtts.pth', cache_dir=self.cache_dir) else: hf_sub = self.models[self.session['fine_t...
The condition `(part and sum(c.isalnum() for c in part) < 2)` is redundant because if `not part` is false, then `part` is already truthy. The condition can be simplified to `if not part or sum(c.isalnum() for c in part) < 2:` ```suggestion if not part or sum(c.isalnum() for c in part) < 2: ```
hf_sub = '' if self.speakers_path is None: self.speakers_path = hf_hub_download(repo_id=hf_repo, filename='speakers_xtts.pth', cache_dir=self.cache_dir) else: hf_sub = self.models[self.session['fine_t...
@@ -69,7 +69,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: self.audio_segments = [] for part in sentence_parts: part = part.strip() - if not part or (part and sum(c.isalnum() for c in part) < 3): + if not part...
lib/classes/tts_engines/xtts.py
26
Python
0.857
suggestion
314
51
51
false
v26.1.14
1,541
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
model_path = self.models[self.session['fine_tuned']]['repo'].replace("[lang_iso1]", iso_dir).replace("[xxx]", sub) self.tts_key = model_path engine = self._load_api(self.tts_key, model_path) else: msg = f...
The condition `(part and sum(c.isalnum() for c in part) < 2)` is redundant because if `not part` is false, then `part` is already truthy. The condition can be simplified to `if not part or sum(c.isalnum() for c in part) < 2:` ```suggestion if not part or sum(c.isalnum() for c in part) < 2: ```
model_path = self.models[self.session['fine_tuned']]['repo'].replace("[lang_iso1]", iso_dir).replace("[xxx]", sub) self.tts_key = model_path engine = self._load_api(self.tts_key, model_path) else: msg = f...
@@ -69,7 +69,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: self.audio_segments = [] for part in sentence_parts: part = part.strip() - if not part or (part and sum(c.isalnum() for c in part) < 3): + if not part...
lib/classes/tts_engines/vits.py
26
Python
0.857
suggestion
314
51
51
false
v26.1.14
1,541
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
d.max_decoder_steps = 1000 # Prevent attention drift d.attention_keeplast = True else: msg = f"{self.session['tts_engine']} checkpoint for {self.session['language']} not found!" pr...
The condition `(part and sum(c.isalnum() for c in part) < 2)` is redundant because if `not part` is false, then `part` is already truthy. The condition can be simplified to `if not part or sum(c.isalnum() for c in part) < 2:` ```suggestion if not part or sum(c.isalnum() for c in part) < 2: ```
d.max_decoder_steps = 1000 # Prevent attention drift d.attention_keeplast = True else: msg = f"{self.session['tts_engine']} checkpoint for {self.session['language']} not found!" pr...
@@ -86,7 +86,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: self.audio_segments = [] for part in sentence_parts: part = part.strip() - if not part or (part and sum(c.isalnum() for c in part) < 3): + if not part...
lib/classes/tts_engines/tacotron.py
26
Python
0.857
suggestion
314
51
51
false
v26.1.14
1,541
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
msg = f"{self.session['tts_engine']} custom model not implemented yet!" print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'].replace("[lang]", self.session['language']) self.tts_key = model_path ...
The condition `(part and sum(c.isalnum() for c in part) < 2)` is redundant because if `not part` is false, then `part` is already truthy. The condition can be simplified to `if not part or sum(c.isalnum() for c in part) < 2:` ```suggestion if not part or sum(c.isalnum() for c in part) < 2: ```
msg = f"{self.session['tts_engine']} custom model not implemented yet!" print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'].replace("[lang]", self.session['language']) self.tts_key = model_path ...
@@ -61,7 +61,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: self.audio_segments = [] for part in sentence_parts: part = part.strip() - if not part or (part and sum(c.isalnum() for c in part) < 3): + if not part...
lib/classes/tts_engines/fairseq.py
26
Python
0.857
suggestion
314
51
51
false
v26.1.14
1,541
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
voice_dir=pth_voice_dir, **fine_tuned_params ) self.engine.to(devices['CPU']['proc']) del result msg = f"Saved file: {pth_voice_file}" ...
The condition `(part and sum(c.isalnum() for c in part) < 2)` is redundant because if `not part` is false, then `part` is already truthy. The condition can be simplified to `if not part or sum(c.isalnum() for c in part) < 2:` ```suggestion if not part or sum(c.isalnum() for c in part) < 2: ```
voice_dir=pth_voice_dir, **fine_tuned_params ) self.engine.to(devices['CPU']['proc']) del result msg = f"Saved file: {pth_voice_file}" ...
@@ -131,7 +131,7 @@ def convert(self, sentence_index:int, sentence:str)->bool: self.audio_segments = [] for part in sentence_parts: part = part.strip() - if not part or (part and sum(c.isalnum() for c in part) < 3): + if not pa...
lib/classes/tts_engines/bark.py
26
Python
0.857
suggestion
314
51
51
false
v26.1.14
1,541
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
def load_json_chapters(filepath:str)->list: try: with open(filepath, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: print(f"load_json_chapters() error: {e}") return [] def save_json_chapters(session_id:str, filepath:str)->bool: try: sessi...
Incorrect syntax: `session.get` is a method and requires parentheses, not brackets. This should be `session.get('cancellation_requested')`. This syntax error appears in 12 locations throughout the file and will cause runtime failures. ```suggestion if session.get('cancellation_requested') or not check_connex(se...
def load_json_chapters(filepath:str)->list: try: with open(filepath, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: print(f"load_json_chapters() error: {e}") return [] def save_json_chapters(session_id:str, filepath:str)->bool: try: sess...
@@ -524,7 +525,7 @@ def save_json_chapters(session_id:str, filepath:str)->bool: def convert2epub(session_id:str)-> bool: session = context.get_session(session_id) if session: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_connex(session_id):
lib/core.py
26
Python
1
bug
334
51
51
false
v25.12.33
1,544
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
def load_json_chapters(filepath:str)->list: try: with open(filepath, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: print(f"load_json_chapters() error: {e}") return [] def save_json_chapters(session_id:str, filepath:str)->bool: try: sessi...
The `check_connex` function is defined as a local function inside `build_interface()` in `lib/gradio.py` and cannot be called from `lib/core.py`. This function needs to be moved to module-level scope in either `lib/core.py` or another importable location to be accessible.
def load_json_chapters(filepath:str)->list: try: with open(filepath, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: print(f"load_json_chapters() error: {e}") return [] def save_json_chapters(session_id:str, filepath:str)->bool: try: sess...
@@ -524,7 +525,7 @@ def save_json_chapters(session_id:str, filepath:str)->bool: def convert2epub(session_id:str)-> bool: session = context.get_session(session_id) if session: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_connex(session_id):
lib/core.py
26
Python
0.643
suggestion
272
51
51
false
v25.12.33
1,544
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
text = text.replace(m, key) tokens = re.findall(r"\w+|[^\w\s]", text, re.UNICODE) buf = [] for t in tokens: if t in protected: buf.append(t) elif re.match(r"^\w+$", t): buf.append(romanize(t)) else: buf.append(t) out = '' for i, t i...
The refactored `filter_sml` function lacks a docstring explaining what SML filtering does and how the new implementation works. Given the complexity of the regex matching and tag processing, documentation would improve maintainability. ```suggestion def filter_sml(text:str)->str: """ Normalize inline SML (speech mark...
protected[key] = m text = text.replace(m, key) tokens = re.findall(r"\w+|[^\w\s]", text, re.UNICODE) buf = [] for t in tokens: if t in protected: buf.append(t) elif re.match(r"^\w+$", t): buf.append(romanize(t)) else: buf.append(t) ...
@@ -1689,20 +1690,21 @@ def romanize(word): out = out.replace(k, v) return out -def filter_sml(text: str) -> str: - text = TTS_SML['###']['match'].sub(' ‡pause‡ ', text) - text = TTS_SML['break']['match'].sub(' ‡break‡ ', text) - text = TTS_SML['pause']['match'].sub( - lambda m: f' ‡pause:{m.group(1)}‡...
lib/core.py
26
Python
1
performance
1,161
51
51
false
v25.12.33
1,544
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
def load_json_chapters(filepath:str)->list: try: with open(filepath, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: print(f"load_json_chapters() error: {e}") return [] def save_json_chapters(session_id:str, filepath:str)->bool: try: sessi...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested', False) or not check_connex(session_id): ```
def load_json_chapters(filepath:str)->list: try: with open(filepath, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: print(f"load_json_chapters() error: {e}") return [] def save_json_chapters(session_id:str, filepath:str)->bool: try: sess...
@@ -524,7 +525,7 @@ def save_json_chapters(session_id:str, filepath:str)->bool: def convert2epub(session_id:str)-> bool: session = context.get_session(session_id) if session: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_connex(session_id):
lib/core.py
26
Python
1
bug
299
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
def get_ebook_title(epubBook:EpubBook,all_docs:list[Any])->str|None: # 1. Try metadata (official EPUB title) meta_title = epubBook.get_metadata('DC','title') if meta_title and meta_title[0][0].strip(): return meta_title[0][0].strip() # 2. Try <title> in the head of the first XHTML document i...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested') or not check_connex(session_id): ```
def get_ebook_title(epubBook:EpubBook,all_docs:list[Any])->str|None: # 1. Try metadata (official EPUB title) meta_title = epubBook.get_metadata('DC','title') if meta_title and meta_title[0][0].strip(): return meta_title[0][0].strip() # 2. Try <title> in the head of the first XHTML document ...
@@ -698,7 +699,7 @@ def get_cover(epubBook:EpubBook, session_id:str)->bool|str: try: session = context.get_session(session_id) if session: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_connex(session_id):
lib/core.py
26
Python
1
bug
296
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if image.mode in ('RGBA', 'P'): image = image.convert('RGB') image.save(cover_path, format = 'JPEG') return cover_path return True except Exception as e: DependencyError(e) return False def get_chapters(epubBook:EpubBoo...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested') or not check_connex(session_id): ```
# Convert to RGB if needed (JPEG doesn't support alpha) if image.mode in ('RGBA', 'P'): image = image.convert('RGB') image.save(cover_path, format = 'JPEG') return cover_path return True except Exception as e: De...
@@ -740,7 +741,7 @@ def get_chapters(epubBook:EpubBook, session_id:str)->list: print(msg) session = context.get_session(session_id) if session: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_connex(session_id):
lib/core.py
26
Python
1
bug
296
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
# Replace ok by 'Owkey' text = re.sub(r'\bok\b', 'Okay', text, flags=re.IGNORECASE) # Escape special characters in the punctuation list for regex pattern = '|'.join(map(re.escape, punctuation_split_hard_set)) # Reduce multiple consecutive punctuations hard text = re.sub(rf'(\s*({pattern})\s*)+',...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested', False) or not check_connex(session_id): ```
# Replace multiple and spaces with single space text = re.sub(r'\s+', ' ', text) # Replace ok by 'Owkey' text = re.sub(r'\bok\b', 'Okay', text, flags=re.IGNORECASE) # Escape special characters in the punctuation list for regex pattern = '|'.join(map(re.escape, punctuation_split_hard_set)) # ...
@@ -1775,7 +1777,7 @@ def convert_chapters2audio(session_id:str)->bool: session = context.get_session(session_id) if session: try: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_connex(session_id):
lib/core.py
26
Python
1
bug
303
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
msg = f"--------------------------------------------------\nA total of {total_chapters} {'block' if total_chapters <= 1 else 'blocks'} and {total_sentences} {'sentence' if total_sentences <= 1 else 'sentences'}.\n--------------------------------------------------" print(msg) if sessi...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested') or not check_connex(session_id): ```
print(error) return False msg = f"--------------------------------------------------\nA total of {total_chapters} {'block' if total_chapters <= 1 else 'blocks'} and {total_sentences} {'sentence' if total_sentences <= 1 else 'sentences'}.\n-------------------------------------...
@@ -1836,7 +1838,7 @@ def convert_chapters2audio(session_id:str)->bool: msg = f'Block {chapter_idx} containing {len(sentences)} sentences…' print(msg) for idx, sentence in enumerate(sentences): - if session['cancellati...
lib/core.py
26
Python
1
bug
312
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
def combine_audio_sentences(file:str, start:int, end:int, session_id:str)->bool: try: session = context.get_session(session_id) if session: global progress_queue chapter_audio_file = os.path.join(session['chapters_dir'], file) sentences_dir = session['sentences_d...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested') or not check_connex(session_id): ```
print(error) return False def combine_audio_sentences(session_id:str, file:str, start:int, end:int)->bool: try: session = context.get_session(session_id) if session: global progress_queue chapter_audio_file = os.path.join(session['chapters_dir'], file...
@@ -1902,9 +1904,8 @@ def combine_audio_sentences(file:str, start:int, end:int, session_id:str)->bool: worker_dir = session['sentences_worker_dir'] os.makedirs(worker_dir, exist_ok=True) chunk_list = [] - total_batches = (len(selected_files)+batch_size-1)//batch_size ...
lib/core.py
26
Python
1
bug
300
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if session['metadata'].get('published'): try: if '.' in session['metadata']['published']: year = datetime.strptime(session['metadata']['published'], '%Y-%m-%dT%H:%M:%S.%f%z').year else: year = datetime.st...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested') or not check_connex(session_id): ```
ffmpeg_metadata += f"{tag('publisher')}={session['metadata']['publisher']}\n" if session['metadata'].get('published'): try: if '.' in session['metadata']['published']: year = datetime.strptime(session['metadata']['published'], '%Y-%...
@@ -2007,7 +2008,7 @@ def tag(key): ffmpeg_metadata += f"{tag('asin')}={asin}\n" start_time = 0 for filename, chapter_title in part_chapters: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_c...
lib/core.py
26
Python
1
bug
300
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
ffmpeg_metadata += f"{tag('asin')}={asin}\n" start_time = 0 for filename, chapter_title in part_chapters: if session['cancellation_requested']: msg = 'Cancel requested' print(msg) return False ...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested') or not check_connex(session_id): ```
if asin: ffmpeg_metadata += f"{tag('asin')}={asin}\n" start_time = 0 for filename, chapter_title in part_chapters: if session.get['cancellation_requested'] or not check_connex(session_id): msg = 'Cancel requested' ...
@@ -2028,7 +2029,7 @@ def tag(key): def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_final_file:str)->bool: try: - if session['cancellation_requested']: + if session.get['cancellation_requested'] or not check_connex(session_id):
lib/core.py
26
Python
1
bug
296
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
chapter_files = sorted(chapter_files, key=lambda x: int(re.search(r'\d+', x).group())) chapter_titles = [c[0] for c in session['chapters']] is_gui_process = session['is_gui_process'] progress_queue = context.progress_queues.get(session_id) if len(chapter_files...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime.
chapter_files = [f for f in os.listdir(session['chapters_dir']) if f.endswith(f'.{default_audio_proc_format}')] chapter_files = sorted(chapter_files, key=lambda x: int(re.search(r'\d+', x).group())) chapter_titles = [c[0] for c in session['chapters']] is_gui_process = ses...
@@ -2163,7 +2164,7 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin max_part_duration = int(session['output_split_hours']) * 3600 needs_split = total_duration > (int(session['output_split_hours']) * 2) * 3600 for idx, (file, dur) in e...
lib/core.py
26
Python
0.714
bug
192
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
cur_duration = 0 max_part_duration = int(session['output_split_hours']) * 3600 needs_split = total_duration > (int(session['output_split_hours']) * 2) * 3600 for idx, (file, dur) in enumerate(zip(chapter_files, durations)): if session['...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime.
cur_indices = [] cur_duration = 0 max_part_duration = int(session['output_split_hours']) * 3600 needs_split = total_duration > (int(session['output_split_hours']) * 2) * 3600 for idx, (file, dur) in enumerate(zip(chapter_files, durations)):...
@@ -2182,9 +2183,8 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin for part_idx, (part_file_list, indices) in enumerate(zip(part_files, part_chapter_indices)): batch_size = 1024 chunk_list = [] - total_batc...
lib/core.py
26
Python
0.714
bug
192
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if not all(results): error = f'assemble_audio_chunks_worker() One or more chunks failed for part {part_idx+1}.' print(error) return None combined_chapters_file = Path(session['process_dir']) / (f"{get_sanitiz...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime.
if not all(results): error = f'assemble_audio_chunks_worker() One or more chunks failed for part {part_idx+1}.' print(error) return None combined_chapters_file = Path(session['process_dir']) / (f"{get_sanitiz...
@@ -2241,7 +2241,7 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin merged_tmp = os.path.join(worker_dir, f'all.{default_audio_proc_format}') with open(txt, 'w') as f: for file in chapter_files: - if session...
lib/core.py
26
Python
0.714
bug
192
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if is_lang_in_tts_engine: session['cover'] = get_cover(epubBook, session_id) if session['cover']: if not session['chapters']: ...
Incorrect syntax for dictionary method call. `session.get` should be called with parentheses: `session.get('cancellation_requested')`. This syntax error will cause the code to fail at runtime. ```suggestion if session.get('cancellation_requested') or not check_connex(session_id): ```
if is_lang_in_tts_engine: session['cover'] = get_cover(epubBook, session_id) if session['cover']: if not session['chapters']: ...
@@ -2657,7 +2657,7 @@ def convert_ebook(args:dict)->tuple: error = f"Temporary directory {session['process_dir']} not removed due to failure." else: error = f"Language {args['language']} is not supported." - if session['cancellation_requested']: + ...
lib/core.py
26
Python
1
bug
292
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
out += t else: if re.match(r"^\w+$", buf[i-1]) and re.match(r"^\w+$", t): out += ' ' + t else: out += t for k, v in protected.items(): out = out.replace(k, v) return out def filter_sml(text: str) -> str: text = TTS_SML['###'][...
The variable `SML_TAG` is not imported. It's defined in `lib/conf_models.py` but not exported through `lib/__init__.py`. Add `SML_TAG` to the imports in `lib/__init__.py` to make it accessible.
if i == 0: out += t else: if re.match(r"^\w+$", buf[i-1]) and re.match(r"^\w+$", t): out += ' ' + t else: out += t for k, v in protected.items(): out = out.replace(k, v) return out def filter_sml(text:str)->str: def c...
@@ -1689,20 +1690,21 @@ def romanize(word): out = out.replace(k, v) return out -def filter_sml(text: str) -> str: - text = TTS_SML['###']['match'].sub(' ‡pause‡ ', text) - text = TTS_SML['break']['match'].sub(' ‡break‡ ', text) - text = TTS_SML['pause']['match'].sub( - lambda m: f' ‡pause:{m.group(1)}‡...
lib/core.py
26
Python
0.5
suggestion
193
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
tmp_fh = tempfile.NamedTemporaryFile(dir=resample_tmp, suffix=".wav", delete=False) tmp_path = tmp_fh.name tmp_fh.close() sf.write(tmp_path,wav_numpy,expected_sr,subtype="PCM_16") return tmp_path def _set_voice(self)->bool: self.params['voice_path'] = ( s...
The variable `SML_TAG` is not imported. It's defined in `lib/conf_models.py` but not exported through `lib/__init__.py`. Add `SML_TAG` to the imports in `lib/__init__.py` to make it accessible.
wav_numpy = wav_tensor.cpu().numpy() resample_tmp = os.path.join(self.session['process_dir'], 'tmp') os.makedirs(resample_tmp, exist_ok=True) tmp_fh = tempfile.NamedTemporaryFile(dir=resample_tmp, suffix=".wav", delete=False) tmp_path = tmp_fh.name tmp_fh.close() ...
@@ -408,36 +411,45 @@ def _set_voice(self)->bool: return False return True - def _convert_sml(self, sml: str) -> bool: - for name, spec in TTS_SML.items(): - if spec.get("close_match") and spec["close_match"].fullmatch(sml): - if name == "voice": - ...
lib/classes/tts_engines/common/utils.py
26
Python
0.5
suggestion
193
51
51
false
v26.1.14
1,545
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
rf'\b({"|".join(map(re.escape, chapter_words))})\s+([IVXLCDM]+)\b', re.IGNORECASE | re.UNICODE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(\s+)', repl_heading, text, flags=re.MULTILINE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(?:\s*)$', ...
Duplicate imports are added in the middle of the file. The modules `unicodedata`, `regex as re`, `unidecode`, and `phonemizer` are already imported at the top of the file (lines 10, 11, 38, 39). These duplicate imports should be removed. ```suggestion ```
flags=re.MULTILINE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(?:\s*)$', repl_standalone, text, flags=re.MULTILINE ) text = chapter_words_re.sub(repl_chapter_single, text) text = re.sub( r'(?<!\S)([IVXLCDM]{2,})(?!\S)', repl_word, tex...
@@ -1610,11 +1603,19 @@ def repl_chapter_single(m: re.Match)->str: ) return text -def is_latin(s: str)->bool: +def is_latin(s:str)->bool: return all((u'a' <= ch.lower() <= 'z') or ch.isdigit() or not ch.isalpha() for ch in s) -def foreign2latin(text, base_lang): - def script_of(word): +from ty...
lib/core.py
26
Python
0.857
refactor
256
51
51
false
v25.12.33
1,547
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
chapter_words = sorted( {w for words in chapter_word_mapping.values() for w in words}, key=len, reverse=True ) chapter_words_re = re.compile( rf'\b({"|".join(map(re.escape, chapter_words))})\s+([IVXLCDM]+)\b', re.IGNORECASE | re.UNICODE ) text = re.sub( ...
The import `from typing import Dict` is redundant as `Dict` is already imported at line 13 via `from typing import Any, TypeAlias, Generator, Callable, Iterable, Dict`. This duplicate import should be removed. ```suggestion ```
re.IGNORECASE | re.UNICODE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(\s+)', repl_heading, text, flags=re.MULTILINE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(?:\s*)$', repl_standalone, text, flags=re.MULTILINE ) text ...
@@ -1610,11 +1603,19 @@ def repl_chapter_single(m: re.Match)->str: ) return text -def is_latin(s: str)->bool: +def is_latin(s:str)->bool: return all((u'a' <= ch.lower() <= 'z') or ch.isdigit() or not ch.isalpha() for ch in s) -def foreign2latin(text, base_lang): - def script_of(word): +from ty...
lib/core.py
26
Python
1
refactor
228
51
51
false
v25.12.33
1,547
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if next_clean and sum(c.isalnum() for c in next_clean) < 3: s = f"{s} {next_s}" i += 2 else: i += 1 else: i += 1 if len(strip_sml(s)) <= max_chars: soft_list.append(s) ...
The comment '# ← rename variable' is a development note that should be removed before merging. It's not meaningful documentation for the code. ```suggestion current_len = len(strip_sml(rest)) ```
if len(strip_sml(s)) <= max_chars: soft_list.append(s) continue parts = split_inclusive(s, soft_pattern) if parts: valid = False for p in parts: if len(strip_sml(p.strip())) <= max_chars: ...
@@ -1229,8 +1222,8 @@ def join_ideogramms(idg_list:list[str])->str: continue rest = s while rest: - clean_len = len(strip_sml(rest)) - if clean_len <= max_chars: + current_len = len(strip_sml(rest)) # ← rename variable
lib/core.py
26
Python
0.857
suggestion
211
51
51
false
v25.12.33
1,547
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(error) return None return sentences return None except Exception as e: error = f'filter_chapter() error: {e}' DependencyError(error) return None def get_sentences(text:str, session_id:str)->list|None: def split_inclusive(text:st...
There is trailing whitespace on line 1095. This should be removed for code cleanliness. ```suggestion ```
print(error) return None return sentences return None except Exception as e: error = f'filter_chapter() error: {e}' DependencyError(error) return None def get_sentences(text:str, session_id:str)->list|None: def split_inclusive(text:st...
@@ -1091,11 +1091,10 @@ def split_inclusive(text:str, pattern:re.Pattern[str])->list[str]: return result def strip_sml(s:str)->str: - if not sml_values: - return s - for v in sml_values: - s = s.replace(v, '') - return s + return SML_TAG_PATTERN.sub('', ...
lib/core.py
26
Python
0.786
suggestion
106
51
51
false
v25.12.33
1,547
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
if scr == 'latin': return word try: if scr == 'chinese': from pypinyin import pinyin, Style return ''.join(x[0] for x in pinyin(word, style=Style.NORMAL)) if scr == 'japanese': import pykakasi k = pykakas...
The comment refers to 'the global grammar' which is unclear. Consider rephrasing to 'using the SML_TAG_PATTERN regex' for clarity. ```suggestion # Protect ALL SML tags using the SML_TAG_PATTERN regex ```
scr = script_of(word) if scr == 'latin': return word try: if scr == 'chinese': from pypinyin import pinyin, Style return ''.join(x[0] for x in pinyin(word, style=Style.NORMAL)) if scr == 'japanese': import pykaka...
@@ -1655,34 +1656,30 @@ def romanize(word): if scr == 'cyrillic': return unidecode(phonemize(word, language='ru', backend='espeak')) return unidecode(word) - except: + except Exception: return unidecode(word) - tts_markers = { - v['token'...
lib/core.py
26
Python
0.857
suggestion
207
51
51
false
v25.12.33
1,547
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
proxy_dict[key] = self._recursive_proxy(value, manager) return proxy_dict elif isinstance(data, list): proxy_list = manager.list() for item in data: proxy_list.append(self._recursive_proxy(item, manager)) return proxy_list e...
The heartbeat is initialized to 120 seconds in the future but is no longer used or updated anywhere in the code after the removal of check_connex and heartbeat updates. This field should either be removed entirely or documented if it's still needed for future functionality. ```suggestion ```
proxy_dict[key] = self._recursive_proxy(value, manager) return proxy_dict elif isinstance(data, list): proxy_list = manager.list() for item in data: proxy_list.append(self._recursive_proxy(item, manager)) return proxy_list e...
@@ -131,7 +131,7 @@ def set_session(self, session_id:str)->Any: "status": None, "event": None, "ticker": 0, - "heartbeat": 0, + "heartbeat": time.time() + 120,
lib/core.py
26
Python
0.857
suggestion
293
51
51
false
v25.12.33
1,547
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
return unidecode(word) if scr == 'arabic': return unidecode(phonemize(word, language='ar', backend='espeak')) if scr == 'cyrillic': return unidecode(phonemize(word, language='ru', backend='espeak')) return unidecode(word) except...
Added explicit type annotations for variables in the function scope. While this improves code clarity, the type annotations use both old-style (Dict[str, str]) and new-style (list[str]) syntax. For consistency, consider using either all old-style (List[str], Dict[str, str]) or all new-style (list[str], dict[str, str]) ...
if scr == 'hangul': return unidecode(word) if scr == 'arabic': return unidecode(phonemize(word, language='ar', backend='espeak')) if scr == 'cyrillic': return unidecode(phonemize(word, language='ru', backend='espeak')) retur...
@@ -1655,34 +1656,30 @@ def romanize(word): if scr == 'cyrillic': return unidecode(phonemize(word, language='ru', backend='espeak')) return unidecode(word) - except: + except Exception: return unidecode(word) - tts_markers = { - v['token'...
lib/core.py
26
Python
0.643
suggestion
344
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'] engine = self._load_api(self.tts_key, model_path) if engine and engine is not None: msg = f'TTS {self.tts_key} Loaded!' re...
The condition logic has been simplified by removing the redundant check 'part and sum(c.isalnum() for c in part) < 2'. The new logic only checks 'if not part' which is cleaner. However, this removes the validation that parts with fewer than 2 alphanumeric characters are skipped. Verify that this doesn't cause issues wi...
msg = f"{self.session['tts_engine']} custom model not implemented yet!" print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'] engine = self._load_api(self.tts_key, model_path) if engine an...
@@ -55,13 +56,13 @@ def convert(self, sentence_index:int, sentence:str)->bool: final_sentence_file = os.path.join(self.session['sentences_dir'], f'{sentence_index}.{default_audio_proc_format}') device = devices['CUDA']['proc'] if self.session['device'] in ['cuda', 'jetson'] else self.s...
lib/classes/tts_engines/yourtts.py
26
Python
0.857
suggestion
449
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'].replace("[lang]", self.session['language']) self.tts_key = model_path engine = self._load_api(self.tts_key, model_path) if engine and ...
The condition logic has been simplified by removing the redundant check 'part and sum(c.isalnum() for c in part) < 2'. The new logic only checks 'if not part' which is cleaner. However, this removes the validation that parts with fewer than 2 alphanumeric characters are skipped. Verify that this doesn't cause issues wi...
msg = f"{self.session['tts_engine']} custom model not implemented yet!" print(msg) else: model_path = self.models[self.session['fine_tuned']]['repo'].replace("[lang]", self.session['language']) self.tts_key = model_path ...
@@ -57,13 +58,13 @@ def convert(self, sentence_index:int, sentence:str)->bool: if self.engine: final_sentence_file = os.path.join(self.session['sentences_dir'], f'{sentence_index}.{default_audio_proc_format}') device = devices['CUDA']['proc'] if self.session['device'] in [...
lib/classes/tts_engines/fairseq.py
26
Python
0.857
suggestion
449
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
while rest: clean_len = len(strip_sml(rest)) if clean_len <= max_chars: last_list.append(rest.strip()) break cut = rest[:max_chars + 1] idx = cut.rfind(' ') if idx > 0: ...
The merge logic has been significantly changed. The previous logic checked 'clean_len(s) <= merge_max_chars' before merging, but the new logic checks 'clean_len(prev) + clean_len(s) <= merge_max_chars * 2'. This changes the merging behavior - previously it only merged short segments (less than 1/8 of max_chars), now it...
if idx > 0: left = rest[:idx].strip() right = rest[idx + 1:].strip() else: left = rest[:max_chars].strip() right = rest[max_chars:].strip() if not left or right == rest: la...
@@ -1254,37 +1247,38 @@ def join_ideogramms(idg_list:list[str])->str: s = s.strip() if not s: continue - clean_len = len(strip_sml(s)) - if merge_list and clean_len <= merge_max_chars: - sep = TTS_SML['pause']['token'] if len(merge_list) ==...
lib/core.py
26
Python
0.5
suggestion
463
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
hf_sub = '' if self.speakers_path is None: self.speakers_path = hf_hub_download(repo_id=hf_repo, filename='speakers_xtts.pth', cache_dir=self.cache_dir) else: hf_sub = self.models[self.session['fine_t...
The condition logic has been simplified by removing the redundant check 'part and sum(c.isalnum() for c in part) < 2'. The new logic only checks 'if not part' which is cleaner. However, this removes the validation that parts with fewer than 2 alphanumeric characters are skipped. Verify that this doesn't cause issues wi...
hf_sub = '' if self.speakers_path is None: self.speakers_path = hf_hub_download(repo_id=hf_repo, filename='speakers_xtts.pth', cache_dir=self.cache_dir) else: hf_sub = self.models[self.session['fine_t...
@@ -65,13 +65,13 @@ def convert(self, sentence_index:int, sentence:str)->bool: if self.engine: final_sentence_file = os.path.join(self.session['sentences_dir'], f'{sentence_index}.{default_audio_proc_format}') device = devices['CUDA']['proc'] if self.session['device'] in [...
lib/classes/tts_engines/xtts.py
26
Python
0.857
suggestion
449
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
self.tts_key = model_path engine = self._load_api(self.tts_key, model_path) else: msg = f"{self.session['tts_engine']} checkpoint for {self.session['language']} not found!" print(msg) if engin...
The condition logic has been simplified by removing the redundant check 'part and sum(c.isalnum() for c in part) < 2'. The new logic only checks 'if not part' which is cleaner. However, this removes the validation that parts with fewer than 2 alphanumeric characters are skipped. Verify that this doesn't cause issues wi...
model_path = self.models[self.session['fine_tuned']]['repo'].replace("[lang_iso1]", iso_dir).replace("[xxx]", sub) self.tts_key = model_path engine = self._load_api(self.tts_key, model_path) else: msg = f...
@@ -65,13 +66,13 @@ def convert(self, sentence_index:int, sentence:str)->bool: if self.engine: device = devices['CUDA']['proc'] if self.session['device'] in ['cuda', 'jetson'] else self.session['device'] final_sentence_file = os.path.join(self.session['sentences_dir'], f'{...
lib/classes/tts_engines/vits.py
26
Python
0.857
suggestion
449
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
chapter_audio_file = f'chapter_{chapter_idx}.{default_audio_proc_format}' sentences = session['chapters'][c] start = idx_target if c in missing_chapters: msg = f'********* Recovering missing block...
The SML detection logic has been refactored to use 'SML_TAG_PATTERN.fullmatch()' instead of iterating through 'TTS_SML.values()'. While this is cleaner and more maintainable, ensure that the pattern correctly matches all valid SML tags, including the special '###' case which is now explicitly checked with 'or sentence ...
ebook_name = Path(session['ebook']).name final_sentences = [] with tqdm(total=total_iterations, desc='0.00%', bar_format='{desc}: {n_fmt}/{total_fmt} ', unit='step', initial=0) as t: idx_target = 0 for c in range(0, total_chapters):...
@@ -1838,13 +1844,14 @@ def convert_chapters2audio(session_id:str)->bool: msg = f'Block {chapter_idx} containing {len(sentences)} sentences…' print(msg) for idx, sentence in enumerate(sentences): - if session.get['canc...
lib/core.py
26
Python
0.5
refactor
330
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
# Prevent attention drift d.attention_keeplast = True else: msg = f"{self.session['tts_engine']} checkpoint for {self.session['language']} not found!" print(msg) if engine and engine is not No...
The condition logic has been simplified by removing the redundant check 'part and sum(c.isalnum() for c in part) < 2'. The new logic only checks 'if not part' which is cleaner. However, this removes the validation that parts with fewer than 2 alphanumeric characters are skipped. Verify that this doesn't cause issues wi...
d.max_decoder_steps = 1000 # Prevent attention drift d.attention_keeplast = True else: msg = f"{self.session['tts_engine']} checkpoint for {self.session['language']} not found!" pr...
@@ -82,13 +83,13 @@ def convert(self, sentence_index:int, sentence:str)->bool: if self.engine: final_sentence_file = os.path.join(self.session['sentences_dir'], f'{sentence_index}.{default_audio_proc_format}') device = devices['CUDA']['proc'] if self.session['device'] in [...
lib/classes/tts_engines/tacotron.py
26
Python
0.857
suggestion
454
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
rf'\b({"|".join(map(re.escape, chapter_words))})\s+([IVXLCDM]+)\b', re.IGNORECASE | re.UNICODE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(\s+)', repl_heading, text, flags=re.MULTILINE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(?:\s*)$', ...
Duplicate imports detected. The imports for 'Dict' from typing, 'unicodedata', 'regex as re', 'unidecode', and 'phonemizer' are already present at the top of the file (lines 10-11, 13, 38-39). These redundant imports should be removed. ```suggestion ```
flags=re.MULTILINE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(?:\s*)$', repl_standalone, text, flags=re.MULTILINE ) text = chapter_words_re.sub(repl_chapter_single, text) text = re.sub( r'(?<!\S)([IVXLCDM]{2,})(?!\S)', repl_word, tex...
@@ -1610,11 +1603,19 @@ def repl_chapter_single(m: re.Match)->str: ) return text -def is_latin(s: str)->bool: +def is_latin(s:str)->bool: return all((u'a' <= ch.lower() <= 'z') or ch.isdigit() or not ch.isalpha() for ch in s) -def foreign2latin(text, base_lang): - def script_of(word): +from ty...
lib/core.py
26
Python
0.857
refactor
254
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
**fine_tuned_params ) self.engine.to(devices['CPU']['proc']) del result msg = f"Saved file: {pth_voice_file}" print(msg) return True els...
The condition logic has been simplified by removing the redundant check 'part and sum(c.isalnum() for c in part) < 2'. The new logic only checks 'if not part' which is cleaner. However, this removes the validation that parts with fewer than 2 alphanumeric characters are skipped. Verify that this doesn't cause issues wi...
voice_dir=pth_voice_dir, **fine_tuned_params ) self.engine.to(devices['CPU']['proc']) del result msg = f"Saved file: {pth_voice_file}" ...
@@ -127,13 +128,13 @@ def convert(self, sentence_index:int, sentence:str)->bool: if self.engine: device = devices['CUDA']['proc'] if self.session['device'] in ['cuda', 'jetson'] else self.session['device'] final_sentence_file = os.path.join(self.session['sentences_dir'], f...
lib/classes/tts_engines/bark.py
26
Python
0.857
suggestion
449
51
51
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
"ru_speaker_8": "Speaker 8", "ru_speaker_9": "Speaker 9", "tr_speaker_0": "Speaker 0", "tr_speaker_1": "Speaker 1", "tr_speaker_2": "Speaker 2", "tr_speaker_3": "Speaker 3", "tr_speaker_4": "Speaker 4", "tr_speaker_5": "Speaker 5", "tr_speaker_6": "Speaker 6", "tr_spea...
Dutch language support (nld) has been removed from TACOTRON2 engine. This removes 'nl' from the supported languages list and drops 'mai/tacotron2-DDC' from supporting Dutch in tacotron_presets.py. Ensure this removal is intentional and users depending on Dutch TTS with TACOTRON2 have alternative options or are properly...
"tr_speaker_1": "Speaker 1", "tr_speaker_2": "Speaker 2", "tr_speaker_3": "Speaker 3", "tr_speaker_4": "Speaker 4", "tr_speaker_5": "Speaker 5", "tr_speaker_6": "Speaker 6", "tr_speaker_7": "Speaker 7", "tr_speaker_8": "Speaker 8", "tr_speaker_9": "Speaker 9", "zh_spea...
@@ -158,7 +157,7 @@ "rating": {"VRAM": 2, "CPU": 4, "RAM": 4, "Realism": 4} }, TTS_ENGINES['TACOTRON2']: { - "languages": {"deu": "de", "eng": "en", "fra": "fr", "jpn": "ja", "nld": "nl", "spa": "es", "zho": "zh-CN"}, + "languages": {"deu": "de", "eng": "en", "fra": "fr", "jpn": "ja...
lib/conf_models.py
26
Python
0.857
suggestion
489
40
39
false
v26.1.15
1,548
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
re.IGNORECASE | re.UNICODE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(\s+)', repl_heading, text, flags=re.MULTILINE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(?:\s*)$', repl_standalone, text, flags=re.MULTILINE ) text ...
These imports are already present at the top of the file (lines 10-11, 13, 38-39). The duplicate imports should be removed. ```suggestion ```
flags=re.MULTILINE ) text = re.sub( r'^(?:\s*)([IVXLCDM]+)([.-])(?:\s*)$', repl_standalone, text, flags=re.MULTILINE ) text = chapter_words_re.sub(repl_chapter_single, text) text = re.sub( r'(?<!\S)([IVXLCDM]{2,})(?!\S)', repl_word, tex...
@@ -1609,11 +1603,19 @@ def repl_chapter_single(m: re.Match)->str: ) return text -def is_latin(s: str)->bool: +def is_latin(s:str)->bool: return all((u'a' <= ch.lower() <= 'z') or ch.isdigit() or not ch.isalpha() for ch in s) -def foreign2latin(text, base_lang): - def script_of(word): +from ty...
lib/core.py
26
Python
0.786
refactor
142
51
51
false
v26.1.15
1,549
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
for key, value in data.items(): proxy_dict[key] = self._recursive_proxy(value, manager) return proxy_dict elif isinstance(data, list): proxy_list = manager.list() for item in data: proxy_list.append(self._recursive_proxy(item, manag...
The heartbeat initialization was changed from `time.time() + 120` to `time.time()`, which means the heartbeat starts as already expired (in the past). This will cause issues if heartbeat checking logic expects an initial grace period. The original `+ 120` provided a 120-second initial timeout window. ```suggestion ...
proxy_dict[key] = self._recursive_proxy(value, manager) return proxy_dict elif isinstance(data, list): proxy_list = manager.list() for item in data: proxy_list.append(self._recursive_proxy(item, manager)) return proxy_list e...
@@ -131,8 +130,7 @@ def set_session(self, session_id:str)->Any: "status": None, "event": None, "ticker": 0, - "heartbeat": time.time() + 120, - "progress_queue": None, + "heartbeat": time.time(),
lib/core.py
26
Python
0.857
suggestion
363
51
51
false
v25.12.33
1,553
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
out = os.path.join(worker_dir, f'chunk_{i:04d}.{default_audio_proc_format}') with open(txt, 'w') as f: for file in batch: f.write(f"file '{file.replace(os.sep, '/')}'\n") chunk_list.append((str(txt), str(out), False, idx)) ...
This line is extremely long (over 180 characters) and difficult to read. Consider breaking this into multiple lines for better readability, especially given the complex tuple of arguments. ```suggestion async_results.append( pool.apply_async( assem...
if session['cancellation_requested']: msg = 'Cancel requested' print(msg) return False batch = selected_files[i:i + batch_size] txt = os.path.join(worker_dir, f'chunk_{i:04d}.txt') out = os.path.j...
@@ -1922,15 +1928,22 @@ def combine_audio_sentences(session_id:str, file:str, start:int, end:int)->bool: with open(txt, 'w') as f: for file in batch: f.write(f"file '{file.replace(os.sep, '/')}'\n") - chunk_list.append((str(txt), str(out), Fa...
lib/core.py
26
Python
0.857
suggestion
699
51
51
false
v25.12.33
1,553
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
txt = os.path.join(worker_dir, f'part{part_idx+1}_chunk_{i:04d}.txt') out = os.path.join(worker_dir, f'part{part_idx+1}_chunk_{i:04d}.{default_audio_proc_format}') with open(txt, 'w') as f: for file in batch: ...
This line is excessively long (over 300 characters) with deeply nested ternary operations. This is extremely difficult to read and maintain. The path construction should be extracted to a separate variable before the pool.apply_async call. ```suggestion output_filename = ( ...
if session['cancellation_requested']: msg = 'Cancel requested' print(msg) return None batch = part_file_list[i:i + batch_size] txt = os.path.join(worker_dir, f'part...
@@ -2202,14 +2207,21 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin for file in batch: path = Path(session['chapters_dir']) / file f.write(f"file '{path.as_posix()}'\n") - ...
lib/core.py
26
Python
0.857
security
1,226
51
51
false
v25.12.33
1,553
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
for file in chapter_files: if session['cancellation_requested']: msg = 'Cancel requested' print(msg) return None path = os.path.join(session['chapters_dir'], file).repl...
Performance consideration: Adding maxtasksperchild=1 to the Pool constructor will cause each worker process to be recycled after completing one task. While this can help with memory leaks and ensures clean state, it adds overhead from process creation/destruction. Consider if this is necessary or if a higher value (e.g...
final_file = Path(session['audiobooks_dir']) / (f"{session['final_name'].rsplit('.', 1)[0]}_part{part_idx+1}.{session['output_format']}" if needs_split else session['final_name']) if export_audio(str(combined_chapters_file), str(metadata_file), str(final_file)): ...
@@ -2254,7 +2261,32 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin return None path = os.path.join(session['chapters_dir'], file).replace("\\", "/") f.write(f"file '{path}'\n") - if not ass...
lib/core.py
26
Python
1
performance
486
51
51
false
v26.1.15
1,554
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
print(msg) return None batch = part_file_list[i:i + batch_size] txt = os.path.join(worker_dir, f'part{part_idx+1}_chunk_{i:04d}.txt') out = os.path.join(worker_dir, f'part{part_idx+1}_chunk_{i...
Potential bug: The code attempts to clear the progress_queue, but if progress_queue is None (when session_id is not found in context.progress_queues), this will raise an AttributeError when calling .empty() on None. Consider adding a None check before attempting to clear the queue. ```suggestion if ...
batch_size = 1024 chunk_list = [] for idx, i in enumerate(range(0, len(part_file_list), batch_size)): if session['cancellation_requested']: msg = 'Cancel requested' print(msg) ...
@@ -2202,14 +2207,21 @@ def export_audio(ffmpeg_combined_audio:str, ffmpeg_metadata_file:str, ffmpeg_fin for file in batch: path = Path(session['chapters_dir']) / file f.write(f"file '{path.as_posix()}'\n") - ...
lib/core.py
26
Python
1
bug
588
51
51
false
v26.1.15
1,554
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
last_list.append(left) rest = right # PASS 4 — merge very short rows merge_list = [] merge_max_chars = int((max_chars / 2) / 4) for s in last_list: s = s.strip() if not s: continue if merge_list: ...
Inconsistent separator: The merge logic now uses a space " " as a separator when merging sentences, but in the previous version it used sml_token('pause') for backward merge. This could change the audio playback behavior, as pauses between merged sentences would be removed. Consider whether this is the intended behavio...
# PASS 4 — merge very short rows merge_list = [] merge_max_chars = int((max_chars / 2) / 3) i = 0 n = len(last_list) while i < n: s = last_list[i].strip() if not s: i += 1 continue cur_len = clean_len(s)...
@@ -1242,18 +1240,34 @@ def join_ideogramms(idg_list:list[str])->str: # PASS 4 — merge very short rows merge_list = [] - merge_max_chars = int((max_chars / 2) / 4) - for s in last_list: - s = s.strip() + merge_max_chars = int((max_chars / 2) / 3) + i = 0 + ...
lib/core.py
26
Python
0.857
suggestion
823
51
51
false
v26.1.15
1,554
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
# PASS 3 — space split (last resort) last_list = [] for s in soft_list: s = s.strip() if not s: continue rest = s while rest: current_len = len(strip_sml(rest)) # ← rename variable if current_len <=...
Magic number: The divisor has been changed from 4 to 3. While this appears to adjust the character limits for merging very short rows, the reasoning behind this specific value is unclear. Consider adding a comment explaining why this particular value was chosen and what effect it has on the text merging behavior. ```su...
for s in soft_list: s = s.strip() if not s: continue rest = s while rest: current_len = len(strip_sml(rest)) # ← rename variable if current_len <= max_chars: last_list.append(rest.strip()) ...
@@ -1242,18 +1240,34 @@ def join_ideogramms(idg_list:list[str])->str: # PASS 4 — merge very short rows merge_list = []
lib/core.py
26
Python
0.857
suggestion
742
51
51
false
v26.1.15
1,554
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
import argparse, socket, multiprocessing, sys, warnings from lib.conf import * from lib.conf_lang import default_language_code from lib.conf_models import TTS_ENGINES, default_fine_tuned, default_engine_settings warnings.filterwarnings("ignore", category=SyntaxWarning) warnings.filterwarnings("ignore", category=UserW...
Changed multiprocessing start method from "fork" to "spawn" for macOS. This is a significant change that could affect behavior. The "spawn" method is safer and more compatible with certain libraries but can be slower. Ensure this change has been tested on macOS systems, especially with any libraries that may have relie...
import argparse, socket, multiprocessing, sys, warnings from lib.conf import * from lib.conf_lang import default_language_code from lib.conf_models import TTS_ENGINES, default_fine_tuned, default_engine_settings warnings.filterwarnings("ignore", category=SyntaxWarning) warnings.filterwarnings("ignore", category=UserW...
@@ -10,7 +10,7 @@ def init_multiprocessing(): if sys.platform.startswith("darwin"): try: - multiprocessing.set_start_method("fork") + multiprocessing.set_start_method("spawn")
app.py
13
Python
0.5
performance
340
38
38
false
v26.1.15
1,554
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL
close = m.group("close") value = m.group("value") if tag == "###": silence_time = float(int(np.random.uniform(1.0, 1.6) * 100) / 100) self.audio_segments.append( torch.zeros(1, int(self.params['samplerate'] * silence_time)).clone() ) ...
Potential bug: When closing a voice tag, the code now calls _set_voice() without first resetting self.params['voice_path']. This means the temporary voice set within the voice tag will persist after the closing tag, rather than reverting to the original voice. This changes the behavior from the previous version where v...
close = m.group("close") value = m.group("value") if tag == "###": silence_time = float(int(np.random.uniform(1.0, 1.6) * 100) / 100) self.audio_segments.append( torch.zeros(1, int(self.params['samplerate'] * silence_time)).clone() ) ...
@@ -437,7 +437,6 @@ def _convert_sml(self, sml:str)->bool: return True elif tag == "voice": if close:
lib/classes/tts_engines/common/utils.py
26
Python
1
bug
604
51
51
false
v26.1.15
1,554
DrewThomasson/ebook2audiobook
13,365
Python
Copilot
ROBERT-MCDOWELL