MySafeCode commited on
Commit
f3a11b4
·
verified ·
1 Parent(s): 0f495ea

Update a.py

Browse files
Files changed (1) hide show
  1. a.py +372 -46
a.py CHANGED
@@ -1,53 +1,379 @@
1
  import gradio as gr
2
- from yt_dlp import YoutubeDL
3
  import os
4
- from pydub import AudioSegment
 
 
 
 
5
 
6
- DOWNLOADS_FOLDER = "downloads"
7
- os.makedirs(DOWNLOADS_FOLDER, exist_ok=True)
 
8
 
9
- def download_soundcloud(url, file_format, duration_sec):
10
- # Download best audio first (usually m4a)
11
- ydl_opts = {
12
- 'format': 'bestaudio/best',
13
- 'outtmpl': os.path.join(DOWNLOADS_FOLDER, '%(title)s.%(ext)s')
14
- }
15
-
16
- with YoutubeDL(ydl_opts) as ydl:
17
- info = ydl.extract_info(url, download=True)
18
-
19
- original_file = os.path.join(DOWNLOADS_FOLDER, f"{info['title']}.{info['ext']}")
20
-
21
- # Load audio and trim to duration
22
- audio = AudioSegment.from_file(original_file)
23
- duration_ms = min(len(audio), int(duration_sec * 1000))
24
- trimmed_audio = audio[:duration_ms]
25
-
26
- # Determine output file path
27
- if file_format.lower() == "mp3":
28
- output_file = os.path.splitext(original_file)[0] + ".mp3"
29
- trimmed_audio.export(output_file, format="mp3")
30
- elif file_format.lower() == "opus":
31
- output_file = os.path.splitext(original_file)[0] + ".opus"
32
- trimmed_audio.export(output_file, format="opus")
33
- else: # keep original format
34
- output_file = os.path.splitext(original_file)[0] + f".{info['ext']}"
35
- trimmed_audio.export(output_file, format=info['ext'])
36
-
37
- return output_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # Gradio interface
40
- with gr.Blocks() as iface:
41
- url_input = gr.Textbox(label="SoundCloud URL", value="https://soundcloud.com/antonio-antetomaso/mutiny-on-the-bounty-closing-titles-cover")
42
- format_choice = gr.Dropdown(choices=["mp3", "m4a", "opus"], value="mp3", label="Select format")
43
- duration_slider = gr.Slider(minimum=5, maximum=300, value=30, step=5, label="Duration (seconds)")
44
- download_button = gr.Button("Download")
45
- download_file = gr.File(label="Download your track")
46
-
47
- download_button.click(
48
- fn=download_soundcloud,
49
- inputs=[url_input, format_choice, duration_slider],
50
- outputs=download_file
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  )
52
 
53
- iface.launch(show_error=True)
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
 
2
  import os
3
+ import zipfile
4
+ import tempfile
5
+ import shutil
6
+ from pathlib import Path
7
+ import mimetypes
8
 
9
+ # Create uploads directory
10
+ UPLOADS_FOLDER = "uploads"
11
+ os.makedirs(UPLOADS_FOLDER, exist_ok=True)
12
 
