File size: 1,900 Bytes
335cfd2
9b27f70
 
335cfd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0e3fe63
 
 
9b27f70
 
 
 
 
 
 
 
 
 
0e3fe63
335cfd2
 
 
9b27f70
 
 
 
 
 
 
 
 
 
 
 
335cfd2
854dfbc
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
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 export_file(srt_content):
    if srt_content.strip() == "":
        return None
    # Write SRT content to a temporary file
    with NamedTemporaryFile(delete=False, suffix=".srt", mode='w+', dir="./") as tmp_file:
        tmp_file.write(srt_content)
        return tmp_file.name  # Return the path for Gradio to handle

# Use a stateful text component to hold the path to the temporary SRT file
def update_output(text_input):
    srt_content = text_to_srt(text_input)
    file_path = export_file(srt_content)
    return file_path

with gr.Blocks() as app:
    gr.Markdown("### Text to SRT Converter")
    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", visible=False)  # Initially hidden

    # Update to use a state variable for holding the SRT file path
    def on_export_click(_, file_path):
        if file_path:
            output_file.update(value=file_path, visible=True)  # Make the download link visible
        else:
            output_file.update(visible=False)  # Hide if no file

    text_input.change(fn=update_output, inputs=text_input, outputs=output_file, show_progress=True)
    export_btn.click(fn=on_export_click, inputs=[export_btn, text_input], outputs=output_file)

app.launch()