Spaces:
Sleeping
Sleeping
Upload streamlit_app.py
Browse files1<inserted code here to avoid truncation>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127import streamlit as stimport tempfilefrom faster_whisper import WhisperModelimport textwrapfrom datetime import timedeltadef format_time(seconds):td = timedelta(seconds=seconds)result = str(td)[:11].replace(".", ",")return result if "," in result else result + ",000"st.set_page_config(page_title="VO to Subtitle Generator Multi-languages version")st.title("🌍 VO to Subtitle Generator — Multi-languages Version")uploaded_file = st.file_uploader("Upload Arabic MP3 or WAV", type=["mp3", "wav"])model_size = st.selectbox("Model Size", ["tiny", "base", "small", "medium"], index=0)layout = st.selectbox("Video Layout", ["Horizontal (37 chars)", "Vertical (25 chars)"])lines = st.selectbox("Lines per Subtitle", [1, 2], index=1)language_map = {"Auto": None,"Arabic": "ar","English": "en","French": "fr","Farsi": "fa","Spanish": "es"}language = st.selectbox("Language", list(language_map.keys()))export_format = st.selectbox("Export Format", ["srt", "fcpxmld"], index=0)st.markdown("**Preview Direction:**")col1, col2 = st.columns(2)with col1:rtl_button = st.button("⬅️ RTL (Right-to-Left)")with col2:ltr_button = st.button("➡️ LTR (Left-to-Right)")if 'text_dir' not in st.session_state:st.session_state['text_dir'] = 'rtl'if rtl_button:st.session_state['text_dir'] = 'rtl'if ltr_button:st.session_state['text_dir'] = 'ltr'edited_text = ""if uploaded_file:if st.button("🔁 Generate Subtitle"):with st.spinner("Transcribing with Whisper..."):with tempfile.NamedTemporaryFile(delete=False) as temp_audio:temp_audio.write(uploaded_file.read())temp_audio.flush()whisper = WhisperModel(model_size, device="cpu", compute_type="int8")segments_gen, _ = whisper.transcribe(temp_audio.name, language=language_map[language])segments = list(segments_gen)max_chars = 25 if "Vertical" in layout else 37max_lines = int(lines)if export_format == "srt":srt_text = ""count = 1for seg in segments:start = seg.startend = seg.endtext = seg.text.strip()lines = textwrap.wrap(text, width=max_chars)grouped = [lines[i:i+max_lines] for i in range(0, len(lines), max_lines)]chunk_count = len(grouped)duration = end - startchunk_duration = duration / chunk_count if chunk_count > 0 else durationfor j, chunk in enumerate(grouped):chunk_start = start + j * chunk_durationchunk_end = chunk_start + chunk_durationtimestamp = f"{format_time(chunk_start)} --> {format_time(chunk_end)}"content = "\n".join(chunk)srt_text += f"{count}\n{timestamp}\n{content}\n\n"count += 1edited_text = st.text_area("✏️ Edit SRT Before Download",value=srt_text,height=300,key="srt_editor")rtl_style = "direction: rtl;" if st.session_state["text_dir"] == "rtl" else "direction: ltr;"st.markdown(f'<div style="{rtl_style} white-space: pre-wrap; border:1px solid #ccc; padding:1em; border-radius:5px; background:#f9f9f9; max-height:300px; overflow:auto">{edited_text}</div>', unsafe_allow_html=True)st.download_button("⬇️ Download .srt", edited_text, file_name="output.srt", mime="text/plain")elif export_format == "fcpxmld":from xml.sax.saxutils import escapexml = ['<?xml version="1.0" encoding="UTF-8"?>','<!DOCTYPE fcpxml>','<fcpxml version="1.9">',' <resources>',' <format id="r1" name="FFVideoFormat1080p30" frameDuration="100/3000s" width="1920" height="1080"/>',' <effect id="r2" name="Basic Title" uid=".../Effects.localized/Basic Titles.localized/Basic Title.localized/Basic Title.moti"/>',' </resources>',' <library>',' <event name="Transcription">',' <project name="Subtitles">',f' <sequence duration="{round(segments[-1].end, 2)}s" format="r1" tcStart="0s" tcFormat="NDF">',' <spine>']for seg in segments:start = round(seg.start, 2)duration = round(seg.end - seg.start, 2)text = escape(seg.text)xml.append(f' <title lane="1" offset="{start}s" ref="r2" duration="{duration}s" start="{start}s">'f' <text>{text}</text>'f' </title>')xml.extend([' </spine>',' </sequence>',' </project>',' </event>',' </library>','</fcpxml>'])fcpxml_content = '\n'.join(xml)st.text_area("Preview FCPXMLD", value=fcpxml_content, height=300)st.download_button("⬇️ Download .fcpxmld", fcpxml_content, file_name="output.fcpxmld", mime="application/xml")
streamlit_app.py+127-1