Auto backup: 2026-02-21 07:01

This commit is contained in:
Krilly
2026-02-21 07:01:51 +00:00
parent 8757148122
commit 17b5b82d99
2012 changed files with 352552 additions and 331 deletions

View File

@@ -0,0 +1,247 @@
<#
.Synopsis
Activate a Python virtual environment for the current PowerShell session.
.Description
Pushes the python executable for a virtual environment to the front of the
$Env:PATH environment variable and sets the prompt to signify that you are
in a Python virtual environment. Makes use of the command line switches as
well as the `pyvenv.cfg` file values present in the virtual environment.
.Parameter VenvDir
Path to the directory that contains the virtual environment to activate. The
default value for this is the parent of the directory that the Activate.ps1
script is located within.
.Parameter Prompt
The prompt prefix to display when this virtual environment is activated. By
default, this prompt is the name of the virtual environment folder (VenvDir)
surrounded by parentheses and followed by a single space (ie. '(.venv) ').
.Example
Activate.ps1
Activates the Python virtual environment that contains the Activate.ps1 script.
.Example
Activate.ps1 -Verbose
Activates the Python virtual environment that contains the Activate.ps1 script,
and shows extra information about the activation as it executes.
.Example
Activate.ps1 -VenvDir C:\Users\MyUser\Common\.venv
Activates the Python virtual environment located in the specified location.
.Example
Activate.ps1 -Prompt "MyPython"
Activates the Python virtual environment that contains the Activate.ps1 script,
and prefixes the current prompt with the specified string (surrounded in
parentheses) while the virtual environment is active.
.Notes
On Windows, it may be required to enable this Activate.ps1 script by setting the
execution policy for the user. You can do this by issuing the following PowerShell
command:
PS C:\> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
For more information on Execution Policies:
https://go.microsoft.com/fwlink/?LinkID=135170
#>
Param(
[Parameter(Mandatory = $false)]
[String]
$VenvDir,
[Parameter(Mandatory = $false)]
[String]
$Prompt
)
<# Function declarations --------------------------------------------------- #>
<#
.Synopsis
Remove all shell session elements added by the Activate script, including the
addition of the virtual environment's Python executable from the beginning of
the PATH variable.
.Parameter NonDestructive
If present, do not remove this function from the global namespace for the
session.
#>
function global:deactivate ([switch]$NonDestructive) {
# Revert to original values
# The prior prompt:
if (Test-Path -Path Function:_OLD_VIRTUAL_PROMPT) {
Copy-Item -Path Function:_OLD_VIRTUAL_PROMPT -Destination Function:prompt
Remove-Item -Path Function:_OLD_VIRTUAL_PROMPT
}
# The prior PYTHONHOME:
if (Test-Path -Path Env:_OLD_VIRTUAL_PYTHONHOME) {
Copy-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME -Destination Env:PYTHONHOME
Remove-Item -Path Env:_OLD_VIRTUAL_PYTHONHOME
}
# The prior PATH:
if (Test-Path -Path Env:_OLD_VIRTUAL_PATH) {
Copy-Item -Path Env:_OLD_VIRTUAL_PATH -Destination Env:PATH
Remove-Item -Path Env:_OLD_VIRTUAL_PATH
}
# Just remove the VIRTUAL_ENV altogether:
if (Test-Path -Path Env:VIRTUAL_ENV) {
Remove-Item -Path env:VIRTUAL_ENV
}
# Just remove VIRTUAL_ENV_PROMPT altogether.
if (Test-Path -Path Env:VIRTUAL_ENV_PROMPT) {
Remove-Item -Path env:VIRTUAL_ENV_PROMPT
}
# Just remove the _PYTHON_VENV_PROMPT_PREFIX altogether:
if (Get-Variable -Name "_PYTHON_VENV_PROMPT_PREFIX" -ErrorAction SilentlyContinue) {
Remove-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Scope Global -Force
}
# Leave deactivate function in the global namespace if requested:
if (-not $NonDestructive) {
Remove-Item -Path function:deactivate
}
}
<#
.Description
Get-PyVenvConfig parses the values from the pyvenv.cfg file located in the
given folder, and returns them in a map.
For each line in the pyvenv.cfg file, if that line can be parsed into exactly
two strings separated by `=` (with any amount of whitespace surrounding the =)
then it is considered a `key = value` line. The left hand string is the key,
the right hand is the value.
If the value starts with a `'` or a `"` then the first and last character is
stripped from the value before being captured.
.Parameter ConfigDir
Path to the directory that contains the `pyvenv.cfg` file.
#>
function Get-PyVenvConfig(
[String]
$ConfigDir
) {
Write-Verbose "Given ConfigDir=$ConfigDir, obtain values in pyvenv.cfg"
# Ensure the file exists, and issue a warning if it doesn't (but still allow the function to continue).
$pyvenvConfigPath = Join-Path -Resolve -Path $ConfigDir -ChildPath 'pyvenv.cfg' -ErrorAction Continue
# An empty map will be returned if no config file is found.
$pyvenvConfig = @{ }
if ($pyvenvConfigPath) {
Write-Verbose "File exists, parse `key = value` lines"
$pyvenvConfigContent = Get-Content -Path $pyvenvConfigPath
$pyvenvConfigContent | ForEach-Object {
$keyval = $PSItem -split "\s*=\s*", 2
if ($keyval[0] -and $keyval[1]) {
$val = $keyval[1]
# Remove extraneous quotations around a string value.
if ("'""".Contains($val.Substring(0, 1))) {
$val = $val.Substring(1, $val.Length - 2)
}
$pyvenvConfig[$keyval[0]] = $val
Write-Verbose "Adding Key: '$($keyval[0])'='$val'"
}
}
}
return $pyvenvConfig
}
<# Begin Activate script --------------------------------------------------- #>
# Determine the containing directory of this script
$VenvExecPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$VenvExecDir = Get-Item -Path $VenvExecPath
Write-Verbose "Activation script is located in path: '$VenvExecPath'"
Write-Verbose "VenvExecDir Fullname: '$($VenvExecDir.FullName)"
Write-Verbose "VenvExecDir Name: '$($VenvExecDir.Name)"
# Set values required in priority: CmdLine, ConfigFile, Default
# First, get the location of the virtual environment, it might not be
# VenvExecDir if specified on the command line.
if ($VenvDir) {
Write-Verbose "VenvDir given as parameter, using '$VenvDir' to determine values"
}
else {
Write-Verbose "VenvDir not given as a parameter, using parent directory name as VenvDir."
$VenvDir = $VenvExecDir.Parent.FullName.TrimEnd("\\/")
Write-Verbose "VenvDir=$VenvDir"
}
# Next, read the `pyvenv.cfg` file to determine any required value such
# as `prompt`.
$pyvenvCfg = Get-PyVenvConfig -ConfigDir $VenvDir
# Next, set the prompt from the command line, or the config file, or
# just use the name of the virtual environment folder.
if ($Prompt) {
Write-Verbose "Prompt specified as argument, using '$Prompt'"
}
else {
Write-Verbose "Prompt not specified as argument to script, checking pyvenv.cfg value"
if ($pyvenvCfg -and $pyvenvCfg['prompt']) {
Write-Verbose " Setting based on value in pyvenv.cfg='$($pyvenvCfg['prompt'])'"
$Prompt = $pyvenvCfg['prompt'];
}
else {
Write-Verbose " Setting prompt based on parent's directory's name. (Is the directory name passed to venv module when creating the virtual environment)"
Write-Verbose " Got leaf-name of $VenvDir='$(Split-Path -Path $venvDir -Leaf)'"
$Prompt = Split-Path -Path $venvDir -Leaf
}
}
Write-Verbose "Prompt = '$Prompt'"
Write-Verbose "VenvDir='$VenvDir'"
# Deactivate any currently active virtual environment, but leave the
# deactivate function in place.
deactivate -nondestructive
# Now set the environment variable VIRTUAL_ENV, used by many tools to determine
# that there is an activated venv.
$env:VIRTUAL_ENV = $VenvDir
if (-not $Env:VIRTUAL_ENV_DISABLE_PROMPT) {
Write-Verbose "Setting prompt to '$Prompt'"
# Set the prompt to include the env name
# Make sure _OLD_VIRTUAL_PROMPT is global
function global:_OLD_VIRTUAL_PROMPT { "" }
Copy-Item -Path function:prompt -Destination function:_OLD_VIRTUAL_PROMPT
New-Variable -Name _PYTHON_VENV_PROMPT_PREFIX -Description "Python virtual environment prompt prefix" -Scope Global -Option ReadOnly -Visibility Public -Value $Prompt
function global:prompt {
Write-Host -NoNewline -ForegroundColor Green "($_PYTHON_VENV_PROMPT_PREFIX) "
_OLD_VIRTUAL_PROMPT
}
$env:VIRTUAL_ENV_PROMPT = $Prompt
}
# Clear PYTHONHOME
if (Test-Path -Path Env:PYTHONHOME) {
Copy-Item -Path Env:PYTHONHOME -Destination Env:_OLD_VIRTUAL_PYTHONHOME
Remove-Item -Path Env:PYTHONHOME
}
# Add the venv to the PATH
Copy-Item -Path Env:PATH -Destination Env:_OLD_VIRTUAL_PATH
$Env:PATH = "$VenvExecDir$([System.IO.Path]::PathSeparator)$Env:PATH"

