Spaces:
Runtime error
Runtime error
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) | |