Text_to_SRT-API / app.py
Lenylvt's picture
Update app.py
9b27f70 verified
raw
history blame
1.9 kB
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()