View File

@@ -0,0 +1,69 @@
# This file must be used with "source bin/activate" *from bash*
# you cannot run it directly
deactivate () {
# reset old environment variables
if [ -n "${_OLD_VIRTUAL_PATH:-}" ] ; then
PATH="${_OLD_VIRTUAL_PATH:-}"
export PATH
unset _OLD_VIRTUAL_PATH
fi
if [ -n "${_OLD_VIRTUAL_PYTHONHOME:-}" ] ; then
PYTHONHOME="${_OLD_VIRTUAL_PYTHONHOME:-}"
export PYTHONHOME
unset _OLD_VIRTUAL_PYTHONHOME
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r 2> /dev/null
fi
if [ -n "${_OLD_VIRTUAL_PS1:-}" ] ; then
PS1="${_OLD_VIRTUAL_PS1:-}"
export PS1
unset _OLD_VIRTUAL_PS1
fi
unset VIRTUAL_ENV
unset VIRTUAL_ENV_PROMPT
if [ ! "${1:-}" = "nondestructive" ] ; then
# Self destruct!
unset -f deactivate
fi
}
# unset irrelevant variables
deactivate nondestructive
VIRTUAL_ENV=/home/openclaw/.openclaw/workspace/.venvs/transcribe
export VIRTUAL_ENV
_OLD_VIRTUAL_PATH="$PATH"
PATH="$VIRTUAL_ENV/"bin":$PATH"
export PATH
# unset PYTHONHOME if set
# this will fail if PYTHONHOME is set to the empty string (which is bad anyway)
# could use `if (set -u; : $PYTHONHOME) ;` in bash
if [ -n "${PYTHONHOME:-}" ] ; then
_OLD_VIRTUAL_PYTHONHOME="${PYTHONHOME:-}"
unset PYTHONHOME
fi
if [ -z "${VIRTUAL_ENV_DISABLE_PROMPT:-}" ] ; then
_OLD_VIRTUAL_PS1="${PS1:-}"
PS1='(transcribe) '"${PS1:-}"
export PS1
VIRTUAL_ENV_PROMPT='(transcribe) '
export VIRTUAL_ENV_PROMPT
fi
# This should detect bash and zsh, which have a hash command that must
# be called to get it to forget past commands. Without forgetting
# past commands the $PATH changes we made may not be respected
if [ -n "${BASH:-}" -o -n "${ZSH_VERSION:-}" ] ; then
hash -r 2> /dev/null
fi

