Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create translate.ps1 - PowerShell script that downloads video, transl… #153

Merged
merged 4 commits into from
May 22, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 52 additions & 2 deletions vot-cli/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,6 @@
- **[XVideos](https://xvideos.com/)**
- **[PornHub](https://rt.pornhub.com/)**

## Версия для скачивания видео с встроенным переводом: [fishy-voice-over](https://gitlab.com/musickiller/fishy-voice-over/-/blob/main/translate.fish)

# Установка:
1. Скачать и распаковать архив с релизом
2. В распакованной папке (vot-cli) выполнить команду `npm install`
Expand All @@ -38,3 +36,55 @@
Я впервые попытался написать что-то подобное, поэтому получилось далеко не идеально. Есть какие-то рандомные ошибки соединия происходящие при отправке запроса DownloaderHelper (прокомментировано в коде) или Axios, и я не знаю как их исправить :(

![example](https://github.com/ilyhalight/voice-over-translation/blob/master/vot-cli/example.png "btn")

## Скрипт для скачивания видео с встроенным переводом для Unix: [fishy-voice-over](https://gitlab.com/musickiller/fishy-voice-over/-/blob/main/translate.fish)
## Скрипт для скачивания видео с встроенным переводом для Windows (PowerShell):
### Prerequisites

Перед использованием этого инструмента убедитесь, что у вас установлены следующие зависимости:

- [yt-dlp](https://github.com/yt-dlp/yt-dlp): Программа командной строки для загрузки видео с YouTube и других сайтов.
- [ffmpeg](https://ffmpeg.org/): Мощная мультимедийная платформа для работы с аудио, видео и другими медиафайлами.
- [Node.js](https://nodejs.org/): Среда выполнения JavaScript.

### Installation

1. Клонируйте этот репозиторий на локальную машину:

```shell
git clone https://github.com/ilyhalight/voice-over-translation.git
```

2. Перейдите в каталог проекта:

```shell
cd vot-cli
```

3. Установите зависимости Node.js:

```shell
npm install
```
4. После успешной установки модулей выполнить команду:

```shell
npm link
```
5. Запуск скрипта с указанием ссылок на видео:
```shell
.\translate.ps1 <ссылка на видео 1> <ссылка на видео 2> [громкость звука оригинала]
```

- `<ссылка на видео>`: Ссылка на видеоролик YouTube, который вы хотите перевести.
- `[громкость звука оригинала]` (необязательно): Коэффициент громкости для оригинального звука (по умолчанию 0,1).

Пример:

```shell
.\translate.ps1 https://www.youtube.com/watch?v=your_video_link 0.2
```
Скрипт загрузит видео, добавит русский закадровый голос и объединит звуковые дорожки. Переведенное видео будет сохранено в той же директории, что и скрипт.

### Notes
- Команды `yt-dlp`, `ffmpeg`, `vot-cli` должны быть доступны из командной строки. Убедитесь, что пути к их исполняемым файлам добавлены в переменную окружения PATH вашей системы.
75 changes: 75 additions & 0 deletions vot-cli/translate.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Скрипт для PowerShell который скачивает видео, перевод и смешивает
#
# Использование:
# .\translate.ps1 <ссылка на видео 1> <ссылка на видео 2> ... [отношение громкости оригинала - например: 0.4]
#
# Usage:
# .\translate.ps1 <video link 1> <video link 2> ... [volume ratio - for example: 0.4]
#
# Буду рад узнать ваши идеи и о найденных ошибках!
# any ideas/issues are welcome!!
# Original Script: https://gitlab.com/musickiller/fishy-voice-over/-/blob/main/translate.fish




function ProcessVideo($video_link, $original_sound_ratio) {
# No -Force, to make sure nothing is overwritten
New-Item -ItemType Directory -Path $temp_dir -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path $temp_video_dir -ErrorAction SilentlyContinue | Out-Null
New-Item -ItemType Directory -Path $temp_audio -ErrorAction SilentlyContinue | Out-Null

yt-dlp -o $temp_video $video_link
$video_full_name = Get-ChildItem $temp_video_dir
vot-cli $video_link --output $temp_audio

$temp_video_file = (Get-ChildItem -Path $temp_video_dir)[0].FullName
$temp_audio_file = (Get-ChildItem -Path $temp_audio)[0].FullName

ffmpeg `
-i $temp_video_file -i $temp_audio_file `
-c:v copy `
-b:a 128k `
-filter_complex " `
[0:a] volume=$original_sound_ratio [original]; `
[original][1:a] amix=inputs=2:duration=longest [audio_out] `
" `
-map 0:v -map "[audio_out]" `
-y $video_full_name

Remove-Item -Recurse -Force $temp_dir
}

# Settings
$original_sound_ratio = 0.1
$temp_dir = "./temp" # will be removed
$temp_video_dir = "$temp_dir/video"
$temp_video = "$temp_video_dir/%(title)s.%(ext)s"
$temp_audio = "$temp_dir/audio"

$video_links = $args[0..($args.Length - 2)]
$volume_ratio_arg = $args[-1]

# If the last argument is a number, set the original sound ratio to that one
if ($volume_ratio_arg -as [double]) {
$original_sound_ratio = $volume_ratio_arg
Write-Host "Original volume is set to $original_sound_ratio"
} else {
# If the last argument is not a number, add it back to the video links array
$video_links += $volume_ratio_arg
}

# Check that var is init
if ($video_links) {
foreach ($video_link in $video_links) {
if ([string]::IsNullOrEmpty($video_link)) {
Write-Host "Error: Link not entered."
continue
}

Write-Host "Processing video: $video_link"
ProcessVideo $video_link $original_sound_ratio
}
} else {
Write-Host "Error: Link not entered."
}