Adityadn commited on
Commit
f3da3f2
·
verified ·
1 Parent(s): 3d4d3e0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -90
app.py CHANGED
@@ -1,110 +1,83 @@
1
- import gradio as gr
2
  import ffmpeg
3
  import os
4
  from PIL import Image
5
  import re
6
  import tempfile
7
 
 
 
8
  # Supported formats
9
  supported_formats = sorted(['3GP', 'ASF', 'AVI', 'DIVX', 'FLV', 'M2TS', 'M4V', 'MKV', 'MOV', 'MP4', 'MPEG', 'MPG', 'MTS', 'TS', 'VOB', 'WEBM', 'WMV', 'XVID'])
10
  audio_formats = sorted(['MP3', 'WAV', 'AAC', 'FLAC', 'OGG', 'M4A', 'ALAC', 'WMA', 'AIFF', 'OPUS', 'APE', 'CAF', 'PCM', 'DTS', 'TTA', 'AMR', 'MID', 'SPX', 'WV', 'RA', 'TAK'])
11
- gif_formats = ['GIF']
12
- image_formats = sorted(Image.SAVE.keys()) or ['BLP', 'BMP', 'BUFR', 'DDS', 'DIB', 'EPS',
13
- 'GIF', 'GRIB', 'HDF5', 'ICNS', 'ICO', 'IM',
14
- 'JPEG', 'JPEG2000', 'MPO', 'MSP', 'PALM', 'PCX',
15
- 'PDF', 'PNG', 'PPM', 'SGI', 'SPIDER', 'TGA', 'TIFF',
16
- 'WEBP', 'WMX', 'XBM']
17
-
18
- def sanitize_filename(filename):
19
- """Sanitize filename by removing special characters and spaces."""
20
- filename = re.sub(r'[^a-zA-Z0-9_.-]', '_', filename) # Replace invalid characters with '_'
21
- return filename
22
-
23
- def get_video_duration(video_path):
24
- """Get video duration in seconds using ffmpeg."""
25
- probe = ffmpeg.probe(video_path, v='error', select_streams='v:0', show_entries='stream=duration')
26
- duration_in_seconds = float(probe['streams'][0]['duration'])
27
- return duration_in_seconds
28
-
29
- def convert_video(video, target_format, conversion_type, time_in_seconds=None):
30
- try:
31
- # Create a temporary directory for the uploaded file
32
- temp_dir = tempfile.mkdtemp()
33
-
34
- # Sanitize the filename and save the uploaded video to the temp directory
35
- base_name = os.path.splitext(os.path.basename(video.name))[0]
36
- sanitized_base_name = sanitize_filename(base_name)
37
  video_path = os.path.join(temp_dir, f"{sanitized_base_name}.mp4") # Saving as mp4 by default for now
38
 
39
  with open(video_path, "wb") as f:
40
- f.write(video) # Save the uploaded video to a local file
41
 
42
  if conversion_type == 'Video to Video':
43
  output_file = f"flowly_ai_video_converter_{sanitized_base_name}.{target_format.lower()}"
44
- ffmpeg.input(video_path).output(output_file).run() # Use ffmpeg.input properly
45
- return output_file
46
-
47
- elif conversion_type == 'Video to Audio':
48
- audio_output_file = f"flowly_ai_video_to_audio_{sanitized_base_name}.{target_format.lower()}"
49
- ffmpeg.input(video_path).output(audio_output_file).run() # Use ffmpeg.input properly
50
- return audio_output_file
51
-
52
- elif conversion_type == 'Video to GIF':
53
- gif_output_file = f"flowly_ai_video_to_gif_{sanitized_base_name}.gif"
54
- ffmpeg.input(video_path).output(gif_output_file, vf="fps=10,scale=320:-1:flags=lanczos").run() # Use ffmpeg.input properly
55
- return gif_output_file
56
-
57
- elif conversion_type == 'Video to Image':
58
- if time_in_seconds is None:
59
- return "Please specify a valid time in seconds for image extraction."
60
-
61
- image_output_file = f"flowly_ai_video_to_image_{sanitized_base_name}_{time_in_seconds}.png"
62
- ffmpeg.input(video_path, ss=time_in_seconds).output(image_output_file, vframes=1).run() # Use ffmpeg.input properly
63
-
64
- # Convert the image to the desired format using Pillow
65
- img = Image.open(image_output_file)
66
- if target_format.lower() in image_formats:
67
- image_output_file = f"flowly_ai_video_to_image_{sanitized_base_name}_{time_in_seconds}.{target_format.lower()}"
68
- img.save(image_output_file, target_format.upper()) # Save with the desired format
69
-
70
- return image_output_file
71
-
72
- except Exception as e:
73
- return f"Error: {e}"
74
-
75
- def update_format_choices(conversion_type):
76
- """Update available format choices based on the conversion type."""
77
- if conversion_type == 'Video to Video':
78
- return supported_formats
79
- elif conversion_type == 'Video to Audio':
80
- return audio_formats
81
- elif conversion_type == 'Video to GIF':
82
- return gif_formats
83
- elif conversion_type == 'Video to Image':
84
  return image_formats