View File

@@ -0,0 +1,26 @@
# This file must be used with "source bin/activate.csh" *from csh*.
# You cannot run it directly.
# Created by Davide Di Blasi <davidedb@gmail.com>.
# Ported to Python 3.3 venv by Andrew Svetlov <andrew.svetlov@gmail.com>
alias deactivate 'test $?_OLD_VIRTUAL_PATH != 0 && setenv PATH "$_OLD_VIRTUAL_PATH" && unset _OLD_VIRTUAL_PATH; rehash; test $?_OLD_VIRTUAL_PROMPT != 0 && set prompt="$_OLD_VIRTUAL_PROMPT" && unset _OLD_VIRTUAL_PROMPT; unsetenv VIRTUAL_ENV; unsetenv VIRTUAL_ENV_PROMPT; test "\!:*" != "nondestructive" && unalias deactivate'
# Unset irrelevant variables.
deactivate nondestructive
setenv VIRTUAL_ENV /home/openclaw/.openclaw/workspace/.venvs/transcribe
set _OLD_VIRTUAL_PATH="$PATH"
setenv PATH "$VIRTUAL_ENV/"bin":$PATH"
set _OLD_VIRTUAL_PROMPT="$prompt"
if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then
set prompt = '(transcribe) '"$prompt"
setenv VIRTUAL_ENV_PROMPT '(transcribe) '
endif
alias pydoc python -m pydoc
rehash

