File size: 3,014 Bytes
4d69eaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import subprocess
import uuid
import ffmpeg
import gradio as gr

title_and_description = """
# Download de clipes da Twitch
Criado por [@artificialguybr] (https://artificialguy.com)

Insira o URL do Twitch Clip e (opcionalmente) um token de autenticação para fazer download.

## Recursos
- **Fácil de usar**: Interface simples para inserir URLs de clipes do Twitch e tokens de autenticação opcionais para baixar VOD que precisa de sub [Veja aqui como obter seu TOKEN de autenticação] (https://twitch-dl.bezdomni.net/commands/download.html#downloading-subscriber-only-vods)
- **Vídeo de alta qualidade**: Faz download com a melhor qualidade disponível e converte em um formato MP4 amplamente suportado.
- **Nomenclatura exclusiva de arquivos**: Utiliza UUIDs para gerar nomes de arquivos exclusivos, evitando problemas de substituição de arquivos.
- **Processamento eficiente**: Utiliza o `ffmpeg-python` para uma conversão de vídeo rápida e confiável.

Sinta-se à vontade para usar e gerar seus próprios videoclipes!
"""

# Function to download Twitch clip using twitch-dl
def download_twitch_clip(url, auth_token):
    # Generate a UUID for the file name
    unique_id = uuid.uuid4()
    output_filename = f"{unique_id}.mkv"

    # Command to download the video
    command = ["twitch-dl", "download", url, "-q", "source", "-o", output_filename]

    # Add authentication token if provided
    if auth_token.strip():
        command.extend(["-a", auth_token])

    # Execute the download command
    process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = process.communicate()

    if process.returncode != 0:
        raise Exception(f"Error in video download: {stderr.decode('utf-8')}")

    return output_filename

# Function to convert MKV to MP4 using ffmpeg-python
def convert_to_mp4(input_file):
    output_file = input_file.replace('.mkv', '.mp4')

    try:
        (
            ffmpeg
            .input(input_file)
            .output(output_file, vcodec='libx264', acodec='aac')
            .run(overwrite_output=True)
        )
        return output_file
    except ffmpeg.Error as e:
        print(f"Error in file conversion: {e}")
        return None

# Gradio interface
def gradio_interface(url, auth_token=""):
    mkv_file = download_twitch_clip(url, auth_token)
    mp4_file = convert_to_mp4(mkv_file)
    return mp4_file

with gr.Blocks() as app:
    gr.Markdown(title_and_description)
    
    with gr.Row():
        with gr.Column():
            result_video = gr.Video(label="Vídeo Output")
            
    with gr.Row():
        with gr.Column():
            url_input = gr.Textbox(label="Twitch Clip URL")
            auth_token_input = gr.Textbox(label="Authentication Token (optional)", type="password")
            run_btn = gr.Button("Download Clip")
            
    run_btn.click(
        gradio_interface,
        inputs=[url_input, auth_token_input],
        outputs=[result_video]
    )
app.queue()
app.launch()