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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
h.Buf.LastSearch = resp
h.Buf.LastSearchRegex = useRegex
h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
} else {
h.Cursor.ResetSelection()
InfoBar.Message("No matches found")
}
} else {
h.Cursor.ResetSelection()
}
}
pattern := string(h.Cursor.GetSelection())
if useRegex &&... | No issues found. | h.Buf.LastSearch = resp
h.Buf.LastSearchRegex = useRegex
h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
} else {
h.Cursor.ResetSelection()
InfoBar.Message("No matches found")
}
} else {
h.Cursor.ResetSelection()
}
}
pattern := string(h.Cursor.GetSelection())
if useRegex &&... | @@ -1864,7 +1864,7 @@ func (h *BufPane) CommandMode() bool {
// ToggleOverwriteMode lets the user toggle the text overwrite mode
func (h *BufPane) ToggleOverwriteMode() bool {
- h.isOverwriteMode = !h.isOverwriteMode
+ h.Buf.OverwriteMode = !h.Buf.OverwriteMode
return true
}
| internal/action/actions.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | statusline: Provide `overwrite` mode indicator | 3,620 | zyedidia/micro | 13,805 | Go | JoeKar | |
}
}
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
return nil
}
syndef, err := highlight.ParseDef(file, header)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
retu... | No issues found. | }
}
file, err := highlight.ParseFile(data)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
return nil
}
syndef, err := highlight.ParseDef(file, header)
if err != nil {
screen.TermMessage("Error parsing syntax file " + f.Name() + ": " + err.Error())
retu... | @@ -620,6 +620,16 @@ func (b *Buffer) WordAt(loc Loc) []byte {
return b.Substr(start, end)
}
+// Shared returns if there are other buffers with the same file as this buffer
+func (b *Buffer) Shared() bool {
+ for _, buf := range OpenBuffers {
+ if buf != b && buf.SharedBuffer == b.SharedBuffer {
+ return true
+... | internal/buffer/buffer.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | Skip save on `open` or `term` command if buffer is shared | 3,719 | zyedidia/micro | 13,805 | Go | niten94 | |
if err != nil {
return err
}
return os.Remove(backup)
} else if choice%3 == 1 {
// delete
return os.Remove(backup)
} else if choice%3 == 2 {
// abort
return errors.New("Aborted")
}
}
}
return nil
}
func exit(rc int) {
for _, b := range buffer.OpenBuffers {
if !b.Modifie... | No issues found. | if err != nil {
return err
}
return os.Remove(backup)
} else if choice%3 == 1 {
// delete
return os.Remove(backup)
} else if choice%3 == 2 {
// abort
return errors.New("Aborted")
}
}
}
return nil
}
func exit(rc int) {
for _, b := range buffer.OpenBuffers {
if !b.Modifie... | @@ -374,11 +374,6 @@ func main() {
action.InitBindings()
action.InitCommands()
- err = config.InitColorscheme()
- if err != nil {
- screen.TermMessage(err)
- }
-
err = config.RunPluginFn("preinit")
if err != nil {
screen.TermMessage(err)
@@ -407,6 +402,11 @@ func main() {
screen.TermMessage(err)
}
... | cmd/micro/micro.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | Fix non-working colorscheme plugins | 3,761 | zyedidia/micro | 13,805 | Go | dmaluka | |
assignable := false
switch option {
case "pluginrepos", "pluginchannels":
assignable = valType.AssignableTo(reflect.TypeOf(interfaceArr))
default:
assignable = defType.AssignableTo(valType)
}
if !assignable {
return fmt.Errorf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", opt... | No issues found. | assignable := false
switch option {
case "pluginrepos", "pluginchannels":
assignable = valType.AssignableTo(reflect.TypeOf(interfaceArr))
default:
assignable = defType.AssignableTo(valType)
}
if !assignable {
return fmt.Errorf("Error: setting '%s' has incorrect type (%s), using default value: %v (%s)", opt... | @@ -139,8 +139,9 @@ var LocalSettings = []string{
}
var (
- ErrInvalidOption = errors.New("Invalid option")
- ErrInvalidValue = errors.New("Invalid value")
+ ErrInvalidOption = errors.New("Invalid option")
+ ErrInvalidValue = errors.New("Invalid value")
+ ErrOptNotToggleable = errors.New("Option not togglea... | internal/config/settings.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | Add toggle & togglelocal command | 3,783 | zyedidia/micro | 13,805 | Go | cutelisp | |
// Call Sync() on the file to make sure the content is safely on disk.
f := wf.writeCloser.(*os.File)
err = f.Sync()
}
return size, err
}
func (wf wrappedFile) Close() error {
err := wf.writeCloser.Close()
if wf.withSudo {
// wait for dd to finish and restart the screen if we used sudo
err := wf.cmd.Wait... | No issues found. | // Call Sync() on the file to make sure the content is safely on disk.
f := wf.writeCloser.(*os.File)
err = f.Sync()
}
return size, err
}
func (wf wrappedFile) Close() error {
err := wf.writeCloser.Close()
if wf.withSudo {
// wait for dd to finish and restart the screen if we used sudo
err := wf.cmd.Wait... | @@ -331,6 +331,10 @@ func (b *Buffer) saveToFile(filename string, withSudo bool, autoSave bool) error
}
newPath := b.Path != filename
+ if newPath {
+ b.RemoveBackup()
+ }
+
b.Path = filename
b.AbsPath = absFilename
b.isModified = false
@@ -362,7 +366,7 @@ func (b *SharedBuffer) safeWrite(path string, with... | internal/buffer/save.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | backup+util: Prevent too long backup file names with hashing + resolve file | 3,806 | zyedidia/micro | 13,805 | Go | JoeKar | |
func FindRuntimeFile(fileType RTFiletype, name string) RuntimeFile {
for _, f := range ListRuntimeFiles(fileType) {
if f.Name() == name {
return f
}
}
return nil
}
// ListRuntimeFiles lists all known runtime files for the given filetype
func ListRuntimeFiles(fileType RTFiletype) []RuntimeFile {
return allFi... | No issues found. | func FindRuntimeFile(fileType RTFiletype, name string) RuntimeFile {
for _, f := range ListRuntimeFiles(fileType) {
if f.Name() == name {
return f
}
}
return nil
}
// ListRuntimeFiles lists all known runtime files for the given filetype
func ListRuntimeFiles(fileType RTFiletype) []RuntimeFile {
return allFi... | @@ -187,6 +187,7 @@ func InitPlugins() {
p.Name = "initlua"
p.DirName = "initlua"
p.Srcs = append(p.Srcs, realFile(initlua))
+ p.Builtin = false
Plugins = append(Plugins, p)
}
@@ -242,7 +243,7 @@ func InitPlugins() {
p := new(Plugin)
p.Name = d
p.DirName = d
- p.Default = true
+ p.... | internal/config/rtfiles.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | Adding the ability to differentiate builtin plugins when listing | 3,810 | zyedidia/micro | 13,805 | Go | Neko-Box-Coder | |
func handleBackupRequest(br backupRequest) {
switch br.reqType {
case backupCreate:
// schedule periodic backup
requestedBackups[br.buf] = true
case backupRemove:
br.buf.RemoveBackup()
delete(requestedBackups, br.buf)
}
}
func periodicBackup() {
for buf := range requestedBackups {
err := buf.Backup()
... | No issues found. |
func handleBackupRequest(br backupRequest) {
switch br.reqType {
case backupCreate:
// schedule periodic backup
requestedBackups[br.buf] = true
case backupRemove:
br.buf.RemoveBackup()
delete(requestedBackups, br.buf)
}
}
func periodicBackup() {
for buf := range requestedBackups {
err := buf.Backup()
... | @@ -34,75 +34,105 @@ Options: [r]ecover, [i]gnore, [a]bort: `
const backupSeconds = 8
-var BackupCompleteChan chan *Buffer
+type backupRequestType int
+
+const (
+ backupCreate = iota
+ backupRemove
+)
+
+type backupRequest struct {
+ buf *SharedBuffer
+ reqType backupRequestType
+}
+
+var requestedBackups map... | internal/buffer/backup.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | Fix spurious backups of unmodified files | 3,822 | zyedidia/micro | 13,805 | Go | dmaluka | |
h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.GotoLoc(h.Cursor.CurSelection[1])
h.Buf.LastSearch = resp
h.Buf.LastSearchRegex = useRegex
h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
} else {
h.Cursor.ResetSelection... | No issues found. | h.Cursor.OrigSelection[0] = h.Cursor.CurSelection[0]
h.Cursor.OrigSelection[1] = h.Cursor.CurSelection[1]
h.GotoLoc(h.Cursor.CurSelection[1])
h.Buf.LastSearch = resp
h.Buf.LastSearchRegex = useRegex
h.Buf.HighlightSearch = h.Buf.Settings["hlsearch"].(bool)
} else {
h.Cursor.ResetSelection... | @@ -1144,8 +1144,7 @@ func (h *BufPane) find(useRegex bool) bool {
match, found, err := h.Buf.FindNext(resp, h.Buf.Start(), h.Buf.End(), h.searchOrig, true, useRegex)
if err != nil {
InfoBar.Error(err)
- }
- if found {
+ } else if found {
h.Cursor.SetSelectionStart(match[0])
h.Cursor.SetSel... | internal/action/actions.go | 0 | Go | 1 | none | 16 | 51 | 51 | true | quick fix for #3700 | 3,914 | zyedidia/micro | 13,805 | Go | matthias314 | |
}
function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLE... | No issues found. | }
function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLE... | @@ -74,13 +74,13 @@ while (( $# > 0 )); do
shift
done
-if [[ "${arguments[script_mode]}" == "$BUILD_DOCKER" ]]; then
- SCRIPT_MODE="${arguments[script_mode]}"
-fi
-
-if [[ "$SCRIPT_MODE" != "$NATIVE" && "$SCRIPT_MODE" != "$BUILD_DOCKER" ]]; then
- echo "Error: Invalid script mode argument: $SCRIPT_MODE"
- ... | ebook2audiobook.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | v25.12.2b11 | 1,236 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLER_... | No issues found. |
function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLER_... | @@ -36,9 +36,9 @@ APP_NAME="ebook2audiobook"
APP_VERSION=$(<"$SCRIPT_DIR/VERSION.txt")
OS_LANG=$(echo "${LANG:-en}" | cut -d_ -f1 | tr '[:upper:]' '[:lower:]')
HOST_PROGRAMS=("curl" "pkg-config" "calibre" "ffmpeg" "nodejs" "espeak-ng" "rust" "sox" "tesseract")
-DOCKER_PROGRAMS=("curl" "ffmpeg" "nodejs" "espeak-ng" "... | ebook2audiobook.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | v25.12.4b13 | 1,250 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
if ! command -v "$bin" &>/dev/null; then
echo -e "\e[33m$pkg is not installed.\e[0m"
programs_missing+=("$pkg")
fi
done
(( ${#programs_missing[@]} == 0 ))
}
function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
i... | No issues found. | if ! command -v "$bin" &>/dev/null; then
echo -e "\e[33m$pkg is not installed.\e[0m"
programs_missing+=("$pkg")
fi
done
(( ${#programs_missing[@]} == 0 ))
}
function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
i... | @@ -35,7 +35,7 @@ SCRIPT_MODE="$NATIVE"
APP_NAME="ebook2audiobook"
APP_VERSION=$(<"$SCRIPT_DIR/VERSION.txt")
OS_LANG=$(echo "${LANG:-en}" | cut -d_ -f1 | tr '[:upper:]' '[:lower:]')
-HOST_PROGRAMS=("curl" "pkg-config" "calibre" "ffmpeg" "nodejs" "espeak-ng" "rust" "sox" "tesseract")
+HOST_PROGRAMS=("curl" "pkg-confi... | ebook2audiobook.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | v25.12.4b14 | 1,258 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
# ---------------------------------------------------------------------
# Hardware mappings
# ---------------------------------------------------------------------
devices = {
"CPU": {"proc": "cpu", "found": True},
"CUDA": {"proc": "cuda", "found": False},
"MPS": {"proc": "mps", "found": False},
... | No issues found. | # ---------------------------------------------------------------------
# Hardware mappings
# ---------------------------------------------------------------------
devices = {
"CPU": {"proc": "cpu", "found": True},
"CUDA": {"proc": "cuda", "found": False},
"MPS": {"proc": "mps", "found": False},
... | @@ -29,6 +29,7 @@
os.environ['CALIBRE_NO_NATIVE_FILEDIALOGS'] = '1'
os.environ['CALIBRE_TEMP_DIR'] = tmp_dir
os.environ['CALIBRE_CACHE_DIRECTORY'] = tmp_dir
+os.environ['CALIBRE_CONFIG_DIRECTORY'] = tmp_dir
os.environ['TMPDIR'] = tmp_dir
os.environ['GRADIO_DEBUG'] = '0'
os.environ['DO_NOT_TRACK'] = 'True'
... | lib/conf.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.13 | 1,289 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
gui_group.add_argument(options[2], action='store_true', help='''Enable a public shareable Gradio link.''')
headless_group = parser.add_argument_group('**** The following options are for --headless mode only')
headless_group.add_argument(options[3], action='store_true', help='''Run the script in headless mod... | No issues found. | gui_group.add_argument(options[2], action='store_true', help='''Enable a public shareable Gradio link.''')
headless_group = parser.add_argument_group('**** The following options are for --headless mode only')
headless_group.add_argument(options[3], action='store_true', help='''Run the script in headless mod... | @@ -120,6 +120,12 @@ def main()->None:
docker run --device=/dev/dri --rm -it -v "/my/real/ebooks/folder/absolute/path:/app/ebooks" -v "/my/real/output/folder/absolute/path:/app/audiobooks" -p 7860:7860 ebook2audiobook:xpu --headless --ebook "/app/ebooks/myfile.pdf" [--voice /app/my/voicepath/voice.mp3 etc..]
... | app.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.13 | 1,291 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
return True
else:
return True
except Exception as e:
error = f'_check_bark_npz() error: {e}'
print(error)
return False
def _tensor_type(self,audio_data:Any)->torch.Tensor:
if isinstance(audio_data, torch.Ten... | No issues found. | return True
else:
return True
except Exception as e:
error = f'_check_bark_npz() error: {e}'
print(error)
return False
def _tensor_type(self,audio_data:Any)->torch.Tensor:
if isinstance(audio_data, torch.Ten... | @@ -48,7 +48,7 @@ def __init__(self, session:DictProxy):
np.random.seed(seed)
torch.manual_seed(seed)
if using_gpu and enough_vram:
- if devices['CUDA']['found'] or devices['ROCM']['found']:
+ if devices['CUDA']['found'] or devices... | lib/classes/tts_engines/coqui.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.14 | 1,295 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLER_U... | No issues found. | function install_programs {
if [[ "$OSTYPE" == darwin* ]]; then
echo -e "\e[33mInstalling required programs...\e[0m"
PACK_MGR="brew install"
if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLER_U... | @@ -36,7 +36,7 @@ APP_NAME="ebook2audiobook"
APP_VERSION=$(<"$SCRIPT_DIR/VERSION.txt")
OS_LANG=$(echo "${LANG:-en}" | cut -d_ -f1 | tr '[:upper:]' '[:lower:]')
HOST_PROGRAMS=("cmake" "curl" "pkg-config" "calibre" "ffmpeg" "nodejs" "espeak-ng" "cargo" "rust" "sox" "tesseract")
-DOCKER_PROGRAMS=("curl" "wget" "ffmpeg"... | ebook2audiobook.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | v25.12.15 | 1,308 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
def has_working_xpu():
# No XPU on macOS
if sys.platform == "darwin":
return False
# ---------- Linux ----------
if os.name == "posix":
# Must have render node
if not os.path.exists("/dev/dri/renderD128"):
... | No issues found. | def has_working_xpu():
# No XPU on macOS
if sys.platform == "darwin":
return False
# ---------- Linux ----------
if os.name == "posix":
# Must have render node
if not os.path.exists("/dev/dri/renderD128"):
... | @@ -199,6 +199,197 @@ def jetpack_version(text:str)->str:
msg = 'Unrecognized JetPack 6.x version. Falling back to CPU.'
return ('unknown', msg)
+ def has_amd_gpu_pci():
+ # macOS: no ROCm-capable AMD GPUs
+ if sys.platform == "darwin":
+ retur... | lib/classes/device_installer.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.16 | 1,340 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
speaker=speaker,
voice_dir=pth_voice_dir,
**fine_tuned_params
)
del result
msg = f"Saved file: {pth_voice_file}"
print(msg)
return T... | No issues found. | speaker=speaker,
voice_dir=pth_voice_dir,
**fine_tuned_params
)
del result
msg = f"Saved file: {pth_voice_file}"
print(msg)
return T... | @@ -1,4 +1,4 @@
-import threading, torch, torchaudio, random, gc, shutil, subprocess, tempfile, uuid
+import threading, torch, torchaudio, random, gc, shutil, subprocess, tempfile, uuid, types
import regex as re
import numpy as np | lib/classes/tts_engines/coqui.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.17 | 1,342 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
voice_dir=pth_voice_dir,
**fine_tuned_params
)
del result
msg = f"Saved file: {pth_voice_file}"
print(msg)
return True
else:
return ... | No issues found. | voice_dir=pth_voice_dir,
**fine_tuned_params
)
del result
msg = f"Saved file: {pth_voice_file}"
print(msg)
return True
else:
return ... | @@ -17,21 +17,6 @@
#import logging
#logging.basicConfig(level=logging.DEBUG)
-if not hasattr(torch, "distributed"):
- torch.distributed = types.SimpleNamespace()
-
-if not hasattr(torch.distributed, "ReduceOp"):
- class _ReduceOp:
- SUM = None
- MAX = None
- MIN = None
- torch.distributed.ReduceOp = _ReduceOp
-
... | lib/classes/tts_engines/coqui.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.18 | 1,352 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
"voice": os.path.join(voices_dir, 'eng', 'adult', 'male', 'DeathPussInBoots.wav'),
"files": default_engine_settings[TTS_ENGINES['XTTSv2']]['files'],
"samplerate": default_engine_settings[TTS_ENGINES['XTTSv2']]['samplerate']
},
"DermotCrowley": {
"lang... | No issues found. | "voice": os.path.join(voices_dir, 'eng', 'adult', 'male', 'DeathPussInBoots.wav'),
"files": default_engine_settings[TTS_ENGINES['XTTSv2']]['files'],
"samplerate": default_engine_settings[TTS_ENGINES['XTTSv2']]['samplerate']
},
"DermotCrowley": {
"lang... | @@ -30,7 +30,6 @@
default_fine_tuned = 'internal'
default_vc_model = TTS_VOICE_CONVERSION['knnvc']['path']
default_voice_detection_model = 'drewThomasson/segmentation'
-#default_voice_detection_model = 'pyannote/segmentation-3.0'
max_custom_model = 100
max_custom_voices = 1000
| lib/models.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.18 | 1,356 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
from pyannote.audio import Model
from pyannote.audio.pipelines import VoiceActivityDetection
from lib.conf import tts_dir
from lib.models import default_voice_detection_model
_PIPELINE_CACHE = {}
_PIPELINE_LOCK = threading.Lock()
class BackgroundDetector:
def __init__(self, wav_file: str):
self.wav_file = wav_f... | No issues found. |
from pyannote.audio import Model
from pyannote.audio.pipelines import VoiceActivityDetection
from lib.conf import tts_dir
from lib.models import default_voice_detection_model
_PIPELINE_CACHE = {}
_PIPELINE_LOCK = threading.Lock()
class BackgroundDetector:
def __init__(self, wav_file: str):
self.wav_file = wav_f... | @@ -1,42 +1,56 @@
-import os
import torch
import librosa
+import threading
from pyannote.audio import Model
from pyannote.audio.pipelines import VoiceActivityDetection
from lib.conf import tts_dir
from lib.models import default_voice_detection_model
+
+_PIPELINE_CACHE = {}
+_PIPELINE_LOCK = threading.Lock()
+... | lib/classes/background_detector.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.18 | 1,357 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
# ---------------------------------------------------------------------
# Hardware mappings
# ---------------------------------------------------------------------
devices = {
"CPU": {"proc": "cpu", "found": True},
"CUDA": {"proc": "cuda", "found": False},
"MPS": {"proc": "mps", "found": False},
... | No issues found. | # ---------------------------------------------------------------------
# Hardware mappings
# ---------------------------------------------------------------------
devices = {
"CPU": {"proc": "cpu", "found": True},
"CUDA": {"proc": "cuda", "found": False},
"MPS": {"proc": "mps", "found": False},
... | @@ -49,7 +49,6 @@
os.environ['PYTORCH_ENABLE_MPS_FALLBACK'] = '1'
os.environ['PYTORCH_NO_CUDA_MEMORY_CACHING'] = '1'
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:32,garbage_collection_threshold:0.6,expandable_segments:True'
-os.environ["LD_PRELOAD"] = f"/usr/lib/aarch64-linux-gnu/libgomp.so.1:{os.en... | lib/conf.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.19 | 1,363 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
# No XPU on macOS
if sys.platform == "darwin":
return False
# ---------- Linux ----------
if os.name == "posix":
# Must have render node
if not os.path.exists("/dev/dri/renderD128"):
return False
... | No issues found. | # No XPU on macOS
if sys.platform == "darwin":
return False
# ---------- Linux ----------
if os.name == "posix":
# Must have render node
if not os.path.exists("/dev/dri/renderD128"):
return False
... | @@ -732,7 +732,9 @@ def install_device_packages(self, device_info_str:str)->int:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', '--no-cache-dir', torch_pkg])
subprocess.check_call([sys.executable, '-m', 'pip',... | lib/classes/device_installer.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.19 | 1,365 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
is_ffmpeg = "ffmpeg" in os.path.basename(self.cmd[0])
if is_ffmpeg:
self.process = subprocess.Popen(
self.cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=False,
bufsiz... | No issues found. | is_ffmpeg = "ffmpeg" in os.path.basename(self.cmd[0])
if is_ffmpeg:
self.process = subprocess.Popen(
self.cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
text=False,
bufsiz... | @@ -1,4 +1,4 @@
-import os, subprocess, re, sys, tqdm, gradio as gr
+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'): | lib/classes/subprocess_pipe.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.19 | 1,366 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
if sys.platform == "darwin":
return False
# ---------- Linux ----------
if os.name == "posix":
# Must have render node
if not os.path.exists("/dev/dri/renderD128"):
return False
# Prefer Level Zero ru... | No issues found. | if sys.platform == "darwin":
return False
# ---------- Linux ----------
if os.name == "posix":
# Must have render node
if not os.path.exists("/dev/dri/renderD128"):
return False
# Prefer Level Zero ru... | @@ -409,9 +409,10 @@ def has_working_xpu():
devices['JETSON']['found'] = True
name = 'jetson'
tag = f'jetson{jp_code}'
- out = try_cmd('uname -a')
- if 'tegra' in out:
- msg = 'Jetson GPU detected but not(?) compatible'
... | lib/classes/device_installer.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.19 | 1,367 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
key.removeprefix("xtts_"): cast_type(self.session[key])
for key, cast_type in {
"xtts_temperature": float,
#"xtts_codec_temperature": float,
"xtts_length_penalty": floa... | No issues found. | key.removeprefix("xtts_"): cast_type(self.session[key])
for key, cast_type in {
"xtts_temperature": float,
#"xtts_codec_temperature": float,
"xtts_length_penalty": floa... | @@ -11,7 +11,7 @@
from lib.classes.tts_registry import TTSRegistry
from lib.classes.vram_detector import VRAMDetector
-from lib.classes.tts_engines.common.utils import cleanup_memory, append_sentence2vtt, loaded_tts_size_gb, load_xtts_builtin_list #, ensure_safe_checkpoint
+from lib.classes.tts_engines.common.utils... | lib/classes/tts_engines/bark.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.20 | 1,382 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
visible_custom_model = True if session['fine_tuned'] == 'internal' else False
return (
gr.update(value=show_rating(session['tts_engine'])),
gr.update(visible=visible_gr_tab_xtts_params),
... | No issues found. | visible_custom_model = True if session['fine_tuned'] == 'internal' else False
return (
gr.update(value=show_rating(session['tts_engine'])),
gr.update(visible=visible_gr_tab_xtts_params),
... | @@ -1045,9 +1045,11 @@ def click_gr_audiobook_del_btn(selected:str, id:str)->tuple:
def confirm_deletion(voice_path:str, custom_model:str, audiobook:str, id:str, method:str|None=None)->tuple:
try:
+ nonlocal models
if method is not None:
... | lib/gradio.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.25 | 1,388 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
else self.models[self.session['fine_tuned']]['voice']
)
if self.params['voice_path'] is not None:
speaker = re.sub(r'\.wav$', '', os.path.basename(self.params['voice_path']))
if self.params['voice_path'] not in default_engine_settings[TTS_ENGINES['... | No issues found. | else self.models[self.session['fine_tuned']]['voice']
)
if self.params['voice_path'] is not None:
speaker = re.sub(r'\.wav$', '', os.path.basename(self.params['voice_path']))
if self.params['voice_path'] not in default_engine_settings[TTS_ENGINES['... | @@ -141,10 +141,16 @@ def convert(self, sentence_index:int, sentence:str)->bool:
)
audio_sentence = result.get('wav')
if is_audio_data_valid(audio_sentence):
- audio_sentence = audio_sentence.tolist()
- if is_au... | lib/classes/tts_engines/xtts.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.25 | 1,411 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
msg = f"Loading ZeroShot {self.tts_zs_key} model, it takes a while, please be patient..."
print(msg)
self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False)
if not engine_zs:
engine_zs = self._load_api(self.tts_zs_key, default... | No issues found. | msg = f"Loading ZeroShot {self.tts_zs_key} model, it takes a while, please be patient..."
print(msg)
self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False)
if not engine_zs:
engine_zs = self._load_api(self.tts_zs_key, default... | @@ -151,6 +151,7 @@ def _load_engine_zs(self)->Any:
def _check_xtts_builtin_speakers(self, voice_path:str, speaker:str)->str|bool:
new_voice_path = ''
+ proc_voice_path = ''
try:
voice_parts = Path(voice_path).parts
if (self.session['language'] in voice_parts or... | lib/classes/tts_engines/common/utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.25 | 1,413 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
out = try_cmd("sycl-ls").lower()
if "level-zero" in out and "gpu" in out:
return True
if has_cmd("clinfo"):
out = try_cmd("clinfo").lower()
if "intel" in out and "gpu" in out:
... | No issues found. | out = try_cmd("sycl-ls").lower()
if "level-zero" in out and "gpu" in out:
return True
if has_cmd("clinfo"):
out = try_cmd("clinfo").lower()
if "intel" in out and "gpu" in out:
... | @@ -426,7 +426,7 @@ def has_working_xpu():
if version_out:
break
if not version_out:
- msg = 'ROCm hardware detected but ROCm toolkit version file not found.'
+ msg = 'ROCm hardware detected but AMD ROCm base runtime not installed.... | lib/classes/device_installer.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.25 | 1,414 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
or reuse of custom models and custom cloning voices.''')
gui_group = parser.add_argument_group('**** The following option are for gradio/gui mode only', 'Optional')
gui_group.add_argument(options[2], action='store_true', help='''Enable a public shareable Gradio link.''')
headless_group = parser.add_argu... | No issues found. | or reuse of custom models and custom cloning voices.''')
gui_group = parser.add_argument_group('**** The following option are for gradio/gui mode only', 'Optional')
gui_group.add_argument(options[2], action='store_true', help='''Enable a public shareable Gradio link.''')
headless_group = parser.add_argu... | @@ -105,20 +105,20 @@ def main()->None:
CPU:
docker run --rm -it -p 7860:7860 ebook2audiobook:cpu
CUDA:
- docker run --gpus all --rm -it -p 7860:7860 ebook2audiobook:cu[118/121/128 etc..]
+ docker run --gpus all --rm -it -p 7860:7860 ebook2audiobook:cu[118/122/124/126 etc..]
... | app.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | README Typos | 1,420 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
return gr.update(), gr.update(), gr.update()
def change_gr_tts_engine_list(engine:str, id:str)->tuple:
nonlocal models
session = context.get_session(id)
if session:
models = load_engine_presets(engine)
s... | No issues found. | return gr.update(), gr.update(), gr.update()
def change_gr_tts_engine_list(engine:str, id:str)->tuple:
nonlocal models
session = context.get_session(id)
if session:
models = load_engine_presets(engine)
s... | @@ -1118,12 +1118,14 @@ def update_gr_voice_list(id:str)->dict:
file_pattern = "*.wav"
eng_options = []
bark_options = []
+ builtin_dir = Path(os.path.join(voices_dir, lang_dir))
builtin_options = ... | lib/gradio.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.29 | 1,456 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
return True
else:
return True
except Exception as e:
error = f'_check_bark_npz() error: {e}'
print(error)
return False
"""
def convert(self, sentence_index:int, sentence:str)->bool:
try:
speaker = Non... | No issues found. | return True
else:
return True
except Exception as e:
error = f'_check_bark_npz() error: {e}'
print(error)
return False
"""
def convert(self, sentence_index:int, sentence:str)->bool:
try:
speaker = Non... | @@ -9,7 +9,6 @@ def __init__(self, session:DictProxy):
self.cache_dir = tts_dir
self.speakers_path = None
self.tts_key = self.session['model_cache']
- self.tts_zs_key = default_vc_model.rsplit('/',1)[-1]
self.pth_voice_file = None
self.sentence... | lib/classes/tts_engines/bark.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.31 | 1,478 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
else:
msg = f'DEVICE_TAG not valid'
else:
# ============================================================
# JETSON
# ============================================================
if arch in ('aarch64','arm64') and (os.path.exists('/etc/nv... | No issues found. | else:
msg = f'DEVICE_TAG not valid'
else:
# ============================================================
# JETSON
# ============================================================
if arch in ('aarch64','arm64') and (os.path.exists('/etc/nv... | @@ -428,7 +428,8 @@ def has_working_xpu():
):
if os.path.exists(p):
with open(p, 'r', encoding='utf-8', errors='ignore') as f:
- version = f.read()
+ v = f.read()
+ ... | lib/classes/device_installer.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.32 | 1,485 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
else:
return True
except Exception as e:
error = f'_check_bark_npz() error: {e}'
print(error)
return False
"""
def convert(self, sentence_index:int, sentence:str)->bool:
try:
speaker = None
audio_sentence = F... | No issues found. | else:
return True
except Exception as e:
error = f'_check_bark_npz() error: {e}'
print(error)
return False
"""
def convert(self, sentence_index:int, sentence:str)->bool:
try:
speaker = None
audio_sentence = F... | @@ -122,6 +122,9 @@ def convert(self, sentence_index:int, sentence:str)->bool:
return False
if self.engine:
final_sentence_file = os.path.join(self.session['chapters_dir_sentences'], f'{sentence_index}.{default_audio_proc_format}')
+ s = sentence.str... | lib/classes/tts_engines/bark.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.32 | 1,486 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
self.session['voice'] if self.session['voice'] is not None
else self.models[self.session['fine_tuned']]['voice']
)
if self.params['voice_path'] is not None:
speaker = re.sub(r'\.wav$', '', os.path.basename(self.params['voice_path']))
... | No issues found. | self.session['voice'] if self.session['voice'] is not None
else self.models[self.session['fine_tuned']]['voice']
)
if self.params['voice_path'] is not None:
speaker = re.sub(r'\.wav$', '', os.path.basename(self.params['voice_path']))
... | @@ -30,7 +30,6 @@ def __init__(self, session:DictProxy):
self._apply_cuda_policy(using_gpu=using_gpu, enough_vram=enough_vram, seed=seed)
self.xtts_speakers = self._load_xtts_builtin_list()
self.engine = self._load_engine()
- self.engine_zs = self._load_engine_zs()
... | lib/classes/tts_engines/xtts.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.32 | 1,487 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
def clean_match(match:re.Match)->str:
first_num = clean_single_num(match.group(1))
dash_char = match.group(2) or ''
second_num = clean_single_num(match.group(3)) if match.group(3) else ''
trailing = match.group(4) or ''
if second_num:
return f'{first_num}{dash_ch... | No issues found. |
def clean_match(match:re.Match)->str:
first_num = clean_single_num(match.group(1))
dash_char = match.group(2) or ''
second_num = clean_single_num(match.group(3)) if match.group(3) else ''
trailing = match.group(4) or ''
if second_num:
return f'{first_num}{dash_ch... | @@ -47,6 +47,7 @@
from lib.classes.tts_manager import TTSManager
#from lib.classes.redirect_console import RedirectConsole
#from lib.classes.argos_translator import ArgosTranslator
+from lib.classes.tts_engines.common.audio import get_audio_duration
from lib import *
@@ -1843,28 +1844,6 @@ def combine_audio_sen... | lib/core.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 | 1,509 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
def trim_audio(audio_data: Union[list[float], Tensor], samplerate: int, silence_threshold: float = 0.003, buffer_sec: float = 0.005) -> Tensor:
# Ensure audio_data is a PyTorch tensor
if isinstance(audio_data, list):
audio_data = torch.tensor(audio_data, dtype=torch.float32)
if isinstance(audio_dat... | No issues found. |
def trim_audio(audio_data: Union[list[float], Tensor], samplerate: int, silence_threshold: float = 0.003, buffer_sec: float = 0.005) -> Tensor:
# Ensure audio_data is a PyTorch tensor
if isinstance(audio_data, list):
audio_data = torch.tensor(audio_data, dtype=torch.float32)
if isinstance(audio_dat... | @@ -75,10 +75,11 @@ def get_audio_duration(filepath:str)->float:
except Exception:
return 0
except subprocess.CalledProcessError as e:
- DependencyError(e)
+ error = f'get_audio_duration() Error: Failed to process: {e}'
+ print(error)
return 0
except Excepti... | lib/classes/tts_engines/common/audio.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 | 1,511 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
error = f'Cannot extract custom model zip file {os.path.basename(f)}'
state['type'] = 'warning'
state['msg'] = error
else:
error = f'{os.path.basename(f... | No issues found. | error = f'Cannot extract custom model zip file {os.path.basename(f)}'
state['type'] = 'warning'
state['msg'] = error
else:
error = f'{os.path.basename(f... | @@ -673,7 +673,53 @@ def enable_components(id:str)->tuple:
if session['event'] == 'confirm_blocks':
outputs = tuple([gr.update() for _ in range(12)])
return outputs
- outputs = tuple([gr.update(interactive=True) for _ in range(12)])
+... | lib/gradio.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 | 1,514 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
def clean_single_num(num_str:str)->str:
tok = unicodedata.normalize('NFKC', num_str)
if tok.lower() in ('inf', 'infinity', 'nan'):
return tok
clean = tok.replace(',', '').replace('\u00A0', '').replace(' ', '')
try:
num = float(clean) if '.' in clean else int(... | No issues found. |
def clean_single_num(num_str:str)->str:
tok = unicodedata.normalize('NFKC', num_str)
if tok.lower() in ('inf', 'infinity', 'nan'):
return tok
clean = tok.replace(',', '').replace('\u00A0', '').replace(' ', '')
try:
num = float(clean) if '.' in clean else int(... | @@ -24,7 +24,6 @@
from ebooklib.epub import EpubBook
from ebooklib.epub import EpubHtml
from glob import glob
-from gradio import utils
from iso639 import Lang
from markdown import markdown
from multiprocessing import Pool, cpu_count
@@ -850,7 +849,8 @@ def _tuple_row(node:Any, last_text_char:str|None=None)->Gene... | lib/core.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.14 | 1,520 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
print(error)
return None
def _load_engine_zs(self)->Any:
try:
msg = f"Loading ZeroShot {self.tts_zs_key} model, it takes a while, please be patient..."
print(msg)
self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False... | No issues found. | print(error)
return None
def _load_engine_zs(self)->Any:
try:
msg = f"Loading ZeroShot {self.tts_zs_key} model, it takes a while, please be patient..."
print(msg)
self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False... | @@ -168,7 +168,7 @@ def _load_api(self, key:str, model_path:str)->Any:
if not engine:
engine = TTSEngine(model_path)
if engine:
- vram_dict = VRAMDetector().detect_vram(self.session['device'])
+ vram_dict = VRAMDetector().detec... | lib/classes/tts_engines/common/utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.14 | 1,522 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLER_URL)"
echo >> $HOME/.zprofile
echo 'eval "$(/usr/local/bin/brew shellenv)"' >> $HOME/.zprofile
eval "$(/usr/local/bin/brew shellenv)"
if !... | No issues found. | if ! command -v brew &> /dev/null; then
echo -e "\e[33mHomebrew is not installed. Installing Homebrew...\e[0m"
/usr/bin/env bash -c "$(curl -fsSL $BREW_INSTALLER_URL)"
echo >> $HOME/.zprofile
echo 'eval "$(/usr/local/bin/brew shellenv)"' >> $HOME/.zprofile
eval "$(/usr/local/bin/brew shellenv)"
if !... | @@ -30,6 +30,8 @@ export CONDA_HOME="$HOME/Miniforge3"
export CONDA_BIN_PATH="$CONDA_HOME/bin"
export CONDA_ENV="$CONDA_HOME/etc/profile.d/conda.sh"
export PATH="$CONDA_BIN_PATH:${PATH-}"
+export APP_VERSION=$(<"$SCRIPT_DIR/VERSION.txt")
+export DEVICE_TAG="${DEVICE_TAG:-}"
NATIVE="native"
BUILD_DOCKER="build_do... | ebook2audiobook.sh | 0 | Shell | 1 | none | 16 | 51 | 51 | true | v26.1.14 | 1,526 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
info = {
"os": self.system,
"device_type": "jetson",
"device_name": "NVIDIA Jetson (Unified Memory)",
"free_bytes": mem.available,
"total_bytes": mem.total,... | No issues found. | info = {
"os": self.system,
"device_type": "jetson",
"device_name": "NVIDIA Jetson (Unified Memory)",
"free_bytes": mem.available,
"total_bytes": mem.total,... | @@ -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))
def detect_vram(self, device:str, script_mode:str, as_json:bool=False)->Any:
info = {}
+ in_dock... | lib/classes/vram_detector.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 | 1,527 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
def _run_process(self)->bool:
try:
is_ffmpeg = "ffmpeg" in os.path.basename(self.cmd[0])
if is_ffmpeg:
self.process = subprocess.Popen(
self.cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
... | No issues found. | def _run_process(self)->bool:
try:
is_ffmpeg = "ffmpeg" in os.path.basename(self.cmd[0])
if is_ffmpeg:
self.process = subprocess.Popen(
self.cmd,
stdout=subprocess.DEVNULL,
stderr=subprocess.PIPE,
... | @@ -10,6 +10,7 @@ def __init__(self, cmd:str, is_gui_process:bool, total_duration:float, msg:str='
self.msg = msg
self.process = None
self._stop_requested = False
+ self.on_progress = on_progress
self.progress_bar = False
if self.is_gui_process:
self.prog... | lib/classes/subprocess_pipe.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.14 | 1,528 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
try:
msg = f"Loading ZeroShot {self.tts_zs_key} model, it takes a while, please be patient..."
print(msg)
self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False)
if not engine_zs:
engine_zs = self._load_api(self.tts_zs... | No issues found. | try:
msg = f"Loading ZeroShot {self.tts_zs_key} model, it takes a while, please be patient..."
print(msg)
self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False)
if not engine_zs:
engine_zs = self._load_api(self.tts_zs... | @@ -408,29 +408,36 @@ def _set_voice(self)->bool:
return False
return True
- def _convert_sml(self, sml:str)->bool:
- if sml == TTS_SML['break']['token']:
- silence_time = int(np.random.uniform(0.3, 0.6) * 100) / 100
- break_tensor = torch.zeros(1, int(sel... | lib/classes/tts_engines/common/utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 | 1,538 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False)
if not engine_zs:
engine_zs = self._load_api(self.tts_zs_key, default_vc_model)
if engine_zs:
self.session['model_zs_cache'] = self.tts_zs_key
msg = f... | No issues found. | self._cleanup_memory()
engine_zs = loaded_tts.get(self.tts_zs_key, False)
if not engine_zs:
engine_zs = self._load_api(self.tts_zs_key, default_vc_model)
if engine_zs:
self.session['model_zs_cache'] = self.tts_zs_key
msg = f... | @@ -125,7 +125,8 @@ def _apply_gpu_policy(self, enough_vram: bool, seed: int) -> torch.dtype:
if quality_mode:
try:
if hasattr(torch.cuda, "is_bf16_supported") and torch.cuda.is_bf16_supported():
- amp_dtype = torch.bfloat16
+ ... | lib/classes/tts_engines/common/utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 | 1,544 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
#"gpt_cond_len": 512,
#"gpt_batch_size": 1,
"enable_text_splitting": False,
"files": ['config.json', 'model.pth', 'vocab.json', 'ref.wav'],
"voices": {
"ClaribelDervla": "Claribel Dervla", "DaisyStudious": "Daisy Studious", "GracieWise": "Gracie Wise",
... | No issues found. | #"gpt_cond_len": 512,
#"gpt_batch_size": 1,
"enable_text_splitting": False,
"files": ['config.json', 'model.pth', 'vocab.json', 'ref.wav'],
"voices": {
"ClaribelDervla": "Claribel Dervla", "DaisyStudious": "Daisy Studious", "GracieWise": "Gracie Wise",
... | @@ -21,33 +21,27 @@
}
TTS_SML = {
- "break": {
- "match": re.compile(r'(?:‡|\[)break(?:‡|\])'),
- "close_match": None,
- "token": "‡break‡"
- },
- "pause": {
- "match": re.compile(r'(?:‡|\[)pause(?::(\d+(?:\.\d+)?))?(?:‡|\])'),
- "close_match": None,
- "token": "‡pause‡"
- },
- "voice": {
- "ma... | lib/conf_models.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.14 | 1,545 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
session['voice'] = os.path.join(model, f'{os.path.basename(os.path.normpath(model))}.wav')
msg = f'{os.path.basename(model)} added to the custom models list'
state['type'] = 'success'
... | No issues found. | session['voice'] = os.path.join(model, f'{os.path.basename(os.path.normpath(model))}.wav')
msg = f'{os.path.basename(model)} added to the custom models list'
state['type'] = 'success'
... | @@ -661,18 +661,7 @@ def build_interface(args:dict)->gr.Blocks:
gr_state_update = gr.State(value={'hash': None})
gr_restore_session = gr.JSON(elem_id='gr_restore_session', visible='hidden')
- gr_save_session = gr.JSON(elem_id='gr_save_session', visible='hidden')
-
- de... | lib/gradio.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.15 | 1,548 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
max_upload_size = '6GB'
NATIVE = 'native'
FULL_DOCKER = 'full_docker'
debug_mode = False
# ---------------------------------------------------------------------
# Hardware mappings
# ---------------------------------------------------------------------
devices = {
"CPU": {"proc": "cpu", "found": Tru... | No issues found. | max_upload_size = '6GB'
NATIVE = 'native'
FULL_DOCKER = 'full_docker'
debug_mode = False
# ---------------------------------------------------------------------
# Hardware mappings
# ---------------------------------------------------------------------
devices = {
"CPU": {"proc": "cpu", "found": Tru... | @@ -90,49 +90,36 @@
default_py_minor = sys.version_info.minor
default_pytorch_url = 'https://download.pytorch.org/whl'
-default_jetson_url = 'https://www.e-blokos.com/whl/jetson' # TODO: find a definitive place where to upload the jetpack5 torch
-
-jetson_torch_version_base = {
- "jetson60": "2.4.0",
- ... | lib/conf.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.16 | 1,556 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
if device == devices['CPU']['proc']:
self.engine.tts_to_file(
text=part,
file_path=tmp_in_wav,
**speaker_argumen... | No issues found. | if device == devices['CPU']['proc']:
self.engine.tts_to_file(
text=part,
file_path=tmp_in_wav,
**speaker_argumen... | @@ -62,7 +62,7 @@ def convert(self, sentence_index:int, sentence:str)->bool:
self.audio_segments = []
for part in sentence_parts:
part = part.strip()
- if not part:
+ if not part or not any(c.isalnum() for c in part):
... | lib/classes/tts_engines/fairseq.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 | 1,558 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
if self.is_gui_process:
self.progress_bar(0, desc=msg)
chunks = silence.split_on_silence(
audio,
min_silence_len = min_silence_len,
silence_thresh = silence_threshold,
keep_silence = keep_silence
)
if not chunks:
ret... | No issues found. | if self.is_gui_process:
self.progress_bar(0, desc=msg)
chunks = silence.split_on_silence(
audio,
min_silence_len = min_silence_len,
silence_thresh = silence_threshold,
keep_silence = keep_silence
)
if not chunks:
ret... | @@ -6,12 +6,14 @@
from pydub.silence import detect_nonsilent
from lib.classes.tts_engines.common.preset_loader import load_engine_presets
+from lib.classes.tts_engines.common.audio import get_audio_duration
from lib.classes.background_detector import BackgroundDetector
from lib.classes.subprocess_pipe import Subp... | lib/classes/voice_extractor.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v25.12.33 Legacy | 1,569 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
default_text,
speaker_wav=voice_path,
speaker=speaker,
voice_dir=pth_voice_dir,
**fine_tuned_params
)
... | No issues found. | default_text,
speaker_wav=voice_path,
speaker=speaker,
voice_dir=pth_voice_dir,
**fine_tuned_params
)
... | @@ -137,8 +137,8 @@ def convert(self, sentence_index:int, sentence:str)->bool:
if not part:
continue
if SML_TAG_PATTERN.fullmatch(part):
- bool, error = self._convert_sml(part)
- if not bool:
+ ... | lib/classes/tts_engines/bark.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.26 | 1,579 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
if model is not None:
session['custom_model'] = model
session['voice'] = os.path.join(model, f'{os.path.basename(os.path.normpath(model))}.wav')
msg = f'{os.path.basename(model)} a... | No issues found. | if model is not None:
session['custom_model'] = model
session['voice'] = os.path.join(model, f'{os.path.basename(os.path.normpath(model))}.wav')
msg = f'{os.path.basename(model)} a... | @@ -680,33 +680,36 @@ def enable_components(session_id:str)->tuple:
def disable_on_voice_upload()->tuple:
return (
- *([gr.update(interactive=False) for _ in range(8)]),
- gr.update(visible=False),
- gr.update(visib... | lib/gradio.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.26 | 1,581 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
vocals_idx = model.sources.index("vocals")
vocals = sources[0, vocals_idx]
audio_np = vocals.detach().cpu().numpy()
audio_np = audio_np.T
audio_np = (audio_np * 32767.0).clip(-32768, 32767).astype("int16")
audio_segment = AudioSegment(
... | No issues found. | vocals_idx = model.sources.index("vocals")
vocals = sources[0, vocals_idx]
audio_np = vocals.detach().cpu().numpy()
audio_np = audio_np.T
audio_np = (audio_np * 32767.0).clip(-32768, 32767).astype("int16")
audio_segment = AudioSegment(
... | @@ -245,15 +245,12 @@ def _trim_and_clean(self, silence_threshold:int, min_silence_len:int=200, chunk_
print(error)
return False, error
- def normalize_audio(self, src_file:str=None, proc_file:str=None, dst_file:str=None)->tuple[bool, str]:
+ def normalize_audio(self, src_file:str, pro... | lib/classes/voice_extractor.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.26 | 1,583 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
msg = f'{os.path.basename(model)} added to the custom models list'
state['type'] = 'success'
state['msg'] = msg
show_alert(state)
return gr.... | No issues found. | msg = f'{os.path.basename(model)} added to the custom models list'
state['type'] = 'success'
state['msg'] = msg
show_alert(state)
return gr.... | @@ -682,46 +682,45 @@ def disable_on_voice_upload()->tuple:
return (
gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False), gr.update(interactive=False),
gr.update(interactive=False), gr.update(interactive=False), gr.update(in... | lib/gradio.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.27 | 1,586 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
print("\r[Demucs] 100.00%")
sources = result[0] if isinstance(result, (tuple, list)) else result
vocals_idx = model.sources.index("vocals")
vocals = sources[0, vocals_idx]
audio_np = vocals.detach().cpu().numpy()
audio_np = audio_np.T
a... | No issues found. | print("\r[Demucs] 100.00%")
sources = result[0] if isinstance(result, (tuple, list)) else result
vocals_idx = model.sources.index("vocals")
vocals = sources[0, vocals_idx]
audio_np = vocals.detach().cpu().numpy()
audio_np = audio_np.T
a... | @@ -104,14 +104,16 @@ def demucs_callback(d: dict):
if percent - last_percent >= 0.01:
last_percent = percent
print(f"\r[Demucs] {percent*100:.2f}%", end="", flush=True)
- self.progress_bar(percent, desc=msg)
+ if self.is_g... | lib/classes/voice_extractor.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.1.27 | 1,590 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
import os
from lib.conf import voices_dir
from lib.conf_models import TTS_ENGINES, default_engine_settings
models = {
"internal": {
"lang": "multi",
"repo": "tts_models/[lang_iso1]/[xxx]",
"sub": {
"multi-dataset/tortoise-v2": ['en'],
},
"voice": os.path.join(voi... | No issues found. | import os
from lib.conf import voices_dir
from lib.conf_models import TTS_ENGINES, default_engine_settings
models = {
"internal": {
"lang": "multi",
"repo": "tts_models/[lang_iso1]/[xxx]",
"sub": {
"multi-dataset/tortoise-v2": ['en'],
},
"voice": os.path.join(voi... | @@ -0,0 +1,18 @@
+import os
+from lib.conf import voices_dir
+from lib.conf_models import TTS_ENGINES, default_engine_settings
+
+models = {
+ "internal": {
+ "lang": "multi",
+ "repo": "tts_models/[lang_iso1]/[xxx]",
+ "sub": {
+ "multi-dataset/tortoise-v2": ['en'],
+ },
+ ... | lib/classes/tts_engines/presets/tortoise_presets.py | 0 | Python | 1 | none | 16 | 18 | 18 | true | v26.1.27 | 1,594 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
else:
integer_part = tok.replace(',', '')
return "{:,}".format(int(integer_part))
def clean_single_num(num_str:str)->str:
tok = unicodedata.normalize('NFKC', num_str)
if tok.lower() in ('inf', 'infinity', 'nan'):
return tok
clean = tok.replace(','... | No issues found. | else:
integer_part = tok.replace(',', '')
return "{:,}".format(int(integer_part))
def clean_single_num(num_str:str)->str:
tok = unicodedata.normalize('NFKC', num_str)
if tok.lower() in ('inf', 'infinity', 'nan'):
return tok
clean = tok.replace(','... | @@ -10,7 +10,7 @@
import traceback, socket, unicodedata, urllib.request, uuid, zipfile, fitz, multiprocessing
import ebooklib, gradio as gr, psutil, regex as re, requests, stanza, importlib, queue
-from typing import Any, TypeAlias, Generator, Callable, Iterable, Dict
+from typing import Any, TypeAlias, Generator, ... | lib/core.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.1 | 1,612 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
# ROCm
# ============================================================
elif has_working_rocm() and has_amd_gpu_pci():
version = ''
msg = ''
if os.name == 'posix':
for p in (
'/opt/rocm/.info/ve... | No issues found. | # ROCm
# ============================================================
elif has_working_rocm() and has_amd_gpu_pci():
version = ''
msg = ''
if os.name == 'posix':
for p in (
'/opt/rocm/.info/ve... | @@ -2,6 +2,7 @@
from functools import cached_property
from typing import Union
+from glob import glob
from importlib.metadata import version, PackageNotFoundError
from lib.conf import *
@@ -889,6 +890,27 @@ def install_device_packages(self, device_info_str:str)->int:
error =... | lib/classes/device_installer.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.1 | 1,615 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
raise ValueError(error)
def _check_xtts_builtin_speakers(self, current_voice:str, speaker:str)->str|bool:
new_current_voice = ''
proc_current_voice = ''
try:
import torch
import torchaudio
import numpy as np
from huggingface_hub im... | No issues found. | raise ValueError(error)
def _check_xtts_builtin_speakers(self, current_voice:str, speaker:str)->str|bool:
new_current_voice = ''
proc_current_voice = ''
try:
import torch
import torchaudio
import numpy as np
from huggingface_hub im... | @@ -458,12 +458,12 @@ def _convert_sml(self, sml:str)->tuple[bool, str]:
value = m.group('value')
assert tag in TTS_SML, f'Unknown SML tag: {tag!r}'
if tag == 'break':
- silence_time = float(int(np.random.uniform(0.3, 0.6) * 100) / 100)
+ silence_time = float(int(np.rand... | lib/classes/tts_engines/common/utils.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.5b1 | 1,618 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
BUILD_DOCKER = 'build_docker'
debug_mode = False
# ---------------------------------------------------------------------
# Python environment references
# ---------------------------------------------------------------------
python_env_dir = os.path.abspath(os.path.join('.','python_env'))
requirements_file ... | No issues found. | BUILD_DOCKER = 'build_docker'
debug_mode = False
# ---------------------------------------------------------------------
# Python environment references
# ---------------------------------------------------------------------
python_env_dir = os.path.abspath(os.path.join('.','python_env'))
requirements_file ... | @@ -69,6 +69,13 @@
debug_mode = False
+# ---------------------------------------------------------------------
+# Python environment references
+# ---------------------------------------------------------------------
+
+python_env_dir = os.path.abspath(os.path.join('.','python_env'))
+requirements_file = o... | lib/conf.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.19 | 1,632 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
all_group.add_argument(options[0], type=str, help=argparse.SUPPRESS)
parser.add_argument(options[1], type=str, help='''Session to resume the conversion in case of interruption, crash,
or reuse of custom models and custom cloning voices.''')
gui_group = parser.add_argument_group('**** The following opti... | No issues found. | all_group.add_argument(options[0], type=str, help=argparse.SUPPRESS)
parser.add_argument(options[1], type=str, help='''Session to resume the conversion in case of interruption, crash,
or reuse of custom models and custom cloning voices.''')
gui_group = parser.add_argument_group('**** The following opti... | @@ -70,7 +70,7 @@ def kill_previous_instances(script_name: str):
def main()->None:
wsl_cmd = ''
- if os.environ.get('DOCKER_IN_WSL', 0) == "1":
+ if os.environ.get('DOCKER_IN_WSL', '0') == "1":
wsl_cmd = 'wsl --user root --'
# Argument parser to handle optional parameters with descriptions
... | app.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.26 | 1,642 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
language="be",
with_stress=True
)
else:
part_phonemized = part
if self.params['current_voice'] is not None:
proc_dir = os.pa... | No issues found. | language="be",
with_stress=True
)
else:
part_phonemized = part
if self.params['current_voice'] is not None:
proc_dir = os.pa... | @@ -20,8 +20,6 @@ def __init__(self, session:DictProxy):
#random.seed(seed)
self.amp_dtype = self._apply_gpu_policy(enough_vram=enough_vram, seed=seed)
self.xtts_speakers = self._load_xtts_builtin_list()
- self.engine = self.load_engine()
- self.engine_zs = s... | lib/classes/tts_engines/glowtts.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.26 | 1,644 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
msg = f'TTS {self.tts_key} Loaded!'
print(msg)
return engine
except Exception as e:
error = 'load_engine(): engine is None'
raise RuntimeError(error)
def convert(self, sentence_index:int, sentence:str)->bool:
try:
import torch
... | No issues found. | msg = f'TTS {self.tts_key} Loaded!'
print(msg)
return engine
except Exception as e:
error = 'load_engine(): engine is None'
raise RuntimeError(error)
def convert(self, sentence_index:int, sentence:str)->bool:
try:
import torch
... | @@ -15,7 +15,17 @@ def __init__(self, session:DictProxy):
self.audio_segments = []
self.models = load_engine_presets(self.session['tts_engine'])
self.params = {}
- self.params['samplerate'] = self.models[self.session['fine_tuned']]['samplerate']
+ fine_tuned ... | lib/classes/tts_engines/yourtts.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.26 | 1,646 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
parser.add_argument(options[1], type=str, help='''Session to resume the conversion in case of interruption, crash,
or reuse of custom models and custom cloning voices.''')
gui_group = parser.add_argument_group('**** The following option are for gradio/gui mode only', 'Optional')
gui_group.add_argument(... | No issues found. | parser.add_argument(options[1], type=str, help='''Session to resume the conversion in case of interruption, crash,
or reuse of custom models and custom cloning voices.''')
gui_group = parser.add_argument_group('**** The following option are for gradio/gui mode only', 'Optional')
gui_group.add_argument(... | @@ -115,23 +115,20 @@ def main()->None:
{wsl_cmd} docker run -v "./ebooks:/app/ebooks" -v "./audiobooks:/app/audiobooks" -v "./models:/app/models" -v "./voices:/app/voices" -v "/my/real/ebooks/folder/absolute/path:/app/another_ebook_folder" --device=/dev/dri --rm -it -p 7860:7860 ebook2audiobook:xpu --headles... | app.py | 0 | Python | 1 | none | 16 | 51 | 51 | true | v26.2.26 | 1,647 | DrewThomasson/ebook2audiobook | 13,365 | Python | ROBERT-MCDOWELL | |
Assert.assertEquals("\'1234\'", StringUtils.quote("1234"));
}
@Test
public void testRepeat() {
Assert.assertNull(StringUtils.repeat(null, -1635778558));
Assert.assertEquals("", StringUtils.repeat("", 3));
Assert.assertEquals("\u0000\u0000", StringUtils.repeat("\u0000", 2));
... | No issues found. | Assert.assertEquals("\'1234\'", StringUtils.quote("1234"));
}
@Test
public void testRepeat() {
Assert.assertNull(StringUtils.repeat(null, -1635778558));
Assert.assertEquals("", StringUtils.repeat("", 3));
Assert.assertEquals("\u0000\u0000", StringUtils.repeat("\u0000", 2));
... | @@ -412,4 +412,21 @@ public void testWrap() {
public void testClassLoaderHash() {
Assert.assertEquals("null", StringUtils.classLoaderHash(null));
}
+
+ @Test
+ public void testNormalizeNull() {
+ Assert.assertNull(StringUtils.normalizeClassName(null));
+ }
+
+ @Test
+ public voi... | core/src/test/java/com/taobao/arthas/core/util/StringUtilsTest.java | 0 | Java | 1 | none | 16 | 51 | 51 | true | 命令行处理类名时,自动替换/为. | 3,017 | alibaba/arthas | 31,469 | Java | ZenCGL | |
" @Boolean[true],\n" +
" @Boolean[true],\n" +
"]";
Assert.assertEquals(expected, objectView.draw());
}
@Test
public void testCharArray() {
char[] data = {'a', 'b', 'c', 'd'};
ObjectView objectView = new ObjectView(data, 3);
... | No issues found. | " @Boolean[true],\n" +
" @Boolean[true],\n" +
"]";
Assert.assertEquals(expected, objectView.draw());
}
@Test
public void testCharArray() {
char[] data = {'a', 'b', 'c', 'd'};
ObjectView objectView = new ObjectView(data, 3);
... | @@ -189,6 +189,23 @@ public void testThrowable() {
Assert.assertTrue(objectView.draw().startsWith("java.lang.Exception: test"));
}
+ @Test
+ public void testEnum() {
+ EnumDemo t = EnumDemo.DEMO;
+ ObjectView objectView = new ObjectView(t, 3);
+ Assert.assertEquals("@EnumDemo[... | core/src/test/java/com/taobao/arthas/core/view/ObjectViewTest.java | 0 | Java | 1 | none | 16 | 51 | 51 | true | fix bug of enum obj | 3,041 | alibaba/arthas | 31,469 | Java | leizhiyuan | |
* - intervalMs: 刷新属性值时间间隔 (ms) (-i),required=false
* - numberOfExecutions: 刷新次数 (-n),若未指定或 <=0 则使用 DEFAULT_NUMBER_OF_EXECUTIONS
* - regex: 是否启用正则匹配 (-E),required=false
*/
@Tool(
name = "mbean",
description = "MBean 诊断工具: 查看或监控 MBean 属性信息,对应 Arthas 的 mbean 命令。",
streamable... | No issues found. | * - intervalMs: 刷新属性值时间间隔 (ms) (-i),required=false
* - numberOfExecutions: 刷新次数 (-n),若未指定或 <=0 则使用 DEFAULT_NUMBER_OF_EXECUTIONS
* - regex: 是否启用正则匹配 (-E),required=false
*/
@Tool(
name = "mbean",
description = "MBean 诊断工具: 查看或监控 MBean 属性信息,对应 Arthas 的 mbean 命令。",
streamable... | @@ -98,22 +98,7 @@ public String mbean(
String commandStr = cmd.toString();
logger.info("Starting mbean execution: {}", commandStr);
- // 使用同步执行的情况:查看元数据 或者 不需要流式输出
- if (Boolean.TRUE.equals(metadata) || !needStreamOutput) {
- logger.info("Executing sync ... | labs/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/function/jvm300/MBeanTool.java | 0 | Java | 1 | none | 16 | 51 | 51 | true | feat: mcp serialization fix | 3,058 | alibaba/arthas | 31,469 | Java | Yeaury | |
/**
* Bearer Token {@link Principal}.
*/
public final class BearerPrincipal implements Principal {
private final String token;
public BearerPrincipal(String token) {
this.token = token;
}
@Override
public String getName() {
return "bearer";
}
public String getToken() {... | No issues found. |
/**
* Bearer Token {@link Principal}.
*/
public final class BearerPrincipal implements Principal {
private final String token;
public BearerPrincipal(String token) {
this.token = token;
}
@Override
public String getName() {
return "bearer";
}
public String getToken() {... | @@ -0,0 +1,55 @@
+package com.taobao.arthas.core.security;
+
+import java.security.Principal;
+
+/**
+ * Bearer Token {@link Principal}.
+ */
+public final class BearerPrincipal implements Principal {
+
+ private final String token;
+
+ public BearerPrincipal(String token) {
+ this.token = token;
+ }
+
... | core/src/main/java/com/taobao/arthas/core/security/BearerPrincipal.java | 0 | Java | 1 | none | 16 | 51 | 51 | true | feat: Add Bearer Token authentication support for MCP requests | 3,059 | alibaba/arthas | 31,469 | Java | Yeaury | |
session.setAttribute(ArthasConstants.SUBJECT_KEY, subject);
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpResponse) {
// write cookie
HttpResponse response = (HttpR... | No issues found. | session.setAttribute(ArthasConstants.SUBJECT_KEY, subject);
}
}
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
if (msg instanceof HttpResponse) {
// write cookie
HttpResponse response = (HttpR... | @@ -47,20 +47,24 @@ public BasicHttpAuthenticatorHandler(HttpSessionManager httpSessionManager) {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
- if (!securityAuthenticator.needLogin()) {
+ // 先处理非 HttpRequest 消息
+ if (!(msg instanceof HttpR... | core/src/main/java/com/taobao/arthas/core/shell/term/impl/http/BasicHttpAuthenticatorHandler.java | 0 | Java | 1 | none | 16 | 51 | 51 | true | feat: add userId tracking for usage statistics across all command execution paths | 3,087 | alibaba/arthas | 31,469 | Java | hengyunabc | |
cmd.append(" --delete-all");
break;
default:
throw new IllegalArgumentException("Unsupported action: " + ttAction +
". Supported actions: record(t), list(l), info(i), search(s), replay(p), delete(d), deleteAll(da)");
}
... | No issues found. | cmd.append(" --delete-all");
break;
default:
throw new IllegalArgumentException("Unsupported action: " + ttAction +
". Supported actions: record(t), list(l), info(i), search(s), replay(p), delete(d), deleteAll(da)");
}
... | @@ -48,19 +48,23 @@ public String timeTunnel(
@ToolParam(description = "Class最大匹配数量,防止匹配到的Class数量太多导致JVM挂起,默认50", required = false)
Integer maxMatchCount,
+ @ToolParam(description = "命令执行超时时间,单位为秒,默认200秒。超时后命令自动退出(仅record操作)", required = false)
+ Integer timeout,
+
... | labs/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/function/monitor200/TimeTunnelTool.java | 0 | Java | 1 | none | 16 | 51 | 51 | true | watch/trace support timeout | 3,089 | alibaba/arthas | 31,469 | Java | hengyunabc | |
}
}
private static boolean checkCommandCompletion(Map<String, Object> results, int currentAllowInputCount) {
if (results == null) {
return false;
}
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) results.get("results");
... | No issues found. | }
}
private static boolean checkCommandCompletion(Map<String, Object> results, int currentAllowInputCount) {
if (results == null) {
return false;
}
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) results.get("results");
... | @@ -22,9 +22,11 @@ public final class StreamableToolUtils {
private static final Logger logger = LoggerFactory.getLogger(StreamableToolUtils.class);
private static final int DEFAULT_POLL_INTERVAL_MS = 100; // 默认轮询间隔100ms
+
private static final int ERROR_RETRY_INTERVAL_MS = 500; // 错误重试间隔500ms
... | labs/arthas-mcp-server/src/main/java/com/taobao/arthas/mcp/server/tool/function/StreamableToolUtils.java | 0 | Java | 1 | none | 16 | 51 | 51 | true | Feature: Refactor MCP Server Architecture to Streamable or Stateless Single Service | 3,096 | alibaba/arthas | 31,469 | Java | Yeaury | |
return {
success: false,
method: 'failed',
error: 'document.body is not available'
};
}
textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.top = '-9999px';
textarea.style.left = '-9999px';
... | No issues found. | return {
success: false,
method: 'failed',
error: 'document.body is not available'
};
}
textarea = document.createElement('textarea');
textarea.value = text;
textarea.style.position = 'fixed';
textarea.style.top = '-9999px';
textarea.style.left = '-9999px';
... | @@ -0,0 +1,139 @@
+/**
+ * Universal clipboard utility with modern API and fallback support
+ * Handles various security contexts and browser compatibility issues
+ */
+
+export interface ClipboardResult {
+ success: boolean;
+ method: 'clipboard-api' | 'execCommand' | 'failed';
+ error?: string;
+}
+
+/**
+ * Copy ... | archon-ui-main/src/features/shared/utils/clipboard.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: Universal clipboard utility with improved copy functionality | 663 | coleam00/Archon | 12,735 | Python | tazmon95 | |
// Read the configuration and set its `rootDir`
// 1. If it's a `package.json` file, we look into its "jest" property
// 2. For any other file, we just require it. If we receive an 'ERR_REQUIRE_ESM'
// from node, perform a dynamic import instead.
export default async function readConfigFileAndSetRootDir(
configPat... | No issues found. | // Read the configuration and set its `rootDir`
// 1. If it's a `package.json` file, we look into its "jest" property
// 2. For any other file, we just require it. If we receive an 'ERR_REQUIRE_ESM'
// from node, perform a dynamic import instead.
export default async function readConfigFileAndSetRootDir(
configPat... | @@ -10,55 +10,49 @@ import * as fs from 'fs';
import {Config} from '@jest/types';
// @ts-ignore: vendored
import jsonlint from './vendor/jsonlint';
-import {
- JEST_CONFIG_EXT_JSON,
- JEST_CONFIG_EXT_MJS,
- PACKAGE_JSON,
-} from './constants';
-import importMjs from './importMjs';
+import {JEST_CONFIG_EXT_JSON, P... | packages/jest-config/src/readConfigFileAndSetRootDir.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Handle ERR_REQUIRE_ESM when reading configuration | 9,573 | jestjs/jest | 45,309 | TypeScript | azz | |
type,
triggerAsyncId,
resource: {} | NodeJS.Timeout,
) {
// Skip resources that should not generally prevent the process from
// exiting, not last a meaningfully long time, or otherwise shouldn't be
// tracked.
if (type === 'PROMISE') {
return;
}
const e... | No issues found. | type,
triggerAsyncId,
resource: {} | NodeJS.Timeout,
) {
// Skip resources that should not generally prevent the process from
// exiting, not last a meaningfully long time, or otherwise shouldn't be
// tracked.
if (type === 'PROMISE') {
return;
}
const e... | @@ -83,16 +83,7 @@ export default function collectHandles(): HandleCollectionResult {
// Skip resources that should not generally prevent the process from
// exiting, not last a meaningfully long time, or otherwise shouldn't be
// tracked.
- if (
- type === 'PROMISE' ||
- type ==... | packages/jest-core/src/collectHandles.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Improve `detectOpenHandles` | 13,417 | jestjs/jest | 45,309 | TypeScript | liuxingbaoyu | |
// absolute
expect(
resolveConfigPath(path.dirname(absolutePackageJsonPath), DIR),
).toBe(absoluteJestConfigPath);
// relative
expect(
resolveConfigPath(path.dirname(relativePackageJsonPath), DIR),
).toBe(absoluteJestConfigPath);
// jest.config.js and package.... | No issues found. | // absolute
expect(
resolveConfigPath(path.dirname(absolutePackageJsonPath), DIR),
).toBe(absoluteJestConfigPath);
// relative
expect(
resolveConfigPath(path.dirname(relativePackageJsonPath), DIR),
).toBe(absoluteJestConfigPath);
// jest.config.js and package.... | @@ -112,6 +112,72 @@ describe.each(JEST_CONFIG_EXT_ORDER.slice(0))(
);
}).toThrow(NO_ROOT_DIR_ERROR_PATTERN);
});
+
+ test('file path from "jest" key', () => {
+ const anyFileName = `anyJestConfigfile${extension}`;
+ const relativePackageJsonPath = 'a/b/c/package.json';
+ const re... | packages/jest-config/src/__tests__/resolveConfigPath.test.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Feat/load referenced config from packagejson | 14,044 | jestjs/jest | 45,309 | TypeScript | rafaelrabelos | |
status: 'passed',
},
],
name: 'Test describe',
passed: true,
},
],
name: '/',
passed: true,
performanceInfo: {
end: 30,
runtime: 20,
slow: false,
start: 10,
},
... | No issues found. | status: 'passed',
},
],
name: 'Test describe',
passed: true,
},
],
name: '/',
passed: true,
performanceInfo: {
end: 30,
runtime: 20,
slow: false,
start: 10,
},
... | @@ -8,17 +8,25 @@
import type {
AggregatedResult,
AssertionResult,
+ Status,
Test,
TestCaseResult,
TestResult,
} from '@jest/test-result';
+import {normalizeIcons} from '@jest/test-utils';
import type {Config} from '@jest/types';
-import GitHubActionsReporter from '../GitHubActionsReporter';
+import ... | packages/jest-reporters/src/__tests__/GitHubActionsReporter.test.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Fix skipped and todo tests in Github Actions Reporter | 14,309 | jestjs/jest | 45,309 | TypeScript | MatteoH2O1999 | |
}
getAllCoverageInfoCopy(): JestEnvironment['global']['__coverage__'] {
return deepCyclicCopy(this._environment.global.__coverage__);
}
getAllV8CoverageInfoCopy(): V8CoverageResult {
if (!this._v8CoverageResult || !this._v8CoverageSources) {
throw new Error('You need to call `stopCollectingV8Cov... | No issues found. | }
getAllCoverageInfoCopy(): JestEnvironment['global']['__coverage__'] {
return deepCyclicCopy(this._environment.global.__coverage__);
}
getAllV8CoverageInfoCopy(): V8CoverageResult {
if (!this._v8CoverageResult || !this._v8CoverageSources) {
throw new Error('You need to call `stopCollectingV8Cov... | @@ -416,12 +416,15 @@ export default class Runtime {
query = '',
): Promise<VMModule> {
const cacheKey = modulePath + query;
+ const registry = this._isolatedModuleRegistry
+ ? this._isolatedModuleRegistry
+ : this._esmoduleRegistry;
if (this._fileTransformsMutex.has(cacheKey)) {
... | packages/jest-runtime/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix: isolate esm async import bug | 14,397 | jestjs/jest | 45,309 | TypeScript | eryue0220 | |
if (!b.has(aValue)) {
let has = false;
for (const bValue of b) {
const isEqual = equals(aValue, bValue, filteredCustomTesters);
if (isEqual === true) {
has = true;
}
}
if (has === false) {
allFound = false;
... | No issues found. | if (!b.has(aValue)) {
let has = false;
for (const bValue of b) {
const isEqual = equals(aValue, bValue, filteredCustomTesters);
if (isEqual === true) {
has = true;
}
}
if (has === false) {
allFound = false;
... | @@ -390,12 +390,17 @@ export const arrayBufferEquality = (
a: unknown,
b: unknown,
): boolean | undefined => {
- if (!(a instanceof ArrayBuffer) || !(b instanceof ArrayBuffer)) {
- return undefined;
+ let dataViewA = a;
+ let dataViewB = b;
+
+ if (a instanceof ArrayBuffer && b instanceof ArrayBuffer) {
+... | packages/expect-utils/src/utils.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(expect-util): fix comparison of `DataView` | 14,408 | jestjs/jest | 45,309 | TypeScript | Dunqing | |
return `Any<${fnNameFor(this.sample)}>`;
}
}
class Anything extends AsymmetricMatcher<void> {
asymmetricMatch(other: unknown) {
return other != null;
}
toString() {
return 'Anything';
}
// No getExpectedType method, because it matches either null or undefined.
override toAsymmetricMatcher(... | No issues found. | return `Any<${fnNameFor(this.sample)}>`;
}
}
class Anything extends AsymmetricMatcher<void> {
asymmetricMatch(other: unknown) {
return other != null;
}
toString() {
return 'Anything';
}
// No getExpectedType method, because it matches either null or undefined.
override toAsymmetricMatcher(... | @@ -8,6 +8,7 @@
import {
equals,
+ getObjectKeys,
isA,
iterableEquality,
subsetEquality,
@@ -52,7 +53,10 @@ function getPrototype(obj: object) {
return obj.constructor.prototype;
}
-export function hasProperty(obj: object | null, property: string): boolean {
+export function hasProperty(
+ obj: o... | packages/expect/src/asymmetricMatchers.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix: symbol key could not be enum. | 14,414 | jestjs/jest | 45,309 | TypeScript | eryue0220 | |
);
for (const [nodeGlobalsKey, descriptor] of nodeGlobals) {
if (!contextGlobals.has(nodeGlobalsKey)) {
if (descriptor.configurable) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
get() {
... | No issues found. | );
for (const [nodeGlobalsKey, descriptor] of nodeGlobals) {
if (!contextGlobals.has(nodeGlobalsKey)) {
if (descriptor.configurable) {
Object.defineProperty(global, nodeGlobalsKey, {
configurable: true,
enumerable: descriptor.enumerable,
get() {
... | @@ -27,16 +27,19 @@ const denyList = new Set([
'GLOBAL',
'root',
'global',
+ 'globalThis',
'Buffer',
'ArrayBuffer',
'Uint8Array',
// if env is loaded within a jest test
'jest-symbol-do-not-touch',
]);
+type GlobalProperties = Array<keyof typeof globalThis>;
+
const nodeGlobals = new Map(
- ... | packages/jest-environment-node/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix: make sure `atob` and `btoa` are writeable | 14,446 | jestjs/jest | 45,309 | TypeScript | SimenB | |
const questions = defaultQuestions.slice(0);
let hasJestProperty = false;
let projectPackageJson: ProjectPackageJson;
try {
projectPackageJson = JSON.parse(
fs.readFileSync(projectPackageJsonPath, 'utf-8'),
) as ProjectPackageJson;
} catch {
throw new MalformedPackageJsonError(projectPacka... | No issues found. |
const questions = defaultQuestions.slice(0);
let hasJestProperty = false;
let projectPackageJson: ProjectPackageJson;
try {
projectPackageJson = JSON.parse(
fs.readFileSync(projectPackageJsonPath, 'utf-8'),
) as ProjectPackageJson;
} catch {
throw new MalformedPackageJsonError(projectPacka... | @@ -7,10 +7,11 @@
import * as path from 'path';
import chalk = require('chalk');
+import exit = require('exit');
import * as fs from 'graceful-fs';
import prompts = require('prompts');
import {constants} from 'jest-config';
-import {tryRealpath} from 'jest-util';
+import {clearLine, tryRealpath} from 'jest-util'... | packages/create-jest/src/runCreate.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat(create-jest): Add `npm init` / `yarn create` initialiser | 14,453 | jestjs/jest | 45,309 | TypeScript | dj-stormtrooper | |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk = require('chalk');
import type {Config} from '@jest/types';
import {isNonNullable} from 'jest-util';
const active... | No issues found. | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk = require('chalk');
import type {Config} from '@jest/types';
import {isNonNullable} from 'jest-util';
const active... | @@ -7,11 +7,9 @@
import chalk = require('chalk');
import type {Config} from '@jest/types';
+import {isNonNullable} from 'jest-util';
-const activeFilters = (
- globalConfig: Config.GlobalConfig,
- delimiter = '\n',
-): string => {
+const activeFilters = (globalConfig: Config.GlobalConfig): string => {
const ... | packages/jest-core/src/lib/activeFiltersMessage.ts | 0 | TypeScript | 1 | none | 16 | 35 | 35 | true | Simplify active filters | 14,461 | jestjs/jest | 45,309 | TypeScript | Connormiha | |
' "color": "#99424F",',
' }',
' }',
' >',
' painless JavaScript testing',
' </dd>,',
']',
].join('\n');
expect(formatElement(val)).toEqual(expected);
expect(
formatTestObject(val.map(element => renderer.create(element).toJSON())),
).toEqual(expected);
});
des... | No issues found. | ' "color": "#99424F",',
' }',
' }',
' >',
' painless JavaScript testing',
' </dd>,',
']',
].join('\n');
expect(formatElement(val)).toEqual(expected);
expect(
formatTestObject(val.map(element => renderer.create(element).toJSON())),
).toEqual(expected);
});
des... | @@ -48,10 +48,7 @@ test('supports a single element with non-empty string child', () => {
});
test('supports a single element with empty string child', () => {
- assertPrintedJSX(
- React.createElement('Mouse', null, ''),
- '<Mouse>\n \n</Mouse>',
- );
+ assertPrintedJSX(React.createElement('Mouse', null, ... | packages/pretty-format/src/__tests__/react.test.tsx | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(pretty-format): Handle empty string children in React same as `react-test-renderer` | 14,470 | jestjs/jest | 45,309 | TypeScript | SimenB | |
* @param tests All tests
* @param options shardIndex and shardIndex to select
*
* @example
* ```typescript
* class CustomSequencer extends Sequencer {
* shard(tests, { shardIndex, shardCount }) {
* const shardSize = Math.ceil(tests.length / options.shardCount);
* const shardStart = sha... | No issues found. | * @param tests All tests
* @param options shardIndex and shardIndex to select
*
* @example
* ```typescript
* class CustomSequencer extends Sequencer {
* shard(tests, { shardIndex, shardCount }) {
* const shardSize = Math.ceil(tests.length / options.shardCount);
* const shardStart = sha... | @@ -16,7 +16,9 @@ const FAIL = 0;
const SUCCESS = 1;
type Cache = {
- [key: string]: [0 | 1, number] | undefined;
+ [key: string]:
+ | [testStatus: typeof FAIL | typeof SUCCESS, testDuration: number]
+ | undefined;
};
export type ShardOptions = {
@@ -42,7 +44,7 @@ type ShardPositionOptions = ShardOption... | packages/jest-test-sequencer/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix(test-sequencer): correctly figure out test runtime | 14,473 | jestjs/jest | 45,309 | TypeScript | SimenB | |
import hg from './hg';
import sl from './sl';
import type {ChangedFilesPromise, Options, Repos} from './types';
export type {ChangedFiles, ChangedFilesPromise} from './types';
// This is an arbitrary number. The main goal is to prevent projects with
// many roots (50+) from spawning too many processes at once.
const ... | No issues found. | import hg from './hg';
import sl from './sl';
import type {ChangedFilesPromise, Options, Repos} from './types';
export type {ChangedFiles, ChangedFilesPromise} from './types';
// This is an arbitrary number. The main goal is to prevent projects with
// many roots (50+) from spawning too many processes at once.
const ... | @@ -11,9 +11,7 @@ import {isNonNullable} from 'jest-util';
import git from './git';
import hg from './hg';
import sl from './sl';
-import type {ChangedFilesPromise, Options, Repos, SCMAdapter} from './types';
-
-type RootPromise = ReturnType<SCMAdapter['getRoot']>;
+import type {ChangedFilesPromise, Options, Repos} ... | packages/jest-changed-files/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | changed-files: simplify find repos | 14,503 | jestjs/jest | 45,309 | TypeScript | Connormiha | |
const tick = promisify(setImmediate);
export default class LeakDetector {
private _isReferenceBeingHeld: boolean;
private readonly _finalizationRegistry?: FinalizationRegistry<undefined>;
constructor(value: unknown) {
if (isPrimitive(value)) {
throw new TypeError(
[
'Primitives canno... | No issues found. | const tick = promisify(setImmediate);
export default class LeakDetector {
private _isReferenceBeingHeld: boolean;
private readonly _finalizationRegistry?: FinalizationRegistry<undefined>;
constructor(value: unknown) {
if (isPrimitive(value)) {
throw new TypeError(
[
'Primitives canno... | @@ -7,7 +7,7 @@
/// <reference lib="es2021.WeakRef" />
import {promisify} from 'util';
-import {setFlagsFromString} from 'v8';
+import {getHeapSnapshot, setFlagsFromString} from 'v8';
import {runInNewContext} from 'vm';
import {isPrimitive} from 'jest-get-type';
import {format as prettyFormat} from 'pretty-forma... | packages/jest-leak-detector/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | fix: make leak-detector more aggressive when running GC | 14,526 | jestjs/jest | 45,309 | TypeScript | SimenB | |
try {
const {stdout: statusStdout} = execa.sync(
'git',
['status', '--porcelain'],
{cwd},
);
if (statusStdout.length > 0) {
throw new Error(
'Repo is not clean - cannot run type tests with old typescript version',
);
}
execa.sync('yarn', ['add', tsconfigBase... | No issues found. | try {
const {stdout: statusStdout} = execa.sync(
'git',
['status', '--porcelain'],
{cwd},
);
if (statusStdout.length > 0) {
throw new Error(
'Repo is not clean - cannot run type tests with old typescript version',
);
}
execa.sync('yarn', ['add', tsconfigBase... | @@ -12,9 +12,22 @@ import chalk from 'chalk';
import execa from 'execa';
import fs from 'graceful-fs';
import stripJsonComments from 'strip-json-comments';
+/* eslint-disable import/order */
import tempy from 'tempy';
const require = createRequire(import.meta.url);
+const rootPackageJson = require('../package.js... | scripts/verifyOldTs.mjs | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | chore: use `@tsconfig/node16` | 14,547 | jestjs/jest | 45,309 | TypeScript | mrazauskas | |
async function buildNodePackages() {
process.stdout.write(chalk.inverse(' Bundling packages \n'));
const buildConfigs = createBuildConfigs();
const compiler = webpack(createWebpackConfigs(buildConfigs));
let stats;
try {
stats = await util.promisify(compiler.run.bind(compiler))();
await util.promis... | No issues found. | async function buildNodePackages() {
process.stdout.write(chalk.inverse(' Bundling packages \n'));
const buildConfigs = createBuildConfigs();
const compiler = webpack(createWebpackConfigs(buildConfigs));
let stats;
try {
stats = await util.promisify(compiler.run.bind(compiler))();
await util.promis... | @@ -6,18 +6,23 @@
*/
import {strict as assert} from 'assert';
+import {createRequire} from 'module';
import * as path from 'path';
import util from 'util';
import chalk from 'chalk';
+import dedent from 'dedent';
import fs from 'graceful-fs';
import webpack from 'webpack';
import {
ERROR,
OK,
create... | scripts/build.mjs | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | fix: add ESM exports of all modules manually | 14,661 | jestjs/jest | 45,309 | TypeScript | SimenB | |
await fs.promises.writeFile(
path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../api-extractor.json',
),
JSON.stringify(sharedExtractorConfig, null, 2),
);
const eslint = new ESLint({
cwd: process.cwd(),
fix: true,
overrideConfig: {
rules: {
// `d.ts` files are by nature `type... | No issues found. | await fs.promises.writeFile(
path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../api-extractor.json',
),
JSON.stringify(sharedExtractorConfig, null, 2),
);
const eslint = new ESLint({
cwd: process.cwd(),
fix: true,
overrideConfig: {
rules: {
// `d.ts` files are by nature `type... | @@ -14,16 +14,12 @@ import {
ExtractorConfig,
} from '@microsoft/api-extractor';
import chalk from 'chalk';
+import {ESLint} from 'eslint';
import {glob} from 'glob';
import fs from 'graceful-fs';
import pkgDir from 'pkg-dir';
-import prettier from 'prettier';
import {rimraf} from 'rimraf';
-import {copyrightS... | scripts/bundleTs.mjs | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | chore: cleanup imports in `d.ts` files | 14,663 | jestjs/jest | 45,309 | TypeScript | SimenB | |
const doNotFake = [
'Date' as const,
'hrtime' as const,
'nextTick' as const,
'performance' as const,
'queueMicrotask' as const,
'requestAnimationFrame' as const,
'cancelAnimationFrame' as const,
'requestIdleCallback' as const,
'cancelIdleCallback' as const,
... | No issues found. | const doNotFake = [
'Date' as const,
'hrtime' as const,
'nextTick' as const,
'performance' as const,
'queueMicrotask' as const,
'requestAnimationFrame' as const,
'cancelAnimationFrame' as const,
'requestIdleCallback' as const,
'cancelIdleCallback' as const,
... | @@ -5,115 +5,126 @@
* LICENSE file in the root directory of this source tree.
*/
-import {expectAssignable, expectNotAssignable} from 'tsd-lite';
-import type {Config} from '@jest/types';
+import {describe, expect, test} from 'tstyche';
+import type {Config} from 'jest';
-expectAssignable<Config.InitialOptions>... | packages/jest-types/__typetests__/config.test.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | chore: migrate the `Config` type test to TSTyche | 14,687 | jestjs/jest | 45,309 | TypeScript | mrazauskas | |
runScripts: 'dangerously',
url: 'http://localhost/',
virtualConsole,
...projectConfig.testEnvironmentOptions,
},
);
const global = (this.global = this.dom.window as unknown as Win);
if (global == null) {
throw new Error('JSDOM did not return a Window object');
... | No issues found. | runScripts: 'dangerously',
url: 'http://localhost/',
virtualConsole,
...projectConfig.testEnvironmentOptions,
},
);
const global = (this.global = this.dom.window as unknown as Win);
if (global == null) {
throw new Error('JSDOM did not return a Window object');
... | @@ -0,0 +1,191 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ */
+
+import type {Context} from 'vm';
+import type * as jsdom from 'jsdom';
+import type {
+ EnvironmentCo... | packages/jest-environment-jsdom-abstract/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: introduce helper package for implementing a custom JSDOM enviroment | 14,717 | jestjs/jest | 45,309 | TypeScript | SimenB | |
'eslint-comments/no-unlimited-disable': 'off',
},
},
{
files: [
'e2e/error-on-deprecated/__tests__/*',
'e2e/jasmine-async/__tests__/*',
],
globals: {
fail: 'readonly',
jasmine: 'readonly',
pending: 'readonly',
},
},
{
fi... | No issues found. | 'eslint-comments/no-unlimited-disable': 'off',
},
},
{
files: [
'e2e/error-on-deprecated/__tests__/*',
'e2e/jasmine-async/__tests__/*',
],
globals: {
fail: 'readonly',
jasmine: 'readonly',
pending: 'readonly',
},
},
{
fi... | @@ -34,6 +34,7 @@ module.exports = {
'plugin:import/errors',
'plugin:eslint-comments/recommended',
'plugin:prettier/recommended',
+ 'plugin:unicorn/recommended',
],
globals: {
console: 'readonly',
@@ -417,7 +418,7 @@ module.exports = {
parserOptions: {
sourceType: 'module',
},
- ... | .eslintrc.cjs | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | chore: opt out of unused unicorn ESLint rules | 14,795 | jestjs/jest | 45,309 | TypeScript | SimenB | |
'@typescript-eslint/explicit-module-boundary-types': 'off',
},
},
{
files: [
'packages/jest-jasmine2/src/jasmine/**/*',
'packages/expect-utils/src/jasmineUtils.ts',
],
rules: {
'eslint-comments/disable-enable-pair': 'off',
'eslint-comments/no-unlim... | No issues found. | '@typescript-eslint/explicit-module-boundary-types': 'off',
},
},
{
files: [
'packages/jest-jasmine2/src/jasmine/**/*',
'packages/expect-utils/src/jasmineUtils.ts',
],
rules: {
'eslint-comments/disable-enable-pair': 'off',
'eslint-comments/no-unlim... | @@ -439,6 +439,19 @@ module.exports = {
'unicorn/prefer-top-level-await': 'error',
},
},
+ {
+ files: [
+ 'e2e/coverage-report/__mocks__/sumDependency.js',
+ 'e2e/require-main-after-create-require/empty.js',
+ 'packages/create-jest/src/__tests__/__fixtures__/**/*',
+ ... | .eslintrc.cjs | 0 | JavaScript | 1 | none | 16 | 51 | 51 | true | chore: prefer `Date.now` | 14,811 | jestjs/jest | 45,309 | TypeScript | SimenB | |
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk = require('chalk');
import type {Config} from '@jest/types';
import {
type ChangedFilesPromise,
getChangedFiles... | No issues found. | /**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import chalk = require('chalk');
import type {Config} from '@jest/types';
import {
type ChangedFilesPromise,
getChangedFiles... | @@ -18,16 +18,10 @@ export default function getChangedFilesPromise(
configs: Array<Config.ProjectConfig>,
): ChangedFilesPromise | undefined {
if (globalConfig.onlyChanged) {
- const allRootsForAllProjects = configs.reduce<Array<string>>(
- (roots, config) => {
- if (config.roots) {
- roo... | packages/jest-core/src/getChangedFilesPromise.ts | 0 | TypeScript | 1 | none | 16 | 42 | 42 | true | fix: only check for watchman existence once per process | 14,826 | jestjs/jest | 45,309 | TypeScript | SimenB | |
async collectV8Coverage(): Promise<void> {
this._v8CoverageInstrumenter = new CoverageInstrumenter();
this._v8CoverageSources = new Map();
await this._v8CoverageInstrumenter.startInstrumenting();
}
async stopCollectingV8Coverage(): Promise<void> {
if (!this._v8CoverageInstrumenter || !this._v8C... | No issues found. |
async collectV8Coverage(): Promise<void> {
this._v8CoverageInstrumenter = new CoverageInstrumenter();
this._v8CoverageSources = new Map();
await this._v8CoverageInstrumenter.startInstrumenting();
}
async stopCollectingV8Coverage(): Promise<void> {
if (!this._v8CoverageInstrumenter || !this._v8C... | @@ -520,6 +520,11 @@ export default class Runtime {
initializeImportMeta: (meta: JestImportMeta) => {
meta.url = pathToFileURL(modulePath).href;
+ // @ts-expect-error Jest uses @types/node@16. Will be fixed when updated to @types/node@20.11.0
+ meta.filename = fil... | packages/jest-runtime/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: support import.meta.dirname and import.meta.filename | 14,854 | jestjs/jest | 45,309 | TypeScript | alesmenzel | |
}
}
if (this._environment.fakeTimers) {
this._environment.fakeTimers.clearAllTimers();
}
}
}
async collectV8Coverage(): Promise<void> {
this._v8CoverageInstrumenter = new CoverageInstrumenter();
this._v8CoverageSources = new Map();
await this._v8CoverageInstrumen... | No issues found. | }
}
if (this._environment.fakeTimers) {
this._environment.fakeTimers.clearAllTimers();
}
}
}
async collectV8Coverage(): Promise<void> {
this._v8CoverageInstrumenter = new CoverageInstrumenter();
this._v8CoverageSources = new Map();
await this._v8CoverageInstrumen... | @@ -518,12 +518,26 @@ export default class Runtime {
return this.linkAndEvaluateModule(module);
},
initializeImportMeta: (meta: JestImportMeta) => {
- meta.url = pathToFileURL(modulePath).href;
+ const metaUrl = pathToFileURL(modulePath).href;
+ ... | packages/jest-runtime/src/index.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | import.meta.resolve support | 14,930 | jestjs/jest | 45,309 | TypeScript | CheadleCheadle | |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {build} = require('@jridgewell/build-mapping');
const Handlebars = require('handlebars/dist/cjs/handlebars.js');
const dede... | No issues found. | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
const {build} = require('@jridgewell/build-mapping');
const Handlebars = require('handlebars/dist/cjs/handlebars.js');
const dede... | @@ -5,16 +5,14 @@
* LICENSE file in the root directory of this source tree.
*/
+const {build} = require('@jridgewell/build-mapping');
const Handlebars = require('handlebars/dist/cjs/handlebars.js');
-const {SourceMapConsumer, SourceNode} = require('source-map');
+const dedent = require('string-dedent');
expor... | e2e/coverage-handlebars/transform-handlebars.js | 0 | JavaScript | 1 | none | 16 | 19 | 19 | true | chore: remove source-map dep from E2E test | 14,933 | jestjs/jest | 45,309 | TypeScript | SimenB | |
test('unknown JestWorkerFarm', () => {
expect(unknownWorkerFarm).type.not.toHaveProperty('runTest');
expect(unknownWorkerFarm).type.not.toHaveProperty('runTestAsync');
expect(unknownWorkerFarm).type.not.toHaveProperty('getResult');
expect(unknownWorkerFarm).type.not.toHaveProperty('isResult');
expect(unknow... | No issues found. | test('unknown JestWorkerFarm', () => {
expect(unknownWorkerFarm).type.not.toHaveProperty('runTest');
expect(unknownWorkerFarm).type.not.toHaveProperty('runTestAsync');
expect(unknownWorkerFarm).type.not.toHaveProperty('getResult');
expect(unknownWorkerFarm).type.not.toHaveProperty('isResult');
expect(unknow... | @@ -5,96 +5,98 @@
* LICENSE file in the root directory of this source tree.
*/
-import {expectError, expectNotAssignable, expectType} from 'tsd-lite';
+import {expect, test} from 'tstyche';
import type {JestWorkerFarm} from 'jest-worker';
import type * as testWorker from './testWorker';
type TestWorker = {
... | packages/jest-worker/__typetests__/jest-worker.test.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | chore: migrate type test of `jest-worker` to TSTyche | 14,949 | jestjs/jest | 45,309 | TypeScript | mrazauskas | |
options: RunJestOptions,
): string {
if (options.stripAnsi) stream = stripAnsi(stream);
stream = normalizeIcons(stream);
return stream;
}
function normalizeStdoutAndStderrOnResult(
result: RunJestResult,
options: RunJestOptions,
): RunJestResult {
const stdout = normalizeStreamString(result.stdout, opti... | No issues found. | options: RunJestOptions,
): string {
if (options.stripAnsi) stream = stripAnsi(stream);
stream = normalizeIcons(stream);
return stream;
}
function normalizeStdoutAndStderrOnResult(
result: RunJestResult,
options: RunJestOptions,
): RunJestResult {
const stdout = normalizeStreamString(result.stdout, opti... | @@ -87,6 +87,7 @@ function spawnJest(
const env: NodeJS.ProcessEnv = {
...process.env,
FORCE_COLOR: '0',
+ NO_COLOR: '1',
...options.env,
};
| e2e/runJest.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | Update `@babel/code-frame` | 14,976 | jestjs/jest | 45,309 | TypeScript | nicolo-ribaudo | |
!retryImmediately
) {
deferredRetryTests.push(child);
}
break;
}
}
}
// Re-run failed tests n-times if configured
for (const test of deferredRetryTests) {
await rerunTest(test);
}
if (!isSkipped) {
for (const hook of afterAll) {
await _call... | No issues found. | !retryImmediately
) {
deferredRetryTests.push(child);
}
break;
}
}
}
// Re-run failed tests n-times if configured
for (const test of deferredRetryTests) {
await rerunTest(test);
}
if (!isSkipped) {
for (const hook of afterAll) {
await _call... | @@ -15,7 +15,7 @@ import shuffleArray, {
rngBuilder,
} from './shuffleArray';
import {dispatch, getState} from './state';
-import {RETRY_TIMES, WAIT_BEFORE_RETRY} from './types';
+import {RETRY_IMMEDIATELY, RETRY_TIMES, WAIT_BEFORE_RETRY} from './types';
import {
callAsyncCircusFn,
getAllHooksForDescribe,
@... | packages/jest-circus/src/run.ts | 0 | TypeScript | 1 | none | 16 | 51 | 51 | true | feat: add retryImmediately option to jest.retryTimes (#14696) | 14,977 | jestjs/jest | 45,309 | TypeScript | Vadimchesh |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.