Adityadn commited on
Commit
2ceb823
·
verified ·
1 Parent(s): 1eecb36

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -102
app.py CHANGED
@@ -15,12 +15,10 @@ def delete_temp_dir(directory, delay=900): # 15 minutes = 900 seconds
15
  st.set_page_config(layout="wide", page_title="Video Conversion Tool")
16
 
17
  # Supported formats
18
- supported_formats = (data for data in (sorted(['3GP', 'ASF', 'AVI', 'DIVX', 'FLV', 'M2TS', 'M4V', 'MKV', 'MOV', 'MP4', 'MPEG', 'MPG', 'MTS', 'TS', 'VOB', 'WEBM', 'WMV', 'XVID'])) if data not in ['3GP', 'DIVX', 'XVID'])
19
- audio_formats = sorted(['MP3', 'WAV', 'AAC', 'FLAC', 'OGG', 'M4A', 'ALAC', 'WMA', 'AIFF', 'OPUS', 'APE', 'CAF', 'PCM', 'DTS', 'TTA', 'AMR', 'MID', 'SPX', 'WV', 'RA', 'TAK'])
20
  gif_formats = ['GIF']
21
- image_formats = sorted(Image.SAVE.keys()) or ['BLP', 'BMP', 'BUFR', 'DDS', 'DIB', 'EPS', 'GIF', 'GRIB', 'HDF5', 'ICNS', 'ICO', 'IM',
22
- 'JPEG', 'JPEG2000', 'MPO', 'MSP', 'PALM', 'PCX', 'PDF', 'PNG', 'PPM', 'SGI', 'SPIDER',
23
- 'TGA', 'TIFF', 'WEBP', 'WMX', 'XBM']
24
 
25
  CACHE_DIR = tempfile.mkdtemp()
26
  delete_temp_dir(CACHE_DIR, delay=900) # Clean up cache after 15 minutes
@@ -29,69 +27,48 @@ def sanitize_filename(filename):
29
  """Sanitize filename by removing special characters and spaces."""
30
  return re.sub(r'[^a-zA-Z0-9_.-]', '_', filename)
31
 
32
- def clean_cache():
33
- """Remove files in the cache directory older than 15 minutes."""
34
- now = time.time()
35
- for file in os.listdir(CACHE_DIR):
36
- file_path = os.path.join(CACHE_DIR, file)
37
- if os.path.isfile(file_path) and now - os.path.getmtime(file_path) > 900: # 15 minutes
38
- os.remove(file_path)
39
-
40
  def get_video_duration(video_path):
41
  """Get video duration in seconds using ffmpeg."""
42
- probe = ffmpeg.probe(video_path, v='error', select_streams='v:0', show_entries='stream=duration')
43
- return float(probe['streams'][0]['duration'])
44
-
45
- def convert_video(video, target_format, conversion_type, time_in_seconds=None):
46
  try:
47
- # Create a temporary directory for the uploaded file
48
- temp_dir = tempfile.mkdtemp()
49
-
50
- # Sanitize the filename and save the uploaded video to the temp directory
51
- base_name = os.path.splitext(os.path.basename(video.name))[0]
52
- sanitized_base_name = sanitize_filename(base_name)
53
- video_path = os.path.join(temp_dir, f"{sanitized_base_name}.mp4") # Saving as mp4 by default for now
54
 
55
- with open(video_path, "wb") as f:
56
- f.write(video.getbuffer()) # Save the uploaded video to a local file
 
 
 
57
 
58
  if conversion_type == 'Video to Video':
59
- output_file = f"flowly_ai_video_converter_{sanitized_base_name}.{target_format.lower()}"
60
- ffmpeg.input(video_path).output(output_file).overwrite_output().run() # Add .overwrite_output()
61
- return output_file
62
 
63
  elif conversion_type == 'Video to Audio':
64
- audio_output_file = f"flowly_ai_video_to_audio_{sanitized_base_name}.{target_format.lower()}"
65
- ffmpeg.input(video_path).output(audio_output_file).overwrite_output().run() # Add .overwrite_output()
66
- return audio_output_file
67
 
68
  elif conversion_type == 'Video to GIF':
69
- gif_output_file = f"flowly_ai_video_to_gif_{sanitized_base_name}.gif"
70
- ffmpeg.input(video_path).output(gif_output_file, vf="fps=10,scale=320:-1:flags=lanczos").overwrite_output().run() # Add .overwrite_output()
71
- return gif_output_file
72
 
