File size: 4,150 Bytes
202725c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import cv2
import numpy as np
from PIL import Image, ImageEnhance
from tqdm import tqdm
import gradio as gr
import tempfile

def enhance_frame(frame, sharpness=4, contrast=1.1, blur=3):
    """Enhance a video frame's sharpness, contrast, and blur."""
    try:
        # Convert the frame to RGB (if it's in BGR format)
        frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

        # Convert the frame to PIL Image
        pil_img = Image.fromarray(frame)

        # Enhance the sharpness
        enhancer = ImageEnhance.Sharpness(pil_img)
        enhanced_frame = enhancer.enhance(sharpness)

        # Enhance the contrast
        enhancer = ImageEnhance.Contrast(enhanced_frame)
        enhanced_frame = enhancer.enhance(contrast)

        # Convert back to numpy array
        enhanced_frame = np.array(enhanced_frame)

        # Apply Gaussian blur
        enhanced_frame = cv2.GaussianBlur(enhanced_frame, (blur, blur), 0)

        # Convert back to BGR format for OpenCV
        enhanced_frame = cv2.cvtColor(enhanced_frame, cv2.COLOR_RGB2BGR)

        return enhanced_frame
    except Exception as e:
        raise ValueError(f"Error enhancing frame: {str(e)}")

def enhance_video(input_path, output_path, sharpness=4, contrast=1.3, blur=3):
    """Enhance a video's sharpness, contrast, and blur."""
    try:
        # Open the video file
        cap = cv2.VideoCapture(input_path)

        if not cap.isOpened():
            raise ValueError("Error: Could not open video file.")

        # Get video properties
        fps = cap.get(cv2.CAP_PROP_FPS)
        width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))

        if total_frames == 0:
            raise ValueError("Error: Video file has no frames.")

        # Define the codec and create VideoWriter object
        fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # Using mp4v codec for mp4 files
        out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))

        if not out.isOpened():
            cap.release()
            raise ValueError("Error: Could not open video writer.")

        # Process each frame with tqdm progress bar
        for _ in tqdm(range(total_frames), desc="Processing frames"):
            ret, frame = cap.read()
            if not ret:
                break

            # Enhance the frame
            enhanced_frame = enhance_frame(frame, sharpness, contrast, blur)

            # Write the enhanced frame to the output video
            out.write(enhanced_frame)

        # Release everything when done
        cap.release()
        out.release()
    except Exception as e:
        if 'cap' in locals():
            cap.release()
        if 'out' in locals():
            out.release()
        raise ValueError(f"Error enhancing video: {str(e)}")

def video_enhancer(input_video, sharpness=4, contrast=1.3, blur=3):
    """Gradio interface function to enhance videos."""
    try:
        # Check if input file exists
        if not os.path.exists(input_video):
            raise FileNotFoundError("Input video file not found.")

        # Generate a temporary output path
        temp_dir = tempfile.gettempdir()
        base_name = os.path.basename(input_video)
        name, ext = os.path.splitext(base_name)
        output_path = os.path.join(temp_dir, f"enhanced_{name}.mp4")

        # Process the video
        enhance_video(input_video, output_path, sharpness, contrast, blur)

        return output_path
    except Exception as e:
        return f"Error: {str(e)}"

# Create the Gradio interface
iface = gr.Interface(
    fn=video_enhancer,
    inputs=[
        gr.Video(label="Upload Video"),
        gr.Slider(minimum=1, maximum=10, value=4, label="Sharpness"),
        gr.Slider(minimum=0.5, maximum=2, step=0.1, value=1.1, label="Contrast"),
        gr.Slider(minimum=1, maximum=10, step=0.1, value=3, label="Blur")
    ],
    outputs=gr.Video(label="Download Enhanced Video"),
    title="Video Enhancer",
    description="Enhance your videos by adjusting sharpness, contrast, and blur."
)

iface.launch()