View File

@@ -0,0 +1,69 @@
# This file must be used with "source <venv>/bin/activate.fish" *from fish*
# (https://fishshell.com/); you cannot run it directly.
function deactivate -d "Exit virtual environment and return to normal shell environment"
# reset old environment variables
if test -n "$_OLD_VIRTUAL_PATH"
set -gx PATH $_OLD_VIRTUAL_PATH
set -e _OLD_VIRTUAL_PATH
end
if test -n "$_OLD_VIRTUAL_PYTHONHOME"
set -gx PYTHONHOME $_OLD_VIRTUAL_PYTHONHOME
set -e _OLD_VIRTUAL_PYTHONHOME
end
if test -n "$_OLD_FISH_PROMPT_OVERRIDE"
set -e _OLD_FISH_PROMPT_OVERRIDE
# prevents error when using nested fish instances (Issue #93858)
if functions -q _old_fish_prompt
functions -e fish_prompt
functions -c _old_fish_prompt fish_prompt
functions -e _old_fish_prompt
end
end
set -e VIRTUAL_ENV
set -e VIRTUAL_ENV_PROMPT
if test "$argv[1]" != "nondestructive"
# Self-destruct!
functions -e deactivate
end
end
# Unset irrelevant variables.
deactivate nondestructive
set -gx VIRTUAL_ENV /home/openclaw/.openclaw/workspace/.venvs/transcribe
set -gx _OLD_VIRTUAL_PATH $PATH
set -gx PATH "$VIRTUAL_ENV/"bin $PATH
# Unset PYTHONHOME if set.
if set -q PYTHONHOME
set -gx _OLD_VIRTUAL_PYTHONHOME $PYTHONHOME
set -e PYTHONHOME
end
if test -z "$VIRTUAL_ENV_DISABLE_PROMPT"
# fish uses a function instead of an env var to generate the prompt.
# Save the current fish_prompt function as the function _old_fish_prompt.
functions -c fish_prompt _old_fish_prompt
# With the original prompt function renamed, we can override with our own.
function fish_prompt
# Save the return status of the last command.
set -l old_status $status
# Output the venv prompt; color taken from the blue of the Python logo.
printf "%s%s%s" (set_color 4B8BBE) '(transcribe) ' (set_color normal)
# Restore the return status of the previous command.
echo "exit $old_status" | .
# Output the original/"old" prompt.
_old_fish_prompt
end
set -gx _OLD_FISH_PROMPT_OVERRIDE "$VIRTUAL_ENV"
set -gx VIRTUAL_ENV_PROMPT '(transcribe) '
end

View File

@@ -0,0 +1,8 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from charset_normalizer.cli import cli_detect
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(cli_detect())

8
.venvs/transcribe/bin/pip Executable file
View File

@@ -0,0 +1,8 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
.venvs/transcribe/bin/pip3 Executable file
View File

@@ -0,0 +1,8 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

8
.venvs/transcribe/bin/pip3.11 Executable file
View File

@@ -0,0 +1,8 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from pip._internal.cli.main import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

View File

@@ -0,0 +1 @@
python3

View File

@@ -0,0 +1 @@
/usr/bin/python3

View File

@@ -0,0 +1 @@
python3

57
.venvs/transcribe/bin/srt Executable file
View File

@@ -0,0 +1,57 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
import os
import sys
import errno
SRT_BIN_PREFIX = "srt-"
def find_srt_commands_in_path():
paths = os.environ.get("PATH", "").split(os.pathsep)
for path in paths:
try:
path_files = os.listdir(path)
except OSError as thrown_exc:
if thrown_exc.errno in (errno.ENOENT, errno.ENOTDIR):
continue
else:
raise
for path_file in path_files:
if path_file.startswith(SRT_BIN_PREFIX):
yield path_file[len(SRT_BIN_PREFIX) :]
def show_help():
print(
"Available commands "
"(pass --help to a specific command for usage information):\n"
)
commands = sorted(set(find_srt_commands_in_path()))
for command in commands:
print("- {}".format(command))
def main():
if len(sys.argv) < 2 or sys.argv[1].startswith("-"):
show_help()
sys.exit(0)
command = sys.argv[1]
available_commands = find_srt_commands_in_path()
if command not in available_commands:
print('Unknown command: "{}"\n'.format(command))
show_help()
sys.exit(1)
real_command = SRT_BIN_PREFIX + command
os.execvp(real_command, [real_command] + sys.argv[2:])
if __name__ == "__main__": # pragma: no cover
main()

