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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
"""
Video Hard-Subtitle OCR Application
Extract text from video hard subtitles with customizable region selection
"""

import gradio as gr
import cv2
import numpy as np
import json
import os
import tempfile
from datetime import datetime
from pathlib import Path

# Try to import optional dependencies
try:
    import moviepy.editor as mp
    MOVIEPY_AVAILABLE = True
except ImportError:
    MOVIEPY_AVAILABLE = False

try:
    import easyocr
    EASYOCR_AVAILABLE = True
except ImportError:
    EASYOCR_AVAILABLE = False


# Language to OCR language code mapping
LANGUAGE_CODES = {
    "English": "en",
    "Japanese": "ja",
    "Korean": "ko",
    "Chinese (Simplified)": "ch_sim",
    "Chinese (Traditional)": "ch_tra",
    "Thai": "th"
}

# OCR Reader cache
_reader_cache = {}


def get_ocr_reader(language: str):
    """Get or create OCR reader for specified language"""
    lang_code = LANGUAGE_CODES.get(language, "en")
    
    if lang_code in _reader_cache:
        return _reader_cache[lang_code]
    
    if EASYOCR_AVAILABLE:
        try:
            reader = easyocr.Reader([lang_code], gpu=False, verbose=False)
            _reader_cache[lang_code] = reader
            return reader
        except Exception as e:
            return None
    return None


def extract_frames_from_video(video_path: str, start_time: float, end_time: float):
    """Extract frames from video in the specified time range"""
    frames = []
    timestamps = []
    
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return frames, timestamps
    
    fps = cap.get(cv2.CAP_PROP_FPS)
    total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = total_frames / fps if fps > 0 else 0
    
    start_frame = int(start_time * fps)
    end_frame = int(end_time * fps)
    
    cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame)
    
    current_frame = start_frame
    while current_frame <= end_frame:
        ret, frame = cap.read()
        if not ret:
            break
        
        timestamp = current_frame / fps
        frames.append(frame)
        timestamps.append(timestamp)
        current_frame += 1
    
    cap.release()
    return frames, timestamps


def extract_subtitle_from_frame(frame, x: int, y: int, width: int, height: int, reader):
    """Extract text from a specific region of a frame"""
    h, w = frame.shape[:2]
    
    # Ensure coordinates are within bounds
    x = max(0, min(x, w - 1))
    y = max(0, min(y, h - 1))
    width = min(width, w - x)
    height = min(height, h - y)
    
    if width <= 0 or height <= 0:
        return ""
    
    # Crop the subtitle region
    roi = frame[y:y+height, x:x+width]
    
    # Convert to RGB for OCR
    roi_rgb = cv2.cvtColor(roi, cv2.COLOR_BGR2RGB)
    
    try:
        results = reader.readtext(roi_rgb)
        if results:
            # Get the text with highest confidence
            text = " ".join([result[1] for result in results])
            return text.strip()
    except Exception:
        pass
    
    return ""


def merge_subtitles(subtitles: list, time_threshold: float = 1.0, iou_threshold: float = 0.5):
    """Merge consecutive subtitles that are similar or close in time"""
    if not subtitles:
        return []
    
    merged = []
    current = subtitles[0].copy()
    
    for i in range(1, len(subtitles)):
        next_sub = subtitles[i]
        
        # Check if they overlap in time
        time_gap = next_sub["start"] - current["end"]
        
        # Check if text is similar (simple check)
        text_similar = (
            next_sub["text"].strip().lower() == current["text"].strip().lower()
            or next_sub["text"].strip() in current["text"].strip()
        )
        
        if time_gap <= time_threshold and text_similar:
            # Extend current subtitle
            current["end"] = next_sub["end"]
        else:
            merged.append(current)
            current = next_sub.copy()
    
    merged.append(current)
    return merged


