File size: 1,681 Bytes
335cfd2
9b27f70
 
335cfd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5f2ef0
9b27f70
a5f2ef0
 
 
 
 
 
 
0e3fe63
335cfd2
a5f2ef0
 
 
 
9b27f70
a5f2ef0
 
9b27f70
a5f2ef0
 
9b27f70
a5f2ef0
335cfd2
a5f2ef0
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
import gradio as gr
import os
from tempfile import NamedTemporaryFile

def text_to_srt(text):
    lines = text.split('\n')
    srt_content = ""
    for i, line in enumerate(lines):
        if line.strip() == "":
            continue
        try:
            times, content = line.split(']', 1)
            start, end = times[1:].split(' -> ')
            srt_content += f"{i+1}\n{start.replace('.', ',')} --> {end.replace('.', ',')}\n{content.strip()}\n\n"
        except ValueError:
            continue  # Skip lines that don't match the expected format
    return srt_content

def convert_and_prepare_file(text_input):
    srt_content = text_to_srt(text_input)
    if not srt_content.strip():
        return None  # No valid content to create a file
    # Write SRT content to a temporary file
    temp_file = NamedTemporaryFile(delete=False, suffix=".srt", mode='w+', dir="./")
    temp_file.write(srt_content)
    temp_file.close()
    return temp_file.name  # Return the path for Gradio to handle

with gr.Blocks() as app:
    with gr.Row():
        text_input = gr.TextArea(label="Enter text in the specified format")
        export_btn = gr.Button("Export as SRT")
    output_file = gr.File(label="Download SRT", interactive=True, visible=False)

    def on_export_click(text_input):
        file_path = convert_and_prepare_file(text_input)
        if file_path:
            return file_path, True  # Return the path and make the file visible
        return None, False  # If no file was created, return None and keep the file component hidden

    export_btn.click(fn=on_export_click, inputs=text_input, outputs=[output_file, output_file.visible])

app.launch(share=True)