13
+ def process_file(file_obj, file_name, action):
14
+ """
15
+ Process uploaded file: return original or create zip
16
+ """
17
+ if not file_obj:
18
+ return None, "❌ No file uploaded"
19
+
20
+ try:
21
+ # Save uploaded file temporarily
22
+ temp_dir = tempfile.mkdtemp()
23
+ original_path = os.path.join(temp_dir, file_name or os.path.basename(file_obj.name))
24
+
25
+ # Copy file to temp location
26
+ shutil.copy2(file_obj.name, original_path)
27
+
28
+ if action == "original":
29
+ # Return original file
30
+ return original_path, f"✅ Ready to download: {os.path.basename(original_path)}"
31
+
32
+ elif action == "zip":
33
+ # Create zip file
34
+ base_name = os.path.splitext(os.path.basename(original_path))[0]
35
+ zip_path = os.path.join(temp_dir, f"{base_name}.zip")
36
+
37
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
38
+ zipf.write(original_path, os.path.basename(original_path))
39
+
40
+ return zip_path, f"✅ Zipped as: {os.path.basename(zip_path)}"
41
+
42
+ elif action == "zip_with_password":
43
+ # Create password-protected zip (requires pyminizip)
44
+ try:
45
+ import pyminizip
46
+ base_name = os.path.splitext(os.path.basename(original_path))[0]
47
+ zip_path = os.path.join(temp_dir, f"{base_name}_protected.zip")
48
+
49
+ # Compress with password
50
+ pyminizip.compress(
51
+ original_path,
52
+ None,
53
+ zip_path,
54
+ "password123", # Default password
55
+ 5 # Compression level
56
+ )
57
+ return zip_path, f"✅ Password-protected zip created (password: password123)"
58
+
59
+ except ImportError:
60
+ return None, "❌ pyminizip not installed. Install with: pip install pyminizip"
61
+
62
+ else:
63
+ return None, "❌ Invalid action selected"
64
+
65
+ except Exception as e:
66
+ return None, f"❌ Error: {str(e)}"
67
+
68
+ def process_multiple_files(files, action):
69
+ """
70
+ Process multiple uploaded files
71
+ """
72
+ if not files:
73
+ return None, "❌ No files uploaded"
74
+
75
+ try:
76
+ temp_dir = tempfile.mkdtemp()
77
+
78
+ if action == "individual":
79
+ # Create zip containing all files
80
+ zip_path = os.path.join(temp_dir, "files.zip")
81
+
82
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
83
+ for file_obj in files:
84
+ file_path = file_obj.name
85
+ zipf.write(file_path, os.path.basename(file_path))
86
+
87
+ return zip_path, f"✅ Created zip with {len(files)} files"
88
+
89
+ elif action == "separate":
90
+ # Create separate zips for each file
91
+ zip_path = os.path.join(temp_dir, "separate_files.zip")
92
+
93
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
94
+ for file_obj in files:
95
+ file_path = file_obj.name
96
+ # Create individual zip first
97
+ individual_zip = os.path.join(temp_dir, f"{os.path.splitext(os.path.basename(file_path))[0]}.zip")
98
+ with zipfile.ZipFile(individual_zip, 'w', zipfile.ZIP_DEFLATED) as ind_zip:
99
+ ind_zip.write(file_path, os.path.basename(file_path))
100
+ # Add individual zip to main zip
101
+ zipf.write(individual_zip, os.path.basename(individual_zip))
102
+
103
+ return zip_path, f"✅ Created zip with {len(files)} individual zips"
104
+
105
+ else:
106
+ return None, "❌ Invalid action selected"
107
+
108
+ except Exception as e:
109
+ return None, f"❌ Error: {str(e)}"
110
 