View File

@@ -0,0 +1,96 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Deduplicate repeated subtitles."""
import datetime
import srt_tools.utils
import logging
import operator
log = logging.getLogger(__name__)
try: # Python 2
range = xrange # pytype: disable=name-error
except NameError:
pass
def parse_args():
examples = {
"Remove duplicated subtitles within 5 seconds of each other": "srt deduplicate -i duplicated.srt",
"Remove duplicated subtitles within 500 milliseconds of each other": "srt deduplicate -t 500 -i duplicated.srt",
"Remove duplicated subtitles regardless of temporal proximity": "srt deduplicate -t 0 -i duplicated.srt",
}
parser = srt_tools.utils.basic_parser(
description=__doc__,
examples=examples,
)
parser.add_argument(
"-t",
"--ms",
metavar="MILLISECONDS",
default=datetime.timedelta(milliseconds=5000),
type=lambda ms: datetime.timedelta(milliseconds=int(ms)),
help="how many milliseconds distance a subtitle start time must be "
"within of another to be considered a duplicate "
"(default: 5000ms)",
)
return parser.parse_args()
def deduplicate_subs(orig_subs, acceptable_diff):
"""Remove subtitles with duplicated content."""
indices_to_remove = []
# If we only store the subtitle itself and compare that, it's possible that
# we'll not only remove the duplicate, but also the _original_ subtitle if
# they have the same sub index/times/etc.
#
# As such, we need to also store the index in the original subs list that
# this entry belongs to for each subtitle prior to sorting.
sorted_subs = sorted(
enumerate(orig_subs), key=lambda sub: (sub[1].content, sub[1].start)
)
for subs in srt_tools.utils.sliding_window(sorted_subs, width=2, inclusive=False):
cur_idx, cur_sub = subs[0]
next_idx, next_sub = subs[1]
if cur_sub.content == next_sub.content and (
not acceptable_diff or cur_sub.start + acceptable_diff >= next_sub.start
):
log.debug(
"Marking l%d/s%d for removal, duplicate of l%d/s%d",
next_idx,
next_sub.index,
cur_idx,
cur_sub.index,
)
indices_to_remove.append(next_idx)
offset = 0
for idx in indices_to_remove:
del orig_subs[idx - offset]
offset += 1
def main():
args = parse_args()
logging.basicConfig(level=args.log_level)
srt_tools.utils.set_basic_args(args)
subs = list(args.input)
deduplicate_subs(subs, args.ms)
output = srt_tools.utils.compose_suggest_on_fail(subs, strict=args.strict)
try:
args.output.write(output)
except (UnicodeEncodeError, TypeError): # Python 2 fallback
args.output.write(output.encode(args.encoding))
if __name__ == "__main__": # pragma: no cover
main()

View File

@@ -0,0 +1,47 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Shifts a subtitle by a fixed number of seconds."""
import datetime
import srt_tools.utils
import logging
log = logging.getLogger(__name__)
def parse_args():
examples = {
"Make all subtitles 5 seconds later": "srt fixed-timeshift --seconds 5",
"Make all subtitles 5 seconds earlier": "srt fixed-timeshift --seconds -5",
}
parser = srt_tools.utils.basic_parser(description=__doc__, examples=examples)
parser.add_argument(
"--seconds", type=float, required=True, help="how many seconds to shift"
)
return parser.parse_args()
def scalar_correct_subs(subtitles, seconds_to_shift):
td_to_shift = datetime.timedelta(seconds=seconds_to_shift)
for subtitle in subtitles:
subtitle.start += td_to_shift
subtitle.end += td_to_shift
yield subtitle
def main():
args = parse_args()
logging.basicConfig(level=args.log_level)
srt_tools.utils.set_basic_args(args)
corrected_subs = scalar_correct_subs(args.input, args.seconds)
output = srt_tools.utils.compose_suggest_on_fail(corrected_subs, strict=args.strict)
try:
args.output.write(output)
except (UnicodeEncodeError, TypeError): # Python 2 fallback
args.output.write(output.encode(args.encoding))
if __name__ == "__main__": # pragma: no cover
main()