def process_video_ocr(
    video_path: str,
    x: int, y: int, width: int, height: int,
    language: str,
    start_time: float, end_time: float,
    progress=gr.Progress()
):
    """Main OCR processing function"""
    
    if not video_path:
        return None, "Please upload a video first.", ""
    
    if not EASYOCR_AVAILABLE:
        return None, "EasyOCR is not installed. Please install it with: pip install easyocr", ""
    
    reader = get_ocr_reader(language)
    if reader is None:
        return None, f"Could not initialize OCR for {language}", ""
    
    # Extract frames
    progress(0.1, "Extracting frames from video...")
    frames, timestamps = extract_frames_from_video(video_path, start_time, end_time)
    
    if not frames:
        return None, "Could not extract frames from video", ""
    
    # Process frames
    subtitles = []
    frame_interval = max(1, len(frames) // 100)  # Sample ~100 points
    
    for i, (frame, timestamp) in enumerate(frames):
        if i % frame_interval == 0:
            progress(0.1 + 0.7 * (i / len(frames)), f"Processing frame {i}/{len(frames)}...")
        
        text = extract_subtitle_from_frame(frame, x, y, width, height, reader)
        
        if text and text.strip():
            # Check if this is a new subtitle or continuation
            if subtitles and (timestamp - subtitles[-1]["end"]) < 0.5:
                # Might be continuation, check text similarity
                if text.strip() != subtitles[-1]["text"].strip():
                    subtitles.append({
                        "start": timestamp,
                        "end": timestamp + 0.1,
                        "text": text.strip()
                    })
            else:
                subtitles.append({
                    "start": timestamp,
                    "end": timestamp + 0.1,
                    "text": text.strip()
                })
    
    # Merge similar subtitles
    progress(0.85, "Merging subtitle entries...")
    subtitles = merge_subtitles(subtitles)
    
    # Assign sequential IDs
    for i, sub in enumerate(subtitles):
        sub["id"] = i + 1
    
    # Generate SRT
    progress(0.95, "Generating output files...")
    srt_output = generate_srt(subtitles)
    txt_output = generate_txt(subtitles)
    json_output = generate_json(subtitles, language, start_time, end_time)
    
    progress(1.0, "Complete!")
    
    return subtitles, srt_output, json_output


def generate_srt(subtitles: list) -> str:
    """Generate SRT format output"""
    srt_lines = []
    
    for sub in subtitles:
        sub_id = sub.get("id", 1)
        start_time = format_srt_time(sub["start"])
        end_time = format_srt_time(sub["end"])
        text = sub["text"]
        
        srt_lines.append(f"{sub_id}")
        srt_lines.append(f"{start_time} --> {end_time}")
        srt_lines.append(text)
        srt_lines.append("")
    
    return "\n".join(srt_lines)


def format_srt_time(seconds: float) -> str:
    """Format time for SRT (HH:MM:SS,mmm)"""
    hours = int(seconds // 3600)
    minutes = int((seconds % 3600) // 60)
    secs = int(seconds % 60)
    millis = int((seconds % 1) * 1000)
    return f"{hours:02d}:{minutes:02d}:{secs:02d},{millis:03d}"


def generate_txt(subtitles: list) -> str:
    """Generate plain text output"""
    return "\n".join([sub["text"] for sub in subtitles])


def generate_json(subtitles: list, language: str, start: float, end: float) -> str:
    """Generate JSON output"""
    output = {
        "metadata": {
            "language": language,
            "start_time": start,
            "end_time": end,
            "total_subtitles": len(subtitles),
            "generated_at": datetime.now().isoformat()
        },
        "subtitles": subtitles
    }
    return json.dumps(output, indent=2, ensure_ascii=False)


def get_video_info(video_path: str):
    """Get video information"""
    if not video_path or not os.path.exists(video_path):
        return 0, 0, 0, 0
    
    cap = cv2.VideoCapture(video_path)
    if not cap.isOpened():
        return 0, 0, 0, 0
    
    width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    fps = cap.get(cv2.CAP_PROP_FPS)
    frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    duration = frame_count / fps if fps > 0 else 0
    
    cap.release()
    
    return width, height, fps, duration


def create_demo():
    """Create the Gradio demo"""
    
    with gr.Blocks(title="Video Subtitle OCR") as demo:
        
        # Header with anycoder link
        gr.HTML("""
        <div style="text-align: center; padding: 10px; background: linear-gradient(90deg, #667eea 0%, #764ba2 100%); border-radius: 10px; margin-bottom: 20px;">
            <h1 style="color: white; margin: 0;">🎬 Video Subtitle OCR</h1>
            <p style="color: #e0e0e0; margin: 5px 0;">Extract hard-coded subtitles from any video</p>
            <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" style="color: #ffd700; font-weight: bold;">Built with anycoder</a>
        </div>
        """)
        
        with gr.Row():
            with gr.Column(scale=2):
                # Video upload and preview
                video_input = gr.Video(
                    label="Upload Video",
                    sources=["upload"],
                    height=400
                )
                
                # Video info display
                video_info = gr.JSON(label="Video Information", visible=False)
                
            with gr.Column(scale=1):
                # Settings panel
                gr.Markdown("### βš™οΈ Settings")
                
                # Language selection
                language = gr.Dropdown(
                    choices=list(LANGUAGE_CODES.keys()),
                    value="English",
                    label="OCR Language",
                    info="Select the primary language for OCR accuracy"
                )
                
                # Time range
                with gr.Row():
                    start_time = gr.Number(
                        label="Start Time (sec)",
                        value=0,
                        minimum=0,
                        step=0.1
                    )
                    end_time = gr.Number(
                        label="End Time (sec)",
                        value=10,
                        minimum=0,
                        step=0.1
                    )
        
        # Subtitle region adjustment
        gr.Markdown("### πŸ“ Adjust Subtitle Area")
        
        with gr.Row():
            with gr.Column():
                # Position sliders
                x_pos = gr.Slider(
                    minimum=0, maximum=100, value=10,
                    label="Horizontal Position (X %)",
                    info="X-axis position of subtitle box"
                )
                y_pos = gr.Slider(
                    minimum=0, maximum=100, value=80,
                    label="Vertical Position (Y %)",
                    info="Y-axis position of subtitle box"
                )
            
            with gr.Column():
                # Size sliders
                box_width = gr.Slider(
                    minimum=10, maximum=100, value=80,
                    label="Width (%)",
                    info="Width of subtitle box"
                )
                box_height = gr.Slider(
                    minimum=5, maximum=50, value=15,
                    label="Height (%)",
                    info="Height of subtitle box"
                )
        
        # Options
        with gr.Row():
            aspect_lock = gr.Checkbox(
                value=True,
                label="Lock Aspect Ratio",
                info="Maintain 16:9 aspect ratio for subtitle box"
            )
            auto_process = gr.Checkbox(
                value=False,
                label="Auto-process on change",
                info="Automatically process when parameters change"
            )
        
        # Reset button
        with gr.Row():
            reset_btn = gr.Button("β†Ί Reset to Defaults", variant="secondary")
        
        # Process button
        process_btn = gr.Button("πŸ” Process Video", variant="primary", size="lg")
        
        # Progress indicator
        progress_bar = gr.Progress()
        
        # Results section
        gr.Markdown("### πŸ“„ Results")
        
        with gr.Row():
            with gr.Column():
                # Subtitle list with status
                subtitle_list = gr.Dataframe(
                    headers=["ID", "Start", "End", "Status", "Text"],
                    datatype=["number", "str", "str", "str", "str"],
                    label="Extracted Subtitles",
                    wrap=True,
                    max_height=400
                )
            
            with gr.Column():
                # Export options
                with gr.Accordion("πŸ“₯ Export Options", open=True):
                    srt_output = gr.Textbox(
                        label="SRT Format",
                        lines=10,
                        max_lines=20
                    )
                    
                    with gr.Row():
                        download_srt = gr.DownloadButton(
                            label="Download SRT",
                            variant="secondary"
                        )
                        download_txt = gr.DownloadButton(
                            label="Download TXT",
                            variant="secondary"
                        )
                        download_json = gr.DownloadButton(
                            label="Download JSON",
                            variant="secondary"
                        )
        
        # Preview section
        gr.Markdown("### πŸ‘οΈ Active Subtitle Preview")
        
        subtitle_preview = gr.JSON(
            label="Active Subtitles Status",
            info="Shows subtitle status during video playback"
        )
        
        # Hidden state for processed data
        processed_data = gr.State()
        
        # Event handlers
        def update_video_info(video_path):
            """Update video information when video is uploaded"""
            if video_path:
                width, height, fps, duration = get_video_info(video_path)
                info = {
                    "Resolution": f"{width} x {height}",
                    "FPS": round(fps, 2) if fps else 0,
                    "Duration": f"{duration:.2f}s" if duration else "0s"
                }
                return info, {"visible": True}, duration
            return {}, {"visible": False}, 0
        
        def update_end_time_on_load(info, duration):
            """Update end time when video is loaded"""
            if duration > 0:
                return duration
            return 10
        
        def on_aspect_lock_change(lock, width, height):
            """Handle aspect ratio lock"""
            if lock and width:
                # Maintain 16:9 ratio
                new_height = width * 9 / 16
                return width, new_height
            return width, height
        
        def on_process(
            video_path, x, y, width, height,
            language, start, end, progress_bar
        ):
            """Handle video processing"""
            if not video_path:
                return (
                    gr.update(),
                    "Please upload a video first.",
                    "",
                    None
                )
            
            # Get video dimensions
            vw, vh, _, _ = get_video_info(video_path)
            
            # Convert percentages to pixels
            px = int(x / 100 * vw)
            py = int(y / 100 * vh)
            pw = int(width / 100 * vw)
            ph = int(height / 100 * vh)
            
            subtitles, srt, json_output = process_video_ocr(
                video_path, px, py, pw, ph,
                language, start, end,
                progress_bar
            )
            
            if subtitles is None:
                return (
                    gr.update(),
                    srt,  # Error message
                    "",
                    None
                )
            
            # Format for dataframe
            df_data = []
            for sub in subtitles:
                df_data.append([
                    sub.get("id", 0),
                    format_srt_time(sub["start"]).split(",")[0],
                    format_srt_time(sub["end"]).split(",")[0],
                    "entered",
                    sub["text"][:50] + "..." if len(sub["text"]) > 50 else sub["text"]
                ])
            
            # Create downloadable files
            with tempfile.NamedTemporaryFile(mode='w', suffix='.srt', delete=False) as f:
                f.write(srt)
                srt_path = f.name
            
            with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
                txt = generate_txt(subtitles)
                f.write(txt)
                txt_path = f.name
            
            with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
                f.write(json_output)
                json_path = f.name
            
            return (
                df_data,
                srt,
                {"paths": [srt_path, txt_path, json_path]},
                json_output
            )
        
        def reset_defaults():
            """Reset all settings to defaults"""
            return (
                10,  # x
                80,  # y
                80,  # width
                15,  # height
                "English",
                0,
                10
            )
        
        def update_active_subtitles(subtitle_json, current_time):
            """Update active subtitle status based on current time"""
            if not subtitle_json:
                return {}
            
            try:
                data = json.loads(subtitle_json) if isinstance(subtitle_json, str) else subtitle_json
                subtitles = data.get("subtitles", [])
            except:
                return {}
            
            active = {}
            for sub in subtitles:
                start = sub.get("start", 0)
                end = sub.get("end", 0)
                sub_id = sub.get("id", 0)
                
                if current_time < start:
                    status = "entered"
                elif start <= current_time <= end:
                    status = "active"
                else:
                    status = "exited"
                
                active[f"Subtitle {sub_id}"] = {
                    "status": status,
                    "text": sub["text"][:30] + "..." if len(sub["text"]) > 30 else sub["text"],
                    "time": f"{start:.2f}s - {end:.2f}s"
                }
            
            return active
        
        # Bind events
        video_input.change(
            update_video_info,
            inputs=[video_input],
            outputs=[video_info, video_info, end_time]
        ).then(
            update_end_time_on_load,
            inputs=[video_info, end_time],
            outputs=[end_time]
        )
        
        aspect_lock.change(
            on_aspect_lock_change,
            inputs=[aspect_lock, box_width, box_height],
            outputs=[box_width, box_height]
        )
        
        reset_btn.click(
            reset_defaults,
            outputs=[x_pos, y_pos, box_width, box_height, language, start_time, end_time]
        )
        
        process_btn.click(
            on_process,
            inputs=[
                video_input, x_pos, y_pos, box_width, box_height,
                language, start_time, end_time, progress_bar
            ],
            outputs=[subtitle_list, srt_output, processed_data, subtitle_preview]
        )
        
        # Setup download buttons
        def prepare_downloads(data_state):
            if data_state and "paths" in data_state:
                paths = data_state["paths"]
                return (
                    paths[0],  # srt
                    paths[1],  # txt
                    paths[2]   # json
                )
            return None, None, None
        
        processed_data.change(
            prepare_downloads,
            inputs=[processed_data],
            outputs=[download_srt, download_txt, download_json]
        )
    
    return demo


# Create and launch the demo
if __name__ == "__main__":
    demo = create_demo()
    
    # Custom CSS for better UI
    custom_css = """
    .gradio-container {
        max-width: 1400px !important;
        margin: auto;
    }
    .subtitle-active {
        background-color: #4CAF50 !important;
        color: white !important;
        box-shadow: 0 0 10px #4CAF50;
    }
    .subtitle-entered {
        background-color: #2196F3 !important;
        color: white !important;
    }
    .subtitle-exited {
        background-color: #9E9E9E !important;
        color: white !important;
        opacity: 0.6;
    }
    """
    
    demo.launch(
        theme=gr.themes.Soft(
            primary_hue="indigo",
            secondary_hue="purple",
            neutral_hue="slate",
            font=gr.themes.GoogleFont("Inter")
        ),
        css=custom_css,
        footer_links=[
            {"label": "Built with anycoder", "url": "https://huggingface.co/spaces/akhaliq/anycoder"}
        ]
    )