Spaces:
Sleeping
Sleeping
File size: 12,247 Bytes
c2c1bfd | 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 | import gradio as gr
import json
import re
from collections import Counter
from datetime import timedelta
from typing import List, Dict, Any, Optional, Tuple
# Language-specific rules and dictionaries
LANGUAGE_RULES = {
"en": {
"trigger_words": ["however", "but", "therefore", "meanwhile", "nevertheless"],
"forbidden_endings": ["a", "an", "the", "and", "but", "or", "for", "nor", "on", "at", "to", "from", "by", "of", "in", "with"],
"sentence_boundaries": [".", "?", "!"]
},
"es": {
"trigger_words": ["sin embargo", "pero", "por lo tanto", "mientras tanto", "no obstante"],
"forbidden_endings": ["el", "la", "los", "las", "y", "o", "para", "por", "de", "en", "con", "a", "de", "por"],
"sentence_boundaries": [".", "?", "!"]
},
"fr": {
"trigger_words": ["cependant", "mais", "donc", "pendant ce temps", "néanmoins"],
"forbidden_endings": ["le", "la", "les", "et", "ou", "pour", "par", "de", "en", "avec", "à", "de", "par"],
"sentence_boundaries": [".", "?", "!"]
}
}
def validate_input(json_input: str) -> Tuple[bool, Optional[Dict[str, Any]]]:
"""
Validate the input JSON structure.
Args:
json_input: JSON string to validate
Returns:
Tuple of (is_valid, parsed_data) where parsed_data is None if invalid
"""
try:
data = json.loads(json_input)
if not isinstance(data, dict):
return False, None
if "text" not in data or "chunks" not in data:
return False, None
if not isinstance(data["chunks"], list) or len(data["chunks"]) == 0:
return False, None
return True, data
except json.JSONDecodeError:
return False, None
def format_time(seconds: float) -> str:
"""
Convert seconds to SRT time format (HH:MM:SS,mmm).
Args:
seconds: Time in seconds
Returns:
Formatted time string
"""
td = timedelta(seconds=seconds)
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
milliseconds = td.microseconds // 1000
return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"
def count_words(text: str) -> int:
"""
Count words in text (including spaces and punctuation).
Args:
text: Text to count words in
Returns:
Word count
"""
return len(text.split())
def get_majority_speaker(chunks: List[Dict[str, Any]]) -> Optional[str]:
"""
Determine majority speaker from chunks.
Args:
chunks: List of chunk dictionaries
Returns:
Majority speaker ID or None if no speaker info
"""
speaker_counts = Counter()
for chunk in chunks:
if "speaker" in chunk:
speaker_counts[chunk["speaker"]] += count_words(chunk["text"])
if speaker_counts:
return speaker_counts.most_common(1)[0][0]
return None
def should_break_line(line: str, language: str, word_break_threshold: int) -> bool:
"""
Determine if a line should break based on language rules.
Args:
line: Text line to check
language: ISO language code
word_break_threshold: Maximum words per line
Returns:
True if line should break
"""
# Check word count threshold
if count_words(line) > word_break_threshold:
return True
# Check character limit (11 chars excluding spaces)
chars_excluding_spaces = len(re.sub(r'\s+', '', line))
if chars_excluding_spaces > 11:
return True
# Check for trigger words
rules = LANGUAGE_RULES.get(language, LANGUAGE_RULES["en"])
for trigger in rules["trigger_words"]:
if trigger.lower() in line.lower():
return True
# Check for forbidden endings
last_word = line.strip().split()[-1].lower() if line.strip() else ""
if last_word in rules["forbidden_endings"]:
return True
return False
def format_speaker_change(speaker_id: str) -> str:
"""
Format speaker identifier for SRT.
Args:
speaker_id: Speaker identifier
Returns:
Formatted speaker marker
"""
return f"[{speaker_id}] "
def process_chunks_to_srt(
chunks: List[Dict[str, Any]],
word_break_threshold: int,
language: str,
include_speaker: bool
) -> str:
"""
Convert transcription chunks to SRT format.
Args:
chunks: List of chunk dictionaries
word_break_threshold: Maximum words per subtitle block
language: ISO language code
include_speaker: Whether to include speaker information
Returns:
SRT formatted string
"""
srt_segments = []
current_segment = []
current_speaker = None
current_start_time = None
current_end_time = None
# Process chunks to create segments
for i, chunk in enumerate(chunks):
text = chunk["text"]
start_time = chunk["timestamp"][0]
end_time = chunk["timestamp"][1]
# Initialize current segment with first chunk
if not current_segment:
current_segment = [text]
current_start_time = start_time
current_end_time = end_time
current_speaker = chunk.get("speaker")
continue
# Check if we should start a new segment
should_break = False
# Check sentence boundaries
if text.strip() and text.strip()[0] in LANGUAGE_RULES.get(language, LANGUAGE_RULES["en"])["sentence_boundaries"]:
should_break = True
# Check word count threshold
total_words = sum(count_words(t) for t in current_segment)
if total_words + count_words(text) > word_break_threshold:
should_break = True
# Check speaker change (if speaker info available)
if include_speaker and "speaker" in chunk and chunk["speaker"] != current_speaker:
should_break = True
if should_break:
# Finalize current segment
segment_text = " ".join(current_segment).strip()
srt_segments.append({
"start": current_start_time,
"end": current_end_time,
"text": segment_text,
"speaker": current_speaker
})
# Start new segment
current_segment = [text]
current_start_time = start_time
current_end_time = end_time
current_speaker = chunk.get("speaker")
else:
# Continue current segment
current_segment.append(text)
current_end_time = end_time
# Add final segment
if current_segment:
segment_text = " ".join(current_segment).strip()
srt_segments.append({
"start": current_start_time,
"end": current_end_time,
"text": segment_text,
"speaker": current_speaker
})
# Format segments as SRT
srt_lines = []
for i, segment in enumerate(srt_segments, 1):
start_time = format_time(segment["start"])
end_time = format_time(segment["end"])
text = segment["text"]
# Apply speaker marker if needed
if include_speaker and segment["speaker"]:
text = format_speaker_change(segment["speaker"]) + text
# Format SRT block
srt_lines.append(str(i))
srt_lines.append(f"{start_time} --> {end_time}")
srt_lines.append(text)
srt_lines.append("") # Blank line between segments
return "\n".join(srt_lines).strip()
def convert_transcription(
json_input: str,
word_break_threshold: int,
language: str,
include_speaker: bool
) -> Tuple[str, str]:
"""
Main conversion function from Transcribe JSON to SRT.
Args:
json_input: JSON input string
word_break_threshold: Maximum words per subtitle block
language: ISO language code
include_speaker: Whether to include speaker information
Returns:
Tuple of (srt_output, status_message)
"""
# Validate input
is_valid, data = validate_input(json_input)
if not is_valid:
return "", "Invalid JSON input: Missing required 'text' or 'chunks' fields"
# Process chunks to SRT
try:
srt_output = process_chunks_to_srt(
data["chunks"],
word_break_threshold,
language,
include_speaker
)
return srt_output, "Conversion successful"
except Exception as e:
return "", f"Error during conversion: {str(e)}"
# Create Gradio interface
with gr.Blocks() as demo:
gr.Markdown("# Transcription Format Converter")
gr.Markdown("Convert Transcribe JSON format to SRT subtitle format with configurable options")
gr.Markdown("Built with [anycoder](https://huggingface.co/spaces/akhaliq/anycoder)")
with gr.Row():
with gr.Column():
# Input section
json_input = gr.Textbox(
label="Transcribe JSON Input",
placeholder='{"text": "Full text", "chunks": [{"text": "Segment 1", "timestamp": [0, 2.5]}, ...]}',
lines=10
)
# Parameters
word_break_threshold = gr.Slider(
minimum=5,
maximum=20,
value=10,
step=1,
label="Word Break Threshold"
)
language = gr.Dropdown(
choices=["en", "es", "fr"],
value="en",
label="Language"
)
include_speaker = gr.Checkbox(
label="Include Speaker Information",
value=False
)
convert_btn = gr.Button("Convert to SRT", variant="primary")
with gr.Column():
# Output section
srt_output = gr.Textbox(
label="SRT Output",
lines=15,
placeholder="SRT formatted subtitles will appear here..."
)
status_message = gr.Textbox(
label="Status",
interactive=False
)
# Examples
examples = gr.Examples(
examples=[
[
'{"text": "Hello world. This is a test. How are you today?", "chunks": [{"text": "Hello world.", "timestamp": [0, 1.5]}, {"text": "This is a test.", "timestamp": [1.5, 3.2]}, {"text": "How are you today?", "timestamp": [3.2, 5.0]}]}',
10,
"en",
False
],
[
'{"text": "Hola mundo. Esto es una prueba. ¿Cómo estás hoy?", "chunks": [{"text": "Hola mundo.", "timestamp": [0, 1.5]}, {"text": "Esto es una prueba.", "timestamp": [1.5, 3.2]}, {"text": "¿Cómo estás hoy?", "timestamp": [3.2, 5.0]}]}',
10,
"es",
False
]
],
inputs=[json_input, word_break_threshold, language, include_speaker],
outputs=[srt_output, status_message],
fn=convert_transcription,
cache_examples=True,
label="Examples"
)
# Event listener
convert_btn.click(
fn=convert_transcription,
inputs=[json_input, word_break_threshold, language, include_speaker],
outputs=[srt_output, status_message],
api_visibility="public"
)
# Launch with modern theme and styling
demo.launch(
theme=gr.themes.Soft(
primary_hue="blue",
secondary_hue="indigo",
neutral_hue="slate",
font=gr.themes.GoogleFont("Inter"),
text_size="lg",
spacing_size="lg",
radius_size="md"
).set(
button_primary_background_fill="*primary_600",
button_primary_background_fill_hover="*primary_700",
block_title_text_weight="600",
),
footer_links=[
{"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"},
{"label": "Gradio Docs", "url": "https://www.gradio.app/docs"},
{"label": "GitHub", "url": "https://github.com/gradio-app/gradio"}
],
css="""
.gradio-container {
max-width: 1200px !important;
margin: 0 auto !important;
}
.gr-box {
border-radius: 8px !important;
}
"""
) |