View File

@@ -0,0 +1,105 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Perform linear time correction on a subtitle."""
from __future__ import division
import srt
import datetime
import srt_tools.utils
import logging
log = logging.getLogger(__name__)
def timedelta_to_milliseconds(delta):
return delta.days * 86400000 + delta.seconds * 1000 + delta.microseconds / 1000
def parse_args():
def srt_timestamp_to_milliseconds(parser, arg):
try:
delta = srt.srt_timestamp_to_timedelta(arg)
except ValueError:
parser.error("not a valid SRT timestamp: %s" % arg)
else:
return timedelta_to_milliseconds(delta)
examples = {
"Stretch out a subtitle so that second 1 is 1, 2 is 3, 3 is 5, etc": "srt linear-timeshift --f1 00:00:01,000 --t1 00:00:01,000 --f2 00:00:02,000 --t2 00:00:03,000"
}
parser = srt_tools.utils.basic_parser(description=__doc__, examples=examples)
parser.add_argument(
"--from-start",
"--f1",
type=lambda arg: srt_timestamp_to_milliseconds(parser, arg),
required=True,
help="the first desynchronised timestamp",
)
parser.add_argument(
"--to-start",
"--t1",
type=lambda arg: srt_timestamp_to_milliseconds(parser, arg),
required=True,
help="the first synchronised timestamp",
)
parser.add_argument(
"--from-end",
"--f2",
type=lambda arg: srt_timestamp_to_milliseconds(parser, arg),
required=True,
help="the second desynchronised timestamp",
)
parser.add_argument(
"--to-end",
"--t2",
type=lambda arg: srt_timestamp_to_milliseconds(parser, arg),
required=True,
help="the second synchronised timestamp",
)
return parser.parse_args()
def calc_correction(to_start, to_end, from_start, from_end):
angular = (to_end - to_start) / (from_end - from_start)
linear = to_end - angular * from_end
return angular, linear
def correct_time(current_msecs, angular, linear):
return round(current_msecs * angular + linear)
def correct_timedelta(bad_delta, angular, linear):
bad_msecs = timedelta_to_milliseconds(bad_delta)
good_msecs = correct_time(bad_msecs, angular, linear)
good_delta = datetime.timedelta(milliseconds=good_msecs)
return good_delta
def linear_correct_subs(subtitles, angular, linear):
for subtitle in subtitles:
subtitle.start = correct_timedelta(subtitle.start, angular, linear)
subtitle.end = correct_timedelta(subtitle.end, angular, linear)
yield subtitle
def main():
args = parse_args()
logging.basicConfig(level=args.log_level)
angular, linear = calc_correction(
args.to_start, args.to_end, args.from_start, args.from_end
)
srt_tools.utils.set_basic_args(args)
corrected_subs = linear_correct_subs(args.input, angular, linear)
output = srt_tools.utils.compose_suggest_on_fail(corrected_subs, strict=args.strict)
try:
args.output.write(output)
except (UnicodeEncodeError, TypeError): # Python 2 fallback
args.output.write(output.encode(args.encoding))
if __name__ == "__main__": # pragma: no cover
main()

View File

@@ -0,0 +1,85 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Filter subtitles that match or don't match a particular pattern."""
import importlib
import srt_tools.utils
import logging
log = logging.getLogger(__name__)
def strip_to_matching_lines_only(subtitles, imports, func_str, invert, per_sub):
for import_name in imports:
real_import = importlib.import_module(import_name)
globals()[import_name] = real_import
raw_func = eval(func_str) # pylint: disable-msg=eval-used
if invert:
func = lambda line: not raw_func(line)
else:
func = raw_func
for subtitle in subtitles:
if per_sub:
if not func(subtitle.content):
subtitle.content = ""
else:
subtitle.content = "\n".join(
line for line in subtitle.content.splitlines() if func(line)
)
yield subtitle
def parse_args():
examples = {
"Only include Chinese lines": "srt lines-matching -m hanzidentifier -f hanzidentifier.has_chinese",
"Exclude all lines which only contain numbers": "srt lines-matching -v -f 'lambda x: x.isdigit()'",
}
parser = srt_tools.utils.basic_parser(description=__doc__, examples=examples)
parser.add_argument(
"-f", "--func", help="a function to use to match lines", required=True
)
parser.add_argument(
"-m",
"--module",
help="modules to import in the function context",
action="append",
default=[],
)
parser.add_argument(
"-s",
"--per-subtitle",
help="match the content of each subtitle, not each line",
action="store_true",
)
parser.add_argument(
"-v",
"--invert",
help="invert matching -- only match lines returning False",
action="store_true",
)
return parser.parse_args()
def main():
args = parse_args()
logging.basicConfig(level=args.log_level)
srt_tools.utils.set_basic_args(args)
matching_subtitles_only = strip_to_matching_lines_only(
args.input, args.module, args.func, args.invert, args.per_subtitle
)
output = srt_tools.utils.compose_suggest_on_fail(
matching_subtitles_only, strict=args.strict
)
try:
args.output.write(output)
except (UnicodeEncodeError, TypeError): # Python 2 fallback
args.output.write(output.encode(args.encoding))
if __name__ == "__main__": # pragma: no cover
main()