73
  elif conversion_type == 'Video to Image':
74
  if time_in_seconds is None:
75
  return "Please specify a valid time in seconds for image extraction."
 
 
76
 
77
- image_output_file = f"flowly_ai_video_to_image_{sanitized_base_name}_{time_in_seconds}.png"
78
- ffmpeg.input(video_path, ss=time_in_seconds).output(image_output_file, vframes=1).overwrite_output().run() # Add .overwrite_output()
79
-
80
- # Convert the image to the desired format using Pillow
81
- img = Image.open(image_output_file)
82
- if target_format.lower() in image_formats:
83
- image_output_file = f"flowly_ai_video_to_image_{sanitized_base_name}_{time_in_seconds}.{target_format.lower()}"
84
- img.save(image_output_file, target_format.upper()) # Save with the desired format
85
-
86
- return image_output_file
87
 
88
  except Exception as e:
89
- return f"Error: {e}"
90
-
91
  def update_format_choices(conversion_type):
92
- """Update available format choices based on the conversion type."""
93
  if conversion_type == 'Video to Video':
94
- return supported_formats
95
  elif conversion_type == 'Video to Audio':
96
  return audio_formats
97
  elif conversion_type == 'Video to GIF':
@@ -104,60 +81,44 @@ def main():
104
  st.title("Video Conversion Tool")
105
  st.write("Convert videos to audio, GIFs, images, or other formats easily with this powerful tool.")
106
 
107
- # Create two columns
108
- col1, col2 = st.columns([1, 1])
109
-
110
- with col1:
111
- # Upload video file
112
- video_file = st.file_uploader("Upload a Video", type=supported_formats)
113
- if video_file:
114
- st.video(video_file)
115
-
116
- with col2:
117
- if video_file:
118
- # Save uploaded video to cache
119
- temp_video_path = os.path.join(CACHE_DIR, video_file.name)
120
- with open(temp_video_path, "wb") as f:
121
- f.write(video_file.getbuffer())
122
-
123
- # Get video duration
124
- video_duration = get_video_duration(temp_video_path)
125
-
126
- # Select conversion type
127
- conversion_type = st.selectbox(
128
- "Select Conversion Type",
129
- ['Video to Video', 'Video to Audio', 'Video to GIF', 'Video to Image']
130
- )
131
 
132
- # Update format choices based on conversion type
133
- target_format_choices = update_format_choices(conversion_type)
134
- target_format = st.selectbox("Select Target Format", target_format_choices)
135
-
136
- # If 'Video to Image' conversion, ask for time in seconds
137
- if conversion_type == 'Video to Image':
138
- time_in_seconds = st.slider(
139
- label="Time (in seconds) for image extraction",
140
- min_value=0,
141
- max_value=int(video_duration),
142
- value=0,
143
- step=1
144
- )
145
- else:
146
- time_in_seconds = None
147
-
148
- if st.button("Convert"):
149
- with st.spinner("Converting..."):
150
- output_file = convert_video(video_file, target_format, conversion_type, time_in_seconds)
151
-
152
- if "Error" in output_file:
153
- st.error(output_file)
154
- else:
155
- st.success("Conversion Successful! Download the file:")
156
- st.download_button(
157
- label="Download Converted File",
158
- data=open(output_file, 'rb').read(),
159
- file_name=os.path.basename(output_file)
160
- )
 
 
 
 
 
 
 
161
 
162
  if __name__ == "__main__":
163
  main()
 
15
  st.set_page_config(layout="wide", page_title="Video Conversion Tool")
16
 
17
  # Supported formats
18
+ video_formats = ['3GP', 'ASF', 'AVI', 'FLV', 'M4V', 'MKV', 'MOV', 'MP4', 'MPEG', 'MPG', 'TS', 'WEBM', 'WMV']
19
+ audio_formats = ['MP3', 'WAV', 'AAC', 'FLAC', 'OGG', 'M4A']
20
  gif_formats = ['GIF']
21
+ image_formats = ['JPEG', 'PNG', 'BMP', 'TIFF']
 
 
22
 
23
  CACHE_DIR = tempfile.mkdtemp()
24
  delete_temp_dir(CACHE_DIR, delay=900) # Clean up cache after 15 minutes
 
