NeuralFalcon commited on
Commit
a1687a8
1 Parent(s): 0cf9285

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +181 -0
app.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import shutil
4
+ import subprocess
5
+ import uuid
6
+ import json
7
+ from datetime import datetime
8
+
9
+
10
+
11
+ from pydub import AudioSegment
12
+
13
+ def mp3_to_wav(mp3_file, wav_file):
14
+ # Load the MP3 file
15
+ audio = AudioSegment.from_mp3(mp3_file)
16
+
17
+ # Export the audio to WAV format
18
+ audio.export(wav_file, format="wav")
19
+
20
+ from pydub import AudioSegment
21
+ from pydub.silence import split_on_silence
22
+ import os
23
+
24
+ def remove_silence(file_path,output_path):
25
+ # Extract file name and format from the provided path
26
+ file_name = os.path.basename(file_path)
27
+ audio_format = "wav"
28
+
29
+ # Reading and splitting the audio file into chunks
30
+ sound = AudioSegment.from_file(file_path, format=audio_format)
31
+ audio_chunks = split_on_silence(sound,
32
+ min_silence_len=100,
33
+ silence_thresh=-45,
34
+ keep_silence=50)
35
+
36
+ # Putting the file back together
37
+ combined = AudioSegment.empty()
38
+ for chunk in audio_chunks:
39
+ combined += chunk
40
+
41
+
42
+ combined.export(output_path, format=audio_format)
43
+
44
+ return output_path
45
+
46
+ def process_file(upload_audio_path):
47
+ base_path = os.path.dirname(upload_audio_path)
48
+ base_file_name = os.path.basename(upload_audio_path)
49
+ file_name_without_extension, file_extension = os.path.splitext(base_file_name)
50
+ random_uuid = str(uuid.uuid4())[:8]
51
+ if file_extension.lower() == ".mp3":
52
+ new_file_name = f"{random_uuid}.wav"
53
+ save_path= os.path.join(base_path, new_file_name)
54
+ mp3_to_wav(upload_audio_path, save_path)
55
+ elif file_extension.lower() == ".wav":
56
+ new_file_name = f"{random_uuid}{file_extension}"
57
+ save_path= os.path.join(base_path, new_file_name)
58
+ shutil.copy(upload_audio_path,save_path)
59
+ else:
60
+ raise ValueError("Unsupported file format. Please upload an MP3 or WAV file.")
61
+ output_path=os.path.join(base_path, f"{file_name_without_extension}_{random_uuid}.wav")
62
+ remove_silence(save_path,output_path)
63
+ return output_path
64
+
65
+ def store_path_in_json(path, json_file_path="stored_paths.json"):
66
+ # Create a dictionary with the path and timestamp
67
+ entry = {
68
+ "path": path,
69
+ "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
70
+ }
71
+
72
+ # If the JSON file doesn't exist, create it with an empty list
73
+ if not os.path.exists(json_file_path):
74
+ with open(json_file_path, 'w') as json_file:
75
+ json.dump([], json_file)
76
+
77
+ try:
78
+ # Read existing entries from the JSON file
79
+ with open(json_file_path, 'r') as json_file:
80
+ data = json.load(json_file)
81
+ except json.decoder.JSONDecodeError as e:
82
+ print(f"Error decoding JSON file: {e}")
83
+ print(f"Content of JSON file: {json_file.read()}")
84
+ raise # Reraise the exception after printing for further analysis
85
+
86
+ # Append the new entry to the list
87
+ data.append(entry)
88
+
89
+ # Write the updated list back to the JSON file
90
+ with open(json_file_path, 'w') as json_file:
91
+ json.dump(data, json_file, indent=2)
92
+
93
+ # print(f"Path '{path}' stored in '{json_file_path}' with timestamp '{entry['timestamp']}'.")
94
+
95
+ import os
96
+ import json
97
+ from datetime import datetime, timedelta
98
+
99
+ def delete_old_files(json_filename, max_age_hours):
100
+ # Load JSON data
101
+ if os.path.exists(json_filename):
102
+ with open(json_filename, 'r') as json_file:
103
+ data = json.load(json_file)
104
+ else:
105
+ # No data in the JSON file, nothing to delete
106
+ return
107
+
108
+ # Get the current date and time
109
+ now = datetime.now()
110
+
111
+ # Loop through the entries in the JSON file
112
+ updated_data = []
113
+ for entry in data:
114
+ path = entry["path"]
115
+ timestamp_str = entry["timestamp"]
116
+ creation_date = datetime.strptime(timestamp_str, '%Y-%m-%d %H:%M:%S')
117
+
118
+ # Check if the file is older than the specified max age in hours
119
+ if (now - creation_date).total_seconds() / 3600 > max_age_hours:
120
+ # Delete the file if it exists
121
+ if os.path.exists(path):
122
+ os.remove(path)
123
+
124
+ # Skip this entry in the updated data
125
+ continue
126
+
127
+ # Keep the entry in the updated data
128
+ updated_data.append(entry)
129
+
130
+ # Save the updated JSON data
131
+ with open(json_filename, 'w') as json_file:
132
+ json.dump(updated_data, json_file, indent=2)
133
+
134
+
135
+ import subprocess
136
+
137
+ def calculate_duration(file_path):
138
+ # Calculate the duration of an audio or video file using ffprobe
139
+ ffprobe_command = f"ffprobe -i {file_path} -show_entries format=duration -v quiet -of csv=p=0"
140
+ duration_string = subprocess.check_output(ffprobe_command, shell=True, text=True)
141
+ duration = float(duration_string)
142
+ return duration
143
+
144
+
145
+
146
+
147
+
148
+
149
+ import subprocess
150
+ import json
151
+ import os
152
+
153
+
154
+
155
+
156
+
157
+
158
+ def process_audio(audio_file):
159
+ # Process the uploaded audio file
160
+ output_audio_file= process_file(audio_file.name)
161
+
162
+ # Store the processed file path in a JSON file
163
+ store_path_in_json(output_audio_file)
164
+
165
+ # Delete files older than 24 hours
166
+ delete_old_files("stored_paths.json", max_age_hours=24)
167
+ before=calculate_duration(audio_file)
168
+ after=calculate_duration(output_audio_file)
169
+ text=f"Duration before: {before:.2f} seconds, Duration after: {after:.2f} seconds"
170
+ return output_audio_file,text
171
+
172
+
173
+
174
+ demo = gr.Interface(process_audio,
175
+ [gr.File(label="Upload Audio")],
176
+ [gr.File(label="Download Audio File"),gr.Textbox(label="Duration")],
177
+ cache_examples=True)
178
+
179
+ demo.launch(debug=True)
180
+
181
+