112
.venvs/transcribe/bin/srt-mux Executable file
View File

@@ -0,0 +1,112 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Merge multiple subtitles together into one."""
import datetime
import srt_tools.utils
import logging
import operator
log = logging.getLogger(__name__)
TOP = r"{\an8}"
BOTTOM = r"{\an2}"
def parse_args():
examples = {
"Merge English and Chinese subtitles": "srt mux -i eng.srt -i chs.srt -o both.srt",
"Merge subtitles, with one on top and one at the bottom": "srt mux -t -i eng.srt -i chs.srt -o both.srt",
}
parser = srt_tools.utils.basic_parser(
description=__doc__, examples=examples, multi_input=True
)
parser.add_argument(
"--ms",
metavar="MILLISECONDS",
default=datetime.timedelta(milliseconds=600),
type=lambda ms: datetime.timedelta(milliseconds=int(ms)),
help="if subs being muxed are within this number of milliseconds "
"of each other, they will have their times matched (default: 600)",
)
parser.add_argument(
"-w",
"--width",
default=5,
type=int,
help="how many subs to consider for time matching at once (default: %(default)s)",
)
parser.add_argument(
"-t",
"--top-and-bottom",
action="store_true",
help="use SSA-style tags to place files at the top and bottom, respectively. Turns off time matching",
)
parser.add_argument(
"--no-time-matching",
action="store_true",
help="don't try to do time matching for close subtitles (see --ms)",
)
return parser.parse_args()
def merge_subs(subs, acceptable_diff, attr, width):
"""
Merge subs with similar start/end times together. This prevents the
subtitles jumping around the screen.
The merge is done in-place.
"""
sorted_subs = sorted(subs, key=operator.attrgetter(attr))
for subs in srt_tools.utils.sliding_window(sorted_subs, width=width):
current_sub = subs[0]
future_subs = subs[1:]
current_comp = getattr(current_sub, attr)
for future_sub in future_subs:
future_comp = getattr(future_sub, attr)
if current_comp + acceptable_diff > future_comp:
log.debug(
"Merging %d's %s time into %d",
future_sub.index,
attr,
current_sub.index,
)
setattr(future_sub, attr, current_comp)
else:
# Since these are sorted, and this one didn't match, we can be
# sure future ones won't match either.
break
def main():
args = parse_args()
logging.basicConfig(level=args.log_level)
srt_tools.utils.set_basic_args(args)
muxed_subs = []
for idx, subs in enumerate(args.input):
for sub in subs:
if args.top_and_bottom:
if idx % 2 == 0:
sub.content = TOP + sub.content
else:
sub.content = BOTTOM + sub.content
muxed_subs.append(sub)
if args.no_time_matching or not args.top_and_bottom:
merge_subs(muxed_subs, args.ms, "start", args.width)
merge_subs(muxed_subs, args.ms, "end", args.width)
output = srt_tools.utils.compose_suggest_on_fail(muxed_subs, strict=args.strict)
try:
args.output.write(output)
except (UnicodeEncodeError, TypeError): # Python 2 fallback
args.output.write(output.encode(args.encoding))
if __name__ == "__main__": # pragma: no cover
main()

View File

@@ -0,0 +1,28 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Takes a badly formatted SRT file and outputs a strictly valid one."""
import srt_tools.utils
import logging
log = logging.getLogger(__name__)
def main():
examples = {"Normalise a subtitle": "srt normalise -i bad.srt -o good.srt"}
args = srt_tools.utils.basic_parser(
description=__doc__, examples=examples, hide_no_strict=True
).parse_args()
logging.basicConfig(level=args.log_level)
srt_tools.utils.set_basic_args(args)
output = srt_tools.utils.compose_suggest_on_fail(args.input, strict=args.strict)
try:
args.output.write(output)
except (UnicodeEncodeError, TypeError): # Python 2 fallback
args.output.write(output.encode(args.encoding))
if __name__ == "__main__": # pragma: no cover
main()