111
+ def get_file_info(file_obj):
112
+ """Get information about uploaded file"""
113
+ if not file_obj:
114
+ return "No file selected"
115
+
116
+ try:
117
+ file_path = file_obj.name
118
+ file_size = os.path.getsize(file_path)
119
+ file_ext = os.path.splitext(file_path)[1].lower()
120
+
121
+ # Get file type
122
+ mime_type, _ = mimetypes.guess_type(file_path)
123
+ file_type = mime_type.split('/')[0] if mime_type else "Unknown"
124
+
125
+ info = f"""
126
+ 📄 **File Information:**
127
+
128
+ **Name:** {os.path.basename(file_path)}
129
+ **Size:** {file_size:,} bytes ({file_size/1024:.2f} KB)
130
+ **Extension:** {file_ext}
131
+ **Type:** {file_type}
132
+ **Path:** {file_path}
133
+ """
134
+
135
+ return info
136
+
137
+ except Exception as e:
138
+ return f"❌ Error getting file info: {str(e)}"
139
+
140
+ # Create Gradio interface
141
+ with gr.Blocks(title="File Upload & Download Manager", theme=gr.themes.Soft()) as iface:
142
+
143
+ gr.Markdown("# 📁 File Upload & Download Manager")
144
+ gr.Markdown("Upload files and download them as original or zipped")
145
+
146
+ with gr.Tabs():
147
+ # Single File Tab
148
+ with gr.Tab("Single File"):
149
+ with gr.Row():
150
+ with gr.Column(scale=2):
151
+ single_file = gr.File(
152
+ label="Upload a File",
153
+ file_count="single"
154
+ )
155
+
156
+ file_name_input = gr.Textbox(
157
+ label="Custom Filename (optional)",
158
+ placeholder="Leave empty to keep original name...",
159
+ info="Enter a custom name for the downloaded file"
160
+ )
161
+
162
+ single_action = gr.Radio(
163
+ choices=[
164
+ ("Download Original", "original"),
165
+ ("Download as ZIP", "zip"),
166
+ ("Password-protected ZIP", "zip_with_password")
167
+ ],
168
+ label="Select Action",
169
+ value="original"
170
+ )
171
+
172
+ single_btn = gr.Button("Process File", variant="primary")
173
+
174
+ with gr.Column(scale=1):
175
+ file_info = gr.Markdown(label="File Information")
176
+ single_status = gr.Textbox(label="Status", interactive=False)
177
+ single_download = gr.File(label="Download Processed File", interactive=False)
178
+
179
+ # Update file info when file is uploaded
180
+ single_file.change(
181
+ fn=get_file_info,
182
+ inputs=[single_file],
183
+ outputs=file_info
184
+ )
185
+
186
+ # Multiple Files Tab
187
+ with gr.Tab("Multiple Files"):
188
+ with gr.Row():
189
+ with gr.Column(scale=2):
190
+ multi_files = gr.File(
191
+ label="Upload Multiple Files",
192
+ file_count="multiple",
193
+ file_types=["image", "video", "audio", "text", "pdf", ".zip"]
194
+ )
195
+
196
+ multi_action = gr.Radio(
197
+ choices=[
198
+ ("Combine all files into one ZIP", "individual"),
199
+ ("Create separate ZIPs for each file", "separate")
200
+ ],
201
+ label="Select Action",
202
+ value="individual"
203
+ )
204
+
205
+ multi_btn = gr.Button("Process Files", variant="primary")
206
+
207
+ with gr.Column(scale=1):
208
+ multi_status = gr.Textbox(label="Status", interactive=False)
209
+ multi_download = gr.File(label="Download Processed Files", interactive=False)
210
+
211
+ # Batch Processing Tab
212
+ with gr.Tab("Batch Processing"):
213
+ with gr.Row():
214
+ with gr.Column():
215
+ gr.Markdown("### Upload Multiple Files for Batch Processing")
216
+
217
+ batch_files = gr.File(
218
+ label="Upload Files",
219
+ file_count="multiple",
220
+ file_types=None # All file types
221
+ )
222
+
223
+ batch_options = gr.CheckboxGroup(
224
+ choices=[
225
+ "Create individual ZIPs",
226
+ "Create combined ZIP",
227
+ "Rename with timestamp",
228
+ "Add to existing ZIP"
229
+ ],
230
+ label="Processing Options",
231
+ value=["Create combined ZIP"]
232
+ )
233
+
234
+ with gr.Row():
235
+ batch_format = gr.Dropdown(
236
+ choices=[".zip", ".7z", ".tar.gz"],
237
+ value=".zip",
238
+ label="Archive Format"
239
+ )
240
+
241
+ compression_level = gr.Slider(
242
+ minimum=1,
243
+ maximum=9,
244
+ value=6,
245
+ step=1,
246
+ label="Compression Level"
247
+ )
248
+
249
+ batch_btn = gr.Button("Process Batch", variant="primary", size="lg")
250
+
251
+ with gr.Column():
252
+ batch_status = gr.Textbox(label="Status", interactive=False, lines=3)
253
+ batch_download = gr.File(label="Download Results", interactive=False)
254
+
255
+ # Instructions
256
+ with gr.Accordion("📖 Instructions & Features", open=False):
257
+ gr.Markdown("""
258
+ ## How to Use:
259
+
260
+ ### Single File Tab:
261
+ 1. **Upload** a single file
262
+ 2. (Optional) Enter a custom filename
263
+ 3. **Choose action**: Download original, as ZIP, or password-protected ZIP
264
+ 4. Click **Process File**
265
+
266
+ ### Multiple Files Tab:
267
+ 1. **Upload** multiple files (Ctrl+Click to select multiple)
268
+ 2. **Choose action**: Combine into one ZIP or create separate ZIPs
269
+ 3. Click **Process Files**
270
+
271
+ ### Batch Processing Tab:
272
+ 1. **Upload** multiple files
273
+ 2. **Select processing options**
274
+ 3. Choose archive format and compression level
275
+ 4. Click **Process Batch**
276
+
277
+ ## Features:
278
+ - ✅ Single file upload and download
279
+ - ✅ Multiple file upload and batch processing
280
+ - ✅ ZIP file creation with compression
281
+ - ✅ Password-protected ZIPs (requires pyminizip)
282
+ - ✅ File information display
283
+ - ✅ Custom filename support
284
+ - ✅ Multiple archive formats
285
+
286
+ ## Notes:
287
+ - Files are processed in temporary storage
288
+ - Original files are not modified
289
+ - Large files may take time to process
290
+ - Password for protected ZIPs: `password123`
291
+ """)
292
+
293
+ # Connect events
294
+ single_btn.click(
295
+ fn=process_file,
296
+ inputs=[single_file, file_name_input, single_action],
297
+ outputs=[single_download, single_status]
298
+ )
299
+
300
+ multi_btn.click(
301
+ fn=process_multiple_files,
302
+ inputs=[multi_files, multi_action],
303
+ outputs=[multi_download, multi_status]
304
+ )
305
+
306
+ # Batch processing function
307
+ def process_batch(files, options, format_type, compression):
308
+ if not files:
309
+ return None, "❌ No files uploaded"
310
+
311
+ try:
312
+ temp_dir = tempfile.mkdtemp()
313
+ results = []
314
+
315
+ # Process based on options
316
+ if "Create combined ZIP" in options:
317
+ zip_name = f"combined{format_type}"
318
+ zip_path = os.path.join(temp_dir, zip_name)
319
+
320
+ if format_type == ".zip":
321
+ with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED, compresslevel=compression) as zipf:
322
+ for file_obj in files:
323
+ file_path = file_obj.name
324
+ arcname = os.path.basename(file_path)
325
+ if "Rename with timestamp" in options:
326
+ import time
327
+ name, ext = os.path.splitext(arcname)
328
+ arcname = f"{name}_{int(time.time())}{ext}"
329
+ zipf.write(file_path, arcname)
330
+ results.append(zip_path)
331
+
332
+ if "Create individual ZIPs" in options:
333
+ for file_obj in files:
334
+ file_path = file_obj.name
335
+ base_name = os.path.splitext(os.path.basename(file_path))[0]
336
+ if "Rename with timestamp" in options:
337
+ import time
338
+ base_name = f"{base_name}_{int(time.time())}"
339
+
340
+ individual_zip = os.path.join(temp_dir, f"{base_name}{format_type}")
341
+
342
+ if format_type == ".zip":
343
+ with zipfile.ZipFile(individual_zip, 'w', zipfile.ZIP_DEFLATED, compresslevel=compression) as zipf:
344
+ zipf.write(file_path, os.path.basename(file_path))
345
+
346
+ results.append(individual_zip)
347
+
348
+ # If multiple results, create a final zip
349
+ if len(results) > 1:
350
+ final_zip = os.path.join(temp_dir, f"batch_results{format_type}")
351
+ with zipfile.ZipFile(final_zip, 'w', zipfile.ZIP_DEFLATED) as zipf:
352
+ for result in results:
353
+ zipf.write(result, os.path.basename(result))
354
+ output_file = final_zip
355
+ elif results:
356
+ output_file = results[0]
357
+ else:
358
+ return None, "⚠️ No processing options selected"
359
+
360
+ return output_file, f"✅ Processed {len(files)} file(s) with {len(options)} option(s)"
361
+
362
+ except Exception as e:
363
+ return None, f"❌ Error: {str(e)}"
364
+
365
+ batch_btn.click(
366
+ fn=process_batch,
367
+ inputs=[batch_files, batch_options, batch_format, compression_level],
368
+ outputs=[batch_download, batch_status]
369
  )
370
 
371
+ # Launch the app
372
+ if __name__ == "__main__":
373
+ iface.launch(
374
+ server_name="127.0.0.1",
375
+ server_port=7861, # Different port to avoid conflict
376
+ show_error=True,
377
+ share=False,
378
+ ssr_mode=False
379
+ )