85
  return []
86
 
87
- def convert_function(video_file, conversion_type, target_format, time_in_seconds=None):
88
- # Convert the video based on user input
89
- video_file_content = video_file.read()
90
- return convert_video(video_file_content, target_format, conversion_type, time_in_seconds)
91
-
92
- def gradio_interface():
93
- # Set up Gradio interface
94
- with gr.Blocks() as demo:
95
- gr.Markdown("# Video Conversion Tool")
96
- gr.Markdown("Convert videos to audio, GIFs, images, or other formats easily with this powerful tool.")
97
-
98
- with gr.Row():
99
- video_file = gr.File(label="Upload Video File", type="filepath", file_types=supported_formats)
100
- conversion_type = gr.Dropdown(label="Select Conversion Type", choices=['Video to Video', 'Video to Audio', 'Video to GIF', 'Video to Image'])
101
- target_format = gr.Dropdown(label="Select Target Format", choices=supported_formats)
102
- time_in_seconds = gr.Slider(label="Time (in seconds) for image extraction", minimum=0, maximum=300, step=1, value=0)
103
- output_file = gr.File(label="Converted File", interactive=False)
104
-
105
- video_file.change(fn=convert_function, inputs=[video_file, conversion_type, target_format, time_in_seconds], outputs=output_file)
106
-
107
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
 
109
  if __name__ == "__main__":
110
- gradio_interface()
 
1
+ import streamlit as st
2
  import ffmpeg
3
  import os
4
  from PIL import Image
5
  import re
6
  import tempfile
7
 
8
+ st.set_page_config(layout="wide", page_title="Video Conversion Tool")
9
+
10
  # Supported formats
11
  supported_formats = sorted(['3GP', 'ASF', 'AVI', 'DIVX', 'FLV', 'M2TS', 'M4V', 'MKV', 'MOV', 'MP4', 'MPEG', 'MPG', 'MTS', 'TS', 'VOB', 'WEBM', 'WMV', 'XVID'])
12
  audio_formats = sorted(['MP3', 'WAV', 'AAC', 'FLAC', 'OGG', 'M4A', 'ALAC', 'WMA', 'AIFF', 'OPUS', 'APE', 'CAF', 'PCM', 'DTS', 'TTA', 'AMR', 'MID', 'SPX', 'WV', 'RA', 'TAK'])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13
  video_path = os.path.join(temp_dir, f"{sanitized_base_name}.mp4") # Saving as mp4 by default for now
14
 
15
  with open(video_path, "wb") as f:
16
+ f.write(video.getbuffer()) # Save the uploaded video to a local file
17
 
18
  if conversion_type == 'Video to Video':
19
  output_file = f"flowly_ai_video_converter_{sanitized_base_name}.{target_format.lower()}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  return image_formats
21
  return []
22
 
23
+ def main():
24
+ st.title("Video Conversion Tool")
25
+ st.write("Convert videos to audio, GIFs, images, or other formats easily with this powerful tool.")
26
+
27
+ # Create two columns
28
+ col1, col2 = st.columns([1, 1])
29
+
30
+ with col1:
31
+ # Upload video file
32
+ video_file = st.file_uploader("Upload a Video", type=supported_formats)
33
+ if video_file:
34
+ st.video(video_file)
35
+
36
+ with col2:
37
+ if video_file:
38
+ # Create a temporary file and save uploaded video
39
+ temp_video_path = os.path.join(tempfile.mkdtemp(), video_file.name)
40
+ with open(temp_video_path, "wb") as f:
41
+ f.write(video_file.getbuffer())
42
+
43
+ # Get video duration
44
+ video_duration = get_video_duration(temp_video_path)
45
+
46
+ # Select conversion type
47
+ conversion_type = st.selectbox(
48
+ "Select Conversion Type",
49
+ ['Video to Video', 'Video to Audio', 'Video to GIF', 'Video to Image']
50
+ )
51
+
52
+ # Update format choices based on conversion type
53
+ target_format_choices = update_format_choices(conversion_type)
54
+ target_format = st.selectbox("Select Target Format", target_format_choices)
55
+
56
+ # If 'Video to Image' conversion, ask for time in seconds
57
+ if conversion_type == 'Video to Image':
58
+ time_in_seconds = st.slider(
59
+ label="Time (in seconds) for image extraction",
60
+ min_value=0,
61
+ max_value=int(video_duration),
62
+ value=0,
63
+ step=1
64
+ )
65
+ else:
66
+ time_in_seconds = None
67
+
68
+ if st.button("Convert"):
69
+ with st.spinner("Converting..."):
70
+ output_file = convert_video(video_file, target_format, conversion_type, time_in_seconds)
71
+
72
+ if "Error" in output_file:
73
+ st.error(output_file)
74
+ else:
75
+ st.success(f"Conversion Successful! Download the file:")
76
+ st.download_button(
77
+ label="Download Converted File",
78
+ data=open(output_file, 'rb').read(),
79
+ file_name=output_file
80
+ )
81
 
82
  if __name__ == "__main__":
83
+ main()