59
.venvs/transcribe/bin/srt-play Executable file
View File

@@ -0,0 +1,59 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Play subtitles with correct timing to stdout."""
from __future__ import print_function
import logging
from threading import Timer, Lock
import srt_tools.utils
import sys
import time
log = logging.getLogger(__name__)
output_lock = Lock()
def print_sub(sub, encoding):
log.debug("Timer woke up to print %s", sub.content)
with output_lock:
try:
sys.stdout.write(sub.content + "\n\n")
except UnicodeEncodeError: # Python 2 fallback
sys.stdout.write(sub.content.encode(encoding) + "\n\n")
sys.stdout.flush()
def schedule(subs, encoding):
timers = set()
log.debug("Scheduling subtitles")
for sub in subs:
secs = sub.start.total_seconds()
cur_timer = Timer(secs, print_sub, [sub, encoding])
cur_timer.name = "%s:%s" % (sub.index, secs)
cur_timer.daemon = True
log.debug('Adding "%s" to schedule queue', cur_timer.name)
timers.add(cur_timer)
for timer in timers:
log.debug('Starting timer for "%s"', timer.name)
timer.start()
while any(t.is_alive() for t in timers):
time.sleep(0.5)
def main():
examples = {"Play a subtitle": "srt play -i foo.srt"}
args = srt_tools.utils.basic_parser(
description=__doc__, examples=examples, no_output=True
).parse_args()
logging.basicConfig(level=args.log_level)
srt_tools.utils.set_basic_args(args)
schedule(args.input, args.encoding)
if __name__ == "__main__": # pragma: no cover
main()

View File

@@ -0,0 +1,57 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
"""Process subtitle text content using arbitrary Python code."""
import importlib
import srt_tools.utils
import logging
log = logging.getLogger(__name__)
def strip_to_matching_lines_only(subtitles, imports, func_str):
for import_name in imports:
real_import = importlib.import_module(import_name)
globals()[import_name] = real_import
func = eval(func_str) # pylint: disable-msg=eval-used
for subtitle in subtitles:
subtitle.content = func(subtitle.content)
yield subtitle
def parse_args():
examples = {
"Strip HTML-like symbols from a subtitle": """srt process -m re -f 'lambda sub: re.sub("<[^<]+?>", "", sub)'"""
}
parser = srt_tools.utils.basic_parser(description=__doc__, examples=examples)
parser.add_argument(
"-f", "--func", help="a function to use to process lines", required=True
)
parser.add_argument(
"-m",
"--module",
help="modules to import in the function context",
action="append",
default=[],
)
return parser.parse_args()
def main():
args = parse_args()
logging.basicConfig(level=args.log_level)
srt_tools.utils.set_basic_args(args)
processed_subs = strip_to_matching_lines_only(args.input, args.module, args.func)
output = srt_tools.utils.compose_suggest_on_fail(processed_subs, strict=args.strict)
try:
args.output.write(output)
except (UnicodeEncodeError, TypeError): # Python 2 fallback
args.output.write(output.encode(args.encoding))
if __name__ == "__main__": # pragma: no cover
main()

8
.venvs/transcribe/bin/tqdm Executable file
View File

@@ -0,0 +1,8 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from tqdm.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

View File

@@ -0,0 +1,8 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from vosk.transcriber.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())

View File

@@ -0,0 +1,8 @@
#!/home/openclaw/.openclaw/workspace/.venvs/transcribe/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from websockets.cli import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
sys.exit(main())