27
  """Sanitize filename by removing special characters and spaces."""
28
  return re.sub(r'[^a-zA-Z0-9_.-]', '_', filename)
29
 
 
 
 
 
 
 
 
 
30
  def get_video_duration(video_path):
31
  """Get video duration in seconds using ffmpeg."""
 
 
 
 
32
  try:
33
+ probe = ffmpeg.probe(video_path)
34
+ duration = float(probe['streams'][0]['duration'])
35
+ return duration
36
+ except Exception as e:
37
+ st.error(f"Error getting video duration: {e}")
38
+ return 0
 
39
 
40
+ def convert_video(video_path, target_format, conversion_type, time_in_seconds=None):
41
+ try:
42
+ # Sanitize the filename
43
+ sanitized_base_name = sanitize_filename(os.path.splitext(os.path.basename(video_path))[0])
44
+ output_file = None
45
 
46
  if conversion_type == 'Video to Video':
47
+ output_file = os.path.join(CACHE_DIR, f"{sanitized_base_name}.{target_format.lower()}")
48
+ ffmpeg.input(video_path).output(output_file).overwrite_output().run()
 
49
 
50
  elif conversion_type == 'Video to Audio':
51
+ output_file = os.path.join(CACHE_DIR, f"{sanitized_base_name}.{target_format.lower()}")
52
+ ffmpeg.input(video_path).output(output_file, audio_bitrate='192k').overwrite_output().run()
 
53
 
54
  elif conversion_type == 'Video to GIF':
55
+ output_file = os.path.join(CACHE_DIR, f"{sanitized_base_name}.gif")
56
+ ffmpeg.input(video_path).output(output_file, vf="fps=10,scale=320:-1").overwrite_output().run()
 
57
 
58
  elif conversion_type == 'Video to Image':
59
  if time_in_seconds is None:
60
  return "Please specify a valid time in seconds for image extraction."
61
+ output_file = os.path.join(CACHE_DIR, f"{sanitized_base_name}_{time_in_seconds}.png")
62
+ ffmpeg.input(video_path, ss=time_in_seconds).output(output_file, vframes=1).overwrite_output().run()
63
 
64
+ return output_file
 
 
 
 
 
 
 
 
 
65
 
66
  except Exception as e:
67
+ return f"Error during conversion: {e}"
68
+
69
  def update_format_choices(conversion_type):
 
70
  if conversion_type == 'Video to Video':
71
+ return video_formats
72
  elif conversion_type == 'Video to Audio':
73
  return audio_formats
74
  elif conversion_type == 'Video to GIF':
 
81
  st.title("Video Conversion Tool")
82
  st.write("Convert videos to audio, GIFs, images, or other formats easily with this powerful tool.")
83
 
84
+ video_file = st.file_uploader("Upload a Video", type=video_formats)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
 
86
+ if video_file:
87
+ temp_video_path = os.path.join(CACHE_DIR, sanitize_filename(video_file.name))
88
+ with open(temp_video_path, "wb") as f:
89
+ f.write(video_file.getbuffer())
90
+
91
+ st.video(temp_video_path)
92
+
93
+ video_duration = get_video_duration(temp_video_path)
94
+
95
+ conversion_type = st.selectbox(
96
+ "Select Conversion Type",
97
+ ['Video to Video', 'Video to Audio', 'Video to GIF', 'Video to Image']
98
+ )
99
+ target_format_choices = update_format_choices(conversion_type)
100
+ target_format = st.selectbox("Select Target Format", target_format_choices)
101
+
102
+ if conversion_type == 'Video to Image':
103
+ time_in_seconds = st.slider(
104
+ "Time (in seconds) for image extraction",
105
+ min_value=0,
106
+ max_value=int(video_duration),
107
+ value=0,
108
+ step=1
109
+ )
110
+ else:
111
+ time_in_seconds = None
112
+
113
+ if st.button("Convert"):
114
+ with st.spinner("Converting..."):
115
+ output_file = convert_video(temp_video_path, target_format, conversion_type, time_in_seconds)
116
+ if "Error" in output_file:
117
+ st.error(output_file)
118
+ else:
119
+ st.success("Conversion Successful! Download the file:")
120
+ with open(output_file, 'rb') as f:
121
+ st.download_button("Download", f.read(), os.path.basename(output_file))
122
 
123
  if __name__ == "__main